0

Tengo Spring Security 5 en Spring Boot 2.0.3

@Component
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                        AuthenticationException authException) throws IOException, ServletException {

        response.setHeader("WWW-Authenticate", "Basic realm= " + getRealmName());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        //response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        PrintWriter writer = response.getWriter();

        writer.println("Http Status 401 " + authException.getMessage());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        setRealmName("Proyecto");

        super.afterPropertiesSet();
    }
}

configuración de seguridad:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationEntryPoint entryPoint;

    private Usuario usuario;

    @Bean
    public UserDetailsService userDetailsService() {
        return new MyUsuarioDetalleService();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder())
                .withUser(usuario.getUsuarioNombre())
                .password(passwordEncoder().encode(usuario.getClave()))
                .roles(usuario.getRol().getNombre());

    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        final CustomFilter tokenFilter = new CustomFilter();
        http.addFilterBefore(tokenFilter, BasicAuthenticationFilter.class);
        http
                .authorizeRequests()
                .anyRequest().hasRole("admin")

                .and()
                .httpBasic()
                .authenticationEntryPoint(entryPoint);

        http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);

    }
}

Filtro personalziado :

public class CustomFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        chain.doFilter(request, response);

    }

}

Servicio de detalles de usuario :

@Service
public class MyUsuarioDetalleService implements UserDetailsService {

    @Autowired
    private UsuarioRepository usuarioRepository;

    @SuppressWarnings("unchecked")
    @Override
    public UserDetails loadUserByUsername(String usuarionombre) throws UsernameNotFoundException {

        Usuario usuario = usuarioRepository.findByUsuarionombre(usuarionombre);

        UserBuilder builder = null;

        if (usuario != null) {

            builder = org.springframework.security.core.userdetails.User.withUsername(usuario.getUsuarioNombre());
            builder.password(new BCryptPasswordEncoder().encode(usuario.getClave()));

            builder.authorities(getGrantedAuthorities((Collection<Rol>) usuario));
            //throw new UsernameNotFoundException("Nombre Usuario" + usuarionombre+" No encontrado ");
        } else {
            throw new UsernameNotFoundException("Nombre Usuario" + usuarionombre + " No encontrado ");
        }

        return builder.build();
        //return new org.springframework.security.core.userdetails.User(usuario.getUsuarioNombre(),usuario.getClave(),getGrantedAuthorities(usuario));
    }

    private Collection<? extends GrantedAuthority> getGrantedAuthorities(Collection<Rol> roles) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Rol role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getNombre()));

        }

        return authorities;

    }
}

la salida del error es el siguiente :

  org.springframework.beans.factory.BeanCreationException: Error
  creating bean with name 'springSecurityFilterChain' defined in class
  path resource
  [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]:
  Bean instantiation via factory method failed; nested exception is
  org.springframework.beans.BeanInstantiationException: Failed to
  instantiate [javax.servlet.Filter]: Factory method
  'springSecurityFilterChain' threw exception; nested exception is
  java.lang.NullPointerException  at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1254)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1103)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:304)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
  ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]   at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
  ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]   at
  org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
  ~[spring-boot-2.0.3.BUILD-SNAPSHOT.jar:2.0.3.BUILD-SNAPSHOT]    at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
  [spring-boot-2.0.3.BUILD-SNAPSHOT.jar:2.0.3.BUILD-SNAPSHOT]     at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
  [spring-boot-2.0.3.BUILD-SNAPSHOT.jar:2.0.3.BUILD-SNAPSHOT]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
  [spring-boot-2.0.3.BUILD-SNAPSHOT.jar:2.0.3.BUILD-SNAPSHOT]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
  [spring-boot-2.0.3.BUILD-SNAPSHOT.jar:2.0.3.BUILD-SNAPSHOT]     at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
  [spring-boot-2.0.3.BUILD-SNAPSHOT.jar:2.0.3.BUILD-SNAPSHOT]     at
  com.ventura.app.Application.main(Application.java:10) [classes/:na]
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  ~[na:1.8.0_131]     at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  ~[na:1.8.0_131]     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  ~[na:1.8.0_131]     at java.lang.reflect.Method.invoke(Unknown Source)
  ~[na:1.8.0_131]     at
  org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
  [spring-boot-devtools-2.0.3.BUILD-SNAPSHOT.jar:2.0.3.BUILD-SNAPSHOT]
  Caused by: org.springframework.beans.BeanInstantiationException:
  Failed to instantiate [javax.servlet.Filter]: Factory method
  'springSecurityFilterChain' threw exception; nested exception is
  java.lang.NullPointerException  at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     at
  org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     ... 25 common frames
  omitted Caused by: java.lang.NullPointerException: null     at
  com.ventura.app.config.SpringSecurityConfiguration.configure(SpringSecurityConfiguration.java:49)
  ~[classes/:na]  at
  org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.authenticationManager(WebSecurityConfigurerAdapter.java:265)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.getHttp(WebSecurityConfigurerAdapter.java:201)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:321)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter.init(WebSecurityConfigurerAdapter.java:92)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  com.ventura.app.config.SpringSecurityConfiguration$$EnhancerBySpringCGLIB$$a15102ea.init(<generated>)
  ~[classes/:na]  at
  org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$fd4731c2.CGLIB$springSecurityFilterChain$5(<generated>)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$fd4731c2$$FastClassBySpringCGLIB$$3829ce79.invoke(<generated>)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
  ~[spring-core-5.0.6.RELEASE.jar:5.0.6.RELEASE]  at
  org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
  ~[spring-context-5.0.6.RELEASE.jar:5.0.6.RELEASE]   at
  org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$fd4731c2.springSecurityFilterChain(<generated>)
  ~[spring-security-config-5.0.5.RELEASE.jar:5.0.5.RELEASE]   at
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  ~[na:1.8.0_131]     at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  ~[na:1.8.0_131]     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  ~[na:1.8.0_131]     at java.lang.reflect.Method.invoke(Unknown Source)
  ~[na:1.8.0_131]     at
  org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
  ~[spring-beans-5.0.6.RELEASE.jar:5.0.6.RELEASE]     ... 26 common frames
  omitted
2
  • ¿Pudiste resolverlo?
    – Legna
    Commented el 5 jun. 2018 a las 14:37
  • si pude resolverlo pero si hay otra solución puedes publicar también gracias
    – Libra2880
    Commented el 5 jun. 2018 a las 17:04

1 respuesta 1

0

La solución esta en la siguientes lineas código

@Override
public UserDetails loadUserByUsername(String usuarionombre) throws UsernameNotFoundException {

    Usuario usuario=usuarioRepository.findByUsuarionombre(usuarionombre);

    UserBuilder  builder=null;

    if(usuario!=null){

        builder=org.springframework.security.core.userdetails.User.withUsername(usuario.getUsuarioNombre());
        builder.password(new BCryptPasswordEncoder().encode(usuario.getClave()));
        builder.roles(usuario.getRol().getNombre());
        //builder.authorities(getGrantedAuthorities((Collection<Rol>) usuario));

    }else{
        throw new UsernameNotFoundException("Nombre Usuario" + usuarionombre+" No encontrado ");
    }

    return builder.build();

}

Configuración de seguridad:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Autowired
    private AuthenticationEntryPoint entryPoint;



    private Usuario usuario;


     @Bean
      public UserDetailsService userDetailsService() {
        return new MyUsuarioDetalleService();
      };

      @Bean
      public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
      };

    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());



    }

@Override
    protected void configure(final HttpSecurity http) throws Exception {
        final CustomFilter tokenFilter = new CustomFilter();
        http.addFilterBefore(tokenFilter, BasicAuthenticationFilter.class);
        http            
            .authorizeRequests()
            .antMatchers("/**").hasRole("admin")
            .anyRequest().hasRole("admin")

            .and()
            .httpBasic()
            .authenticationEntryPoint(entryPoint);

        http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);

    }




}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.