最近在用Spring Security做登錄管理,登陸成功后,頁面長時間無操作,超過session的有效期后,再次點擊頁面操作,頁面無反應,需重新登錄后才可正常使用系統。
為了優化用戶體驗,使得在session失效后,用戶點擊頁面對服務器發起請求時,頁面能夠自動跳轉到登錄頁面。本次使用spring security 3.1。
第一步:配置spring security的專用配置文件spring-security.xml。
<http auto-config="true" entry-point-ref="myLoginUrlAuthenticationEntryPoint"></http> <beans:bean id="myLoginUrlAuthenticationEntryPoint" class="com.ushareit.beyla.security.MyLoginUrlAuthenticationEntryPoint"> <beans:property name="loginFormUrl" value="/login.jsp"/> </beans:bean>
entry-point-ref屬性,英文的意思是入口點引用,它其實是被ExceptionTranslationFilter引用的,該過濾器的作用是異常翻譯。在出現認證異常、訪問異常的時候,通過入口點決定redirect、forword的操作。比如現在是form-login的認證方式,如果沒有通過UsernamePasswordAuthenticationFilter的認證就直接訪問某個被保護的url,那么經過ExceptionTranslationFilter過濾器處理后,先捕獲到訪問拒絕異常,並把跳轉動作交給入口點來處理。form-login的對應入口點類為LoginUrlAuthenticationEntryPoint,這個入口點類的commence方法會redirect或forward到指定的url(form-login標簽的login-page屬性)。
第二步:自定義MyLoginUrlAuthenticationEntryPoint繼承LoginUrlAuthenticationEntryPoint類,並覆蓋commence方法。
package com.ushareit.beyla.security; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; @SuppressWarnings("deprecation") public class MyLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest)request; if ("XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"))){ response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"SessionTimeout"); } else{ super.commence(request, response, authException); } } }
由於只有在ajax請求的時候,其請求頭中有“X-Requested-With”屬性,而傳統請求的時候,請求頭中無此屬性,因此針對ajax請求異常的時候,我們可以通過response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"SessionTimeout");來返回錯誤代碼“401”,來標記訪問出錯。spring security在通過用戶名和密碼進行登錄的時候是普通請求,直接通過super.commence(request, response, authException)
第三步:ajax方法中通過利用statusCode對象根據服務器返回的不同狀態進行處理,我使用的jQuery。在session失效后,頁面又發起的新的ajax請求中通過statusCode對象進行相應處理。
$.ajax({ url: 'xxxx', type: 'get', data: datas, cache: true, dataType: 'json', success: function (data) { alert(123); }, error: function (data) { console.log(data); }, statusCode: { 401: function() { alert("The session is timed out,please log in again!"); window.location.href = '/login.jsp'; } } });