添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Stack Overflow en español es un sitio de preguntas y respuestas para programadores y profesionales de la informática. Solo te toma un minuto registrarte.

Regístrate para unirte a esta comunidad

Estoy aprendiendo Spring Boot con un proyecto básico usando Spring Security, implementé la parte de autentificación y autorización, los usuarios pueden realizar las acciones que les corresponden según su rol. El problema ocurre al ingresar con cualquiera de los usuarios al 2do intento o después (inicio sesión con "user" , cierro la sesión, entro de nuevo con el mismo usuario y salta el error) hasta que me salta la página de error 403 de Acceso Denegado, pese a haber ingresado antes usando las mismas credenciales. Luego regreso de nuevo al login y trato de iniciar sesión de nuevo con el mismo usuario y ahora si me deja entrar. He colocado logs en mi clase que implementa AccessDeniedHandler y he visto que cuando ocurre el problema el objeto Authentication tiene valor null. Dejo el código de esa parte:

@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exc) throws IOException{
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){
        LOG.warning("**");
        LOG.warning("User: " + auth.getName() + " URI:" + request.getRequestURI() );
    } else {
        LOG.warning("******ERROR DE NULL******");
    response.sendRedirect("/errors/403");

Este es el código de la clase donde implemento la autentificación y autorización:

@Configuration

@EnableWebSecurity public class SecurityConfig{

@Autowired
private UserDetailsService userDetailsService;
public BCryptPasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
@Autowired
public void configurerGlobal(AuthenticationManagerBuilder build) throws Exception{
    build.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
@Bean
public AccessDeniedHandler accessDeniedHandler() {
    return new CustomAccessDeniedHandler();
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
    http.
            authorizeHttpRequests(authorize -> authorize
                    .requestMatchers("/editar/**","/agregar/**","/eliminar/**","/guardar/**").hasRole("ADMIN")
                    .requestMatchers("/").hasAnyRole("USER","ADMIN")
                    .requestMatchers("/errors/403").permitAll()
    http.formLogin(form -> form
                    .loginPage("/login")
                    .permitAll())
            .exceptionHandling()
            .accessDeniedHandler(accessDeniedHandler())
    return http.build();

Adjunto algunas partes de los logs de la consola:

11:01 TRACE 13188 --- [nio-8080-exec-6] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
11:01 TRACE 13188 --- [nio-8080-exec-6] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
11:01  WARN 13188 --- [nio-8080-exec-6] c.com.gm.web.CustomAccessDeniedHandler   : ******ERROR DE NULL******
11:01 TRACE 13188 --- [nio-8080-exec-6] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match request to [Is Secure]
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter@1957510f, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@228fcaa6, org.springframework.security.web.context.SecurityContextHolderFilter@6991a41f, org.springframework.security.web.header.HeaderWriterFilter@751207e, org.springframework.security.web.csrf.CsrfFilter@595dcd23, org.springframework.security.web.authentication.logout.LogoutFilter@32b382fb, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3a329ad6, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@2d25800, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@13a85a66, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@c45100b, org.springframework.security.web.access.ExceptionTranslationFilter@398f12fd, org.springframework.security.web.access.intercept.AuthorizationFilter@5abc2be8]] (1/1)
11:01 DEBUG 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Securing GET /errors/403
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking DisableEncodeUrlFilter (1/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking WebAsyncManagerIntegrationFilter (2/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking SecurityContextHolderFilter (3/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking HeaderWriterFilter (4/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking CsrfFilter (5/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.csrf.CsrfFilter         : Did not protect against CSRF since request did not match CsrfNotRequired [TRACE, HEAD, GET, OPTIONS]
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking LogoutFilter (6/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.s.w.a.logout.LogoutFilter            : Did not match request to Ant [pattern='/logout', POST]
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking UsernamePasswordAuthenticationFilter (7/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] w.a.UsernamePasswordAuthenticationFilter : Did not match request to Ant [pattern='/login', POST]
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking RequestCacheAwareFilter (8/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.s.w.s.HttpSessionRequestCache        : matchingRequestParameterName is required for getMatchingRequest to lookup a value, but not provided
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking SecurityContextHolderAwareRequestFilter (9/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking AnonymousAuthenticationFilter (10/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking ExceptionTranslationFilter (11/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Invoking AuthorizationFilter (12/12)
11:01 TRACE 13188 --- [nio-8080-exec-2] estMatcherDelegatingAuthorizationManager : Authorizing SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@345f5a7]
11:01 TRACE 13188 --- [nio-8080-exec-2] estMatcherDelegatingAuthorizationManager : Checking authorization on SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@345f5a7] using org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer$$Lambda$1273/0x0000000801430a50@540e9212
11:01 DEBUG 13188 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : Secured GET /errors/403
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match request to [Is Secure]
11:01 TRACE 13188 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : Did not find SecurityContext in HttpSession F455BE139B6F821CD20ED0B9E54C17CB using the SPRING_SECURITY_CONTEXT session attribute
11:01 TRACE 13188 --- [nio-8080-exec-2] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
11:01 TRACE 13188 --- [nio-8080-exec-2] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
11:01 TRACE 13188 --- [nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=F455BE139B6F821CD20ED0B9E54C17CB], Granted Authorities=[ROLE_ANONYMOUS]]
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Trying to match request against DefaultSecurityFilterChain [RequestMatcher=any request, Filters=[org.springframework.security.web.session.DisableEncodeUrlFilter@1957510f, org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@228fcaa6, org.springframework.security.web.context.SecurityContextHolderFilter@6991a41f, org.springframework.security.web.header.HeaderWriterFilter@751207e, org.springframework.security.web.csrf.CsrfFilter@595dcd23, org.springframework.security.web.authentication.logout.LogoutFilter@32b382fb, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@3a329ad6, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@2d25800, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@13a85a66, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@c45100b, org.springframework.security.web.access.ExceptionTranslationFilter@398f12fd, org.springframework.security.web.access.intercept.AuthorizationFilter@5abc2be8]] (1/1)
11:01 DEBUG 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Securing GET /favicon.ico
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking DisableEncodeUrlFilter (1/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking WebAsyncManagerIntegrationFilter (2/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking SecurityContextHolderFilter (3/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking HeaderWriterFilter (4/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking CsrfFilter (5/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.csrf.CsrfFilter         : Did not protect against CSRF since request did not match CsrfNotRequired [TRACE, HEAD, GET, OPTIONS]
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking LogoutFilter (6/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.s.w.a.logout.LogoutFilter            : Did not match request to Ant [pattern='/logout', POST]
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking UsernamePasswordAuthenticationFilter (7/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] w.a.UsernamePasswordAuthenticationFilter : Did not match request to Ant [pattern='/login', POST]
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking RequestCacheAwareFilter (8/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.s.w.s.HttpSessionRequestCache        : matchingRequestParameterName is required for getMatchingRequest to lookup a value, but not provided
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking SecurityContextHolderAwareRequestFilter (9/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking AnonymousAuthenticationFilter (10/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking ExceptionTranslationFilter (11/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.security.web.FilterChainProxy        : Invoking AuthorizationFilter (12/12)
11:01 TRACE 13188 --- [nio-8080-exec-8] estMatcherDelegatingAuthorizationManager : Authorizing SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterRequest@3bf390ac]
11:01 TRACE 13188 --- [nio-8080-exec-8] estMatcherDelegatingAuthorizationManager : Denying request since did not find matching RequestMatcher
11:01 TRACE 13188 --- [nio-8080-exec-8] w.c.HttpSessionSecurityContextRepository : Did not find SecurityContext in HttpSession F455BE139B6F821CD20ED0B9E54C17CB using the SPRING_SECURITY_CONTEXT session attribute
11:01 TRACE 13188 --- [nio-8080-exec-8] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
11:01 TRACE 13188 --- [nio-8080-exec-8] .s.s.w.c.SupplierDeferredSecurityContext : Created SecurityContextImpl [Null authentication]
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=F455BE139B6F821CD20ED0B9E54C17CB], Granted Authorities=[ROLE_ANONYMOUS]]
11:01 TRACE 13188 --- [nio-8080-exec-8] o.s.s.w.a.ExceptionTranslationFilter     : Sending AnonymousAuthenticationToken [Principal=anonymousUser, Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=F455BE139B6F821CD20ED0B9E54C17CB], Granted Authorities=[ROLE_ANONYMOUS]] to authentication entry point since access is denied
org.springframework.security.access.AccessDeniedException: Access Denied

Por los logs, también probé averiguando si el problema estaba relacionado al Invalid CSRF o al SecurityContextImpl [Null authentication]. ¿Alguna ayuda de a qué se deba el error?

¡Gracias por contribuir en StackOverflow en español con una respuesta!

  • Por favor, asegúrate de responder a la pregunta. ¡Proporciona información y comparte tu investigación!

Pero evita

  • Pedir ayuda o aclaraciones, o responder a otras respuestas.
  • Hacer declaraciones basadas en opiniones; asegúrate de respaldarlas con referencias o con tu propia experiencia personal.

Para obtener más información, consulta nuestros consejos sobre cómo escribir grandes respuestas.