【學習、總結】Spring security 登錄超時處理

目標:java

      用戶登錄超過必定時間,在頁面作請求時,提示相似登錄已超時,請從新登錄信息。web

實現:ajax

1.超時時間配置(web.xml):spring

<session-config>
     <!-- 10分鐘 --> 
<session-timeout>10</session-timeout> <tracking-mode>COOKIE</tracking-mode> <cookie-config> <secure>false</secure> <http-only>true</http-only> </cookie-config>
</session-config>

2.session超時過濾、ajax請求處理(spring-security.xml)json

   <!-- invalidSession.htm 是一個不存在的頁面 -->
   <session-management invalid-session-url="/invalidSession.htm"
            session-fixation-protection="newSession">
            <concurrency-control session-registry-ref="sessionRegistry"
                max-sessions="1" error-if-maximum-exceeded="true" />
    </session-management>
    
    <beans:bean id="sessionRegistry"
        class="org.springframework.security.core.session.SessionRegistryImpl" />
        
    <!-- 未登陸的切入點 -->
    <beans:bean id="authenticationProcessingFilterEntryPoint"
        class="com.xxx.xxx.web.controller.auth.MyLoginUrlAuthenticationEntryPoint">
        <beans:property name="loginFormUrl" value="/login.htm"></beans:property>
    </beans:bean>

3.繼承LoginUrlAuthenticationEntryPoint  (MyLoginUrlAuthenticationEntryPoint.java)cookie

public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
         // 若是是ajax請求
            if (RequestUtil.isAjaxRequest(request)) {
                String key = ErrorCodes.BUSINESS_EXCEPTION_PREFIX + ErrorCodes.INVALID_SESSION;
                Object[] args = new String[0];
                String message = messageSource.getMessage(key, args, key, LocaleContextHolder.getLocale());

                String jsonObject = "{\"message\":\"" + message + "\","
                        + "\"needlogin\":true,\"cause\":\"Access is denied\"}";
                ResponseUtil.writeJson(response, jsonObject);
                return;
            } else {
                super.commence(request, response, authException);
            }
        }

4.js 擴展ajaxsession

success:function(data, textStatus){
        //成功回調方法加強處理
        if (data.denied) {
            wms.frame.notifyWarning(data.message);
        } else if (data.needlogin) {
               wms.frame.notifyWarning(data.message);
        } else{
               fn.success(data, textStatus);
              }
        }
相關文章
相關標籤/搜索