您好,登錄后才能下訂單哦!
小編給大家分享一下Spring security實(shí)現(xiàn)記錄用戶登錄時間功能的案例分析,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
一、原理分析
spring security提供了一個接口 AuthenticationSuccessHandler,該接口中只有一個方法,用來進(jìn)行登錄成功后的操作
public interface AuthenticationSuccessHandler { /** * Called when a user has been successfully authenticated. * * @param request the request which caused the successful authentication * @param response the response * @param authentication the <tt>Authentication</tt> object which was created during * the authentication process. */ void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException; }
我們可以通過實(shí)現(xiàn)該接口來自定義登錄成功后的操作,但spring security提供了一個SavedRequestAwareAuthenticationSuccessHandler實(shí)現(xiàn)類,這個實(shí)現(xiàn)類可以記住用戶未登錄前要訪問的地址,這樣登錄成功后就可以把用戶再跳轉(zhuǎn)到他想去的頁面。所以我們一般使用繼承這個類的方式來實(shí)現(xiàn)自定義登錄后續(xù)操作的功能。
二、實(shí)現(xiàn)方式
2.1 自定義AuthenticationSuccessHandler實(shí)現(xiàn)類
自定義AuthenticationSuccessHandler接口的實(shí)現(xiàn)類,繼承SavedRequestAwareAuthenticationSuccessHandler類,并加入到spring容器中
@Component("loginSuccessHandler") public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { @Autowired private IUserDao userDao; public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { //記錄相關(guān)的用戶信息,如上次登錄時間 String name = authentication.getName(); userDao.updateLastLonginTime(System.currentTimeMillis(),name); //調(diào)用父類的方法把用戶引導(dǎo)到未登錄前要去的頁面 super.onAuthenticationSuccess(request,response,authentication); } }
其中remember-me-parameter="remembermeParamater"指定前臺傳遞的是否rememberme的參數(shù)名,前臺要傳遞的參數(shù)值是true或false
2.2 在spring-security的配置文件中指定自定義的AuthenticationSuccessHandler
<!--自定義登錄頁面--> <security:form-login login-page="/login.html" login-processing-url="/login" username-parameter="username" password-parameter="password" authentication-failure-forward-url="/failed.html" default-target-url="/index.html" authentication-success-handler-ref="loginSuccessHandler" />
實(shí)例上就是在定義自定義登錄頁面的標(biāo)簽內(nèi)指定authentication-success-handler-ref="loginSuccessHandler",其中l(wèi)oginSuccessHandler是自定義的這個bean在容器中的名稱
2.3 測試
啟動工程,進(jìn)行登錄,登錄成功后會更新用戶表中的last_login_time字段。
需要注意的是如果是通過readme進(jìn)行的登錄,不會更新當(dāng)前用戶的登錄時間,只有通過賬號密碼登錄時才會進(jìn)行更新,也就是只有這時才會執(zhí)行這個onAuthenticationSuccess方法
在用戶登錄成功后記錄本次登錄相關(guān)的信息,需要繼承spring-security提供的SavedRequestAwareAuthenticationSuccessHandler類,重寫其中的onAuthenticationSuccess方法,在其中進(jìn)行記錄用戶信息的操作,在方法的最后調(diào)用父類的方法把用戶引導(dǎo)到未登錄前要去的頁面。
測試工程代碼的地址:工程示例
以上是Spring security實(shí)現(xiàn)記錄用戶登錄時間功能的案例分析的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。