当前位置: 首页 > 知识库问答 >
问题:

Spring Security重定向到登录页面并在身份验证成功后终止会话

袁翰池
2023-03-14

我使用Spring Security 4.2.1来认证一个SpringMVC webapp。我有一个非常难以捉摸的问题,似乎有时工作,有时被打破(打破比它的工作)。

问题如下:

> < li>

在尝试登录时,AuthenticationProvider正确地验证了用户,并且我在日志中看到了验证成功(并且经过验证的用户具有所需的所有权限,等等,我可以在日志中看到它们)。

然后,框架似乎为用户清除了SecurityContextHolder,当它尝试加载登录页面时,就好像它们根本没有经过身份验证一样。

这当然会导致重定向回登录页面。

例外是如果我先显式注销。如果我去注销地址,我似乎可以在那之后登录。

我已经回顾了我的Spring Sec配置,并在其中更改了几天,仍然得到相同的结果。我对此失去了理智。

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
        .authorizeRequests()
            .antMatchers(
                "/link/go/*",
                "/pixel/download/*",
                "/favicon.ico",
                "/ping*").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/j_spring_security_check")
            .defaultSuccessUrl("/")
            .permitAll()
            .authenticationDetailsSource(new CustomAuthenticationDetailsSource())
            .and()
        .logout()
            .permitAll();
}

这是一个具有以下行为的基本控制器:

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/", method = RequestMethod.GET)
public String showIndex() {
    return "pages/index";
}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLogin(HttpServletRequest request, HttpServletResponse response) {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return "pages/login";
}

这是我正在使用的基本登录表单(百里香叶):

<form th:action="@{/j_spring_security_check}" method="post" autocomplete="off">
      <div class="group">
        <input type="text" id="username" name="username" autocomplete="off" required="required" /><span class="highlight"></span><span class="bar"></span>
        <label>Username</label>
        <div th:if="${param.error}" class="alert alert-error">    
            Invalid username and password.
        </div>
        <div th:if="${param.logout}" class="alert alert-success"> 
            You have been logged out.
        </div>
      </div>
      <div class="group">
        <input type="password" id="password" name="password" autocomplete="off" required="required" /><span class="highlight"></span><span class="bar"></span>
        <label>Password</label>
      </div>
      <div class="group">
        <input type="text" id="token" name="token" autocomplete="off" required="required" /><span class="highlight"></span><span class="bar"></span>
        <label>Tracker Token</label>
      </div>
      <button type="submit" class="button buttonBlue">Log in
        <div class="ripples buttonRipples"><span class="ripplesCircle"></span></div>
    </button>
</form>

这些是非常相关的日志(成功的身份验证之后是会话破坏和访问拒绝的循环)。我记录了大量的上下文,但我指出了关键部分(用*),这样您就不必挖得太难了。

2017-01-24 10:32:25,386 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.FilterChainProxy: /j_spring_security_check at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-01-24 10:32:25,386 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.FilterChainProxy: /j_spring_security_check at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-01-24 10:32:25,386 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository: HttpSession returned null object for SPRING_SECURITY_CONTEXT

*2017-01-24 10:32:25,386 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository: No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@1ff52ee9. A new one will be created.

2017-01-24 10:32:25,386 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.FilterChainProxy: /j_spring_security_check at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-01-24 10:32:25,386 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.header.writers.HstsHeaderWriter: Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@362f8994
2017-01-24 10:32:25,386 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.FilterChainProxy: /j_spring_security_check at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
2017-01-24 10:32:25,387 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.FilterChainProxy: /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2017-01-24 10:32:25,387 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Checking match of request : '/j_spring_security_check'; against '/logout'
2017-01-24 10:32:25,387 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.FilterChainProxy: /j_spring_security_check at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'

*2017-01-24 10:32:25,387 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Checking match of request : '/j_spring_security_check'; against '/j_spring_security_check'
*2017-01-24 10:32:25,387 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter: Request is to process authentication
*2017-01-24 10:32:25,388 [http-nio-8080-exec-4] DEBUG org.springframework.security.authentication.ProviderManager: Authentication attempt using com.company.project.tracker.config.security.CustomAuthenticationProvider

2017-01-24 10:32:25,729 [http-nio-8080-exec-4] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory: Returning cached instance of singleton bean 'delegatingApplicationListener'
2017-01-24 10:32:25,729 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy: Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy@473f5bae
2017-01-24 10:32:25,729 [http-nio-8080-exec-4] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory: Returning cached instance of singleton bean 'delegatingApplicationListener'
2017-01-24 10:32:25,729 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy: Delegating to org.springframework.security.web.csrf.CsrfAuthenticationStrategy@213137f3

*2017-01-24 10:32:25,730 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter: Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@d7d972f2: Principal: com.company.project.tracker.config.security.Principal@50525059; Credentials: [PROTECTED]; Authenticated: true; Details: com.company.project.tracker.config.security.CustomAuthenticationDetailsSource$CustomAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: BFDA41C5C1883560BACC75BB353001CA; Granted Authorities: com.company.project.tracker.config.security.UserAuthority@78746e0b

2017-01-24 10:32:25,730 [http-nio-8080-exec-4] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory: Returning cached instance of singleton bean 'delegatingApplicationListener'

*2017-01-24 10:32:25,730 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler: Redirecting to DefaultSavedRequest Url: http://localhost:8080/tracker
*2017-01-24 10:32:25,730 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.DefaultRedirectStrategy: Redirecting to 'http://localhost:8080/tracker'
*2017-01-24 10:32:25,730 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository: SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@d7d972f2: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@d7d972f2: Principal: com.company.project.tracker.config.security.Principal@50525059; Credentials: [PROTECTED]; Authenticated: true; Details: com.company.project.tracker.config.security.CustomAuthenticationDetailsSource$CustomAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: BFDA41C5C1883560BACC75BB353001CA; Granted Authorities: com.company.project.tracker.config.security.UserAuthority@78746e0b' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@1ff52ee9
*2017-01-24 10:32:25,730 [http-nio-8080-exec-4] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter: SecurityContextHolder now cleared, as request processing completed

我认为这是它开始处理认证请求的截止点(也就是它出错的地方)。

2017-01-24 10:32:25,733 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'

*2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository: No HttpSession currently exists
*2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository: No SecurityContext was available from the HttpSession: null. A new one will be created.

2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.header.writers.HstsHeaderWriter: Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@362f8994
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Request 'GET ' doesn't match 'POST /logout
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Request 'GET ' doesn't match 'POST /j_spring_security_check
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'

*2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter: Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'

2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.FilterChainProxy:  at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Request 'GET ' doesn't match 'POST /logout
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Checking match of request : ''; against '/link/go/*'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Checking match of request : ''; against '/pixel/download/*'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Checking match of request : ''; against '/favicon.ico'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher: Checking match of request : ''; against '/ping*'
2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor: Secure object: FilterInvocation: URL: ; Attributes: [authenticated]

*2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor: Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
*2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.access.vote.AffirmativeBased: Voter: org.springframework.security.web.access.expression.WebExpressionVoter@2cca1b0b, returned: -1
*2017-01-24 10:32:25,734 [http-nio-8080-exec-5] DEBUG org.springframework.security.web.access.ExceptionTranslationFilter: Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied

如您所见,当它返回到“/”地址时,会话消失了,存储在会话中的原始、正确的对象被一个匿名身份验证对象所取代,该对象显然无权访问“/”。我还包括了相应的响应和请求标头(通过Chrome),它们来自与上面日志相同的请求周期:

所有三个请求

任何帮助将不胜感激。我确信我在做一些愚蠢的事情。我已经使用这个框架多年了,甚至编写了大量的自定义组件,但这个让我彻底难倒了(实验的 1d)。如果它们有助于深入了解它,我可以提供任何其他文件或示例。

谢了。

共有1个答案

汝承载
2023-03-14

TRy添加http.csrf()。禁用();到您的代码。可能是CSRF过滤器拦截了您的请求。

我在你提供的日志中看到了过滤器调用。

 类似资料:
  • 我试图在登录symfony2应用程序后实现重定向,以便在我的用户是否有一个属性时重定向。我已在项目的Handler文件夹中创建了AuthenticationSuccessHandler.php类: 但是当我登录时,我得到一个错误: 注意:未定义的属性:Me\MyBundle\Handler\AuthenticationSuccessHandler::$router in/var/www/MyBun

  • 试图阻止来宾用户的路由。当有人点击时,它将检查用户是否以管理员身份登录。如果admin然后它工作正常,如果代理然后它重定向到登录页面,但如果我作为访客用户点击链接,它不会将我重定向到登录页面,而是显示一些错误: 路由中的错误异常。php第53行:尝试获取非对象的属性。 这是我的路线。php文件:

  • 我在auth中间件方面遇到了一些问题。我将中间件放在一个路由组中,并回滚了users表。我希望应用程序将我重定向到我的登录/搜索页面,但它没有这样做,它只是给了我“尝试获取非对象的属性”,它指的是我的仪表板视图中的函数(我不应该访问该函数)。 这是我的路线代码: 以下是我的观点: 另外,我不确定从数据库中删除用户是否意味着Laravel将自动删除用户会话。 谢谢你的帮助!

  • 我刚刚在这个论坛的帮助下添加了一个AuthenticationSuccessHandler,当用户通过fosuserbundle或fosfacebookbundle登录时,它在我的站点上实现了重定向。当用户完成或未完成配置文件时,重定向会发生变化,如果已经完成,我希望将它们重定向到以前的位置,这就是我使用referer变量的原因。 security.yml,我已在fos_facebook和form

  • 默认情况下,身份验证后的Spring Security会将您重定向到您之前尝试访问的受保护页面。 当我实现自己的成功处理器时 我不能达到同样的效果。我试图重定向到referer,但在本例中,referer是/en/login页面。 基本上: 用户尝试访问受保护的url 将用户重定向到页面 验证后,用户应再次重定向到 如何使用custom successHandler实现这一点?

  • 在不生成Laravel默认身份验证控制器的情况下,我创建了自己的登录和注册控制器。 我的路线是这样的 用于登录 登记 一切都很好。现在我需要一件事。每当我放置中间件时,一个未经身份验证的用户将被重定向到我的自定义登录页面路由到。 如何做到这一点?