spring security實現記錄用戶登陸時間等信息

spring security實現記錄用戶登陸時間等信息

上一篇: spring security實現記住我下次自動登陸功能java

1、原理分析

spring security提供了一個接口 AuthenticationSuccessHandler,該接口中只有一個方法,用來進行登陸成功後的操做git

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;

}

咱們能夠經過實現該接口來自定義登陸成功後的操做,但spring security提供了一個SavedRequestAwareAuthenticationSuccessHandler實現類,這個實現類能夠記住用戶未登陸前要訪問的地址,這樣登陸成功後就能夠把用戶再跳轉到他想去的頁面。因此咱們通常使用繼承這個類的方式來實現自定義登陸後續操做的功能。spring

2、實現方式

2.1 自定義AuthenticationSuccessHandler實現類

自定義AuthenticationSuccessHandler接口的實現類,繼承SavedRequestAwareAuthenticationSuccessHandler類,並加入到spring容器中ssh

@Component("loginSuccessHandler")
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private IUserDao userDao;

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //記錄相關的用戶信息,如上次登陸時間
        String name = authentication.getName();
        userDao.updateLastLonginTime(System.currentTimeMillis(),name);

        //調用父類的方法把用戶引導到未登陸前要去的頁面
        super.onAuthenticationSuccess(request,response,authentication);
    }
}

其中remember-me-parameter="remembermeParamater"指定前臺傳遞的是否rememberme的參數名,前臺要傳遞的參數值是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"

        />

實例上就是在定義自定義登陸頁面的標籤內指定authentication-success-handler-ref="loginSuccessHandler",其中loginSuccessHandler是自定義的這個bean在容器中的名稱url

2.3 測試

啓動工程,進行登陸,登陸成功後會更新用戶表中的last_login_time字段。code

須要注意的是若是是經過readme進行的登陸,不會更新當前用戶的登陸時間,只有經過帳號密碼登陸時纔會進行更新,也就是隻有這時纔會執行這個onAuthenticationSuccess方法orm

3、總結

在用戶登陸成功後記錄本次登陸相關的信息,須要繼承spring-security提供的SavedRequestAwareAuthenticationSuccessHandler類,重寫其中的onAuthenticationSuccess方法,在其中進行記錄用戶信息的操做,在方法的最後調用父類的方法把用戶引導到未登陸前要去的頁面。xml

測試工程代碼的地址:工程示例

相關文章
相關標籤/搜索