会话超时后,Spring Security不会重定向到上次请求的页面登录

时间:2019-05-14 07:02:34

标签: java spring java-ee spring-security

我在我的应用程序中使用Spring Security 4.2.2.RELEASE。一旦发生超时,然后用户单击任何URL,它将被重定向到注销页面,一旦身份验证成功,它将重定向到默认的主页,而不是请求的页面。

Web xml如下:

<bean id="logoutSuccessHandler"
         class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">
         <property name="useReferer" value="true"/>
     </bean>


    <security:form-login
            login-page="/login"
            authentication-failure-url="/login_error"
            username-parameter="username"
            password-parameter="password"
            default-target-url="/home"
            always-use-default-target="false"
            />

一旦验证正确,我希望它重定向到请求的页面。我已经读过,Spring Security默认提供此功能。但是它没有用,所以我试图使用SimpleUrlLogoutSuccessHandler来实现。但是仍然找不到解决方法。那么,这里可能出什么问题了?

2 个答案:

答案 0 :(得分:0)

好吧,您需要实现SimpleUrlAuthenticationSuccessHandler。这可以帮助您处理重定向。

    <http>
    <intercept-url pattern="/login" access="permitAll"/>
    <intercept-url pattern="/**" access="isAuthenticated()"/>
    <form-login authentication-success-handler-ref="refererHandler" />
</http>

<beans:bean
  class="RefererRedirectionAuthenticationSuccessHandler"
  name="refererHandler"/>

并像这样实现:

    public class RefererRedirectionAuthenticationSuccessHandler 
  extends SimpleUrlAuthenticationSuccessHandler
  implements AuthenticationSuccessHandler {

    public RefererRedirectionAuthenticationSuccessHandler() {
        super();
        setUseReferer(true);
    }
    }

答案 1 :(得分:0)

首先启用并发会话控制支持是在web.xml中添加以下侦听器:

<listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
  </listener>

  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>

会话超时后,如果用户发送的会话ID过期的请求将被重定向到可配置的URL。 同样,如果用户发送的请求的会话ID尚未过期,但完全无效,则它们也将重定向到可配置的URL:security.xml

<session-management invalid-session-url="/sessionexpiredPage.htm" session-authentication-error-url="/forms/common/login.jsp?error=alreadyLoggedin" session-fixation-protection="none" >
            <concurrency-control expired-url="/sessionexpiredPage.htm" max-sessions="5" error-if-maximum-exceeded="true"  />
        </session-management>

对应的Java代码:

@Audit(option = "Session Expire", action = "Session Expired")
    @RequestMapping(value = "/sessionexpiredPage.htm")
    public ModelAndView sessionExpired(HttpSession session, HttpServletRequest request) {
        clLogger.logMethodEntry("sessionexpiredPage");
        ModelAndView model = new ModelAndView();
        String userId = (String) session.getAttribute("USER_ID");
        if(userId == null) {
            model.setViewName("sessionexpiredPage");
        }else {
            model.setViewName("getHomePage");
        }
        clLogger.logMethodExit("sessionexpiredPage");
        return model;

    }