由于会话过期,将用户重定向到最后一页

Posted

技术标签:

【中文标题】由于会话过期,将用户重定向到最后一页【英文标题】:Redirect user to last page due to session expired 【发布时间】:2017-06-19 18:40:24 【问题描述】:

如果会话由于长时间间隔而过期,我想将用户重定向到上次访问的页面。

但是,我通过referrer 属性以及发送到控制器的前端js 文件获取了URL,但控制器仍然无法将请求重定向到上次访问的URL。相反,它总是重定向到默认 URL:Login.js


var comesFromUrl  = document.referrer,
                    mySiteDomain = document.domain;
                    last_location = comesFromUrl,
                        current_location = document.URL;

                    // Check if cookie exists and if its value is not the current location
                    if(typeof last_location !== "undefined"
                       && last_location !== current_location) 
                        // Here is possible to choose if remove the cookie or refresh it. It's up to you.

                        window.location.href = last_location;
                    


                    this.sendNotification( publicLogin.ApplicationFacade.LOGIN_SUCCESS);

这是我的成功处理程序类。

public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException 
response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1);
        Object obj = authentication.getDetails();
        if (obj instanceof PublicUserInfo) 
            PublicUserInfo objUser = (PublicUserInfo) obj;

            String cookieData = "userId|~~~" + objUser.getGuid() + "|~~~|instituteId|~~~" + objUser.getInstitutionId();

            Cookie ck= new Cookie("user_info", cookieData);

            ck.setPath("/");
            response.addCookie(ck);

这是我的控制器类

@RequestMapping(method = RequestMethod.GET, value = "/userlogin/iscaptcharequired.json")
    public ModelAndView isCaptchaRequired(HttpServletRequest objServletRequest,
            HttpServletResponse objServletRespose) 
        // Setting response header to tell client browser not to cache anything.
        objServletRespose.setHeader("Cache-Control",
                "no-cache,no-store,must-revalidate");
        objServletRespose.setHeader("Pragma", "no-cache");
        objServletRespose.setDateHeader("Expires", -1);
        String referrer = objServletRequest.getHeader("Referer");

            objServletRequest.getSession().setAttribute("url_prior_login", referrer);

这是我的 security-config.xml 文件

<sec:filter-chain pattern="/service/**"
                filters="publicSecurityContextPersistenceFilter, 
                    concurrentSessionFilter,
                    publicLogoutFilter,
                    SSOAutoLoginGatewayFilter, 
                    myNePublicUserNamePasswordAuthFilter, 
                    publicAnonymousFilter, 
                    publicExceptionTranslationFilter, 
                    publicFilterSecurityInterceptor" />
<bean id="myNePublicUserNamePasswordAuthFilter"
        class="com.ne.mynelson.authentication.publicuser.MyNePublicUserPasswordAuthFilter">
        <property name="filterProcessesUrl" value="/service/json_authentication_check"></property>
        <property name="authenticationManager" ref="myNePublicUserAuthenticationManager" />
        <property name="authenticationFailureHandler" ref="failureHandler" />
        <property name="authenticationSuccessHandler" ref="successHandler" />
        <property name="authenticationInputProcessor" ref="myNePublicUserAuthInputProcessor"></property>
    </bean>
<bean id="successHandler"
        class="com.ne.mynelson.authentication.publicuser.MyNePublicUserAuthSuccessHandler">
        <property name="authHandlerView" ref="authHandlerView"></property>
        <property name="sessionRegistry" ref="sessionRegistry"></property>
        <property name="publicLoginManager" ref="publicLoginManager"></property>
    </bean>
<bean id="concurrentSessionFilter" class="com.magic.spring.security.ConcurrentSessionFilter">
        <property name="sessionRegistry">
            <ref bean="sessionRegistry" />
        </property>
        <property name="expiredUrl" value="/webapp/staticcontent/html/PublicLogin.html" />
        <property name="logoutHandlers">
            <list>
                <ref bean="publicUserSessionCleanupLogoutHandler" />
                <ref bean="rememberMeServices" /> 
                <ref bean="publicSecurityContextLogoutHandler" />
            </list>
        </property>
    </bean>

【问题讨论】:

【参考方案1】:

像这样添加到你的 spring-security.xml 中

<sec:session-management invalid-session-url="/login">
        <sec:concurrency-control expired-url="/expired-page-url" />
</sec:session-management>

更新:

阅读本文 Spring Security redirect to previous page after successful login

你需要 SavedRequestAwareAuthenticationSuccessHandler

来自 javadoc

 * An authentication success strategy which can make use of the
 * @link org.springframework.security.web.savedrequest.DefaultSavedRequest which may have been stored in the session by the
 * @link ExceptionTranslationFilter. When such a request is intercepted and requires
 * authentication, the request data is stored to record the original destination before
 * the authentication process commenced, and to allow the request to be reconstructed when
 * a redirect to the same URL occurs. This class is responsible for performing the
 * redirect to the original URL if appropriate.

【讨论】:

您好,我添加了 security-config.xml 文件。 我想如果用户由于会话过期而自动注销,然后当他再次登录时,他将被重定向到上次访问的页面而不是默认主页。 您好,我正在使用基于 rest 的身份验证和 concurrentsessionfilter。我尝试使用 SavedRequestAwareAuthenticationSuccessHandler 但运气不佳。

以上是关于由于会话过期,将用户重定向到最后一页的主要内容,如果未能解决你的问题,请参考以下文章

使用protect_from_forgery with: :exception 但如果会话过期则将用户重定向到登录页面

Java Web 应用程序中的会话过期时如何重定向到登录页面?

作者会话的 Laravel 更改重定向部分过期

如果 keycloak 会话过期,我如何重定向到登录页面?

不活动后重定向用户,但保持会话活动

Spring Security:会话过期而不重定向到过期网址?