Spring security如何实现记录用户登录时间功能

一、原理分析

security" title="spring security">spring security提供了一个接口 AuthenticationSuccessHandler,该接口中只有一个方法,用来进行登录成功后的操作

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实现类,这个实现类可以记住用户未登录前要访问的地址,这样登录成功后就可以把用户再跳转到他想去的页面。所以我们一般使用继承这个类的方式来实现自定义登录后续操作的功能。

二、实现方式

2.1 自定义AuthenticationSuccessHandler实现类

自定义AuthenticationSuccessHandler接口的实现类,继承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 {

//记录相关的用户信息,如上次登录时间

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在容器中的名称

2.3 测试

启动工程,进行登录,登录成功后会更新用户表中的last_login_time字段。

需要注意的是如果是通过readme进行的登录,不会更新当前用户的登录时间,只有通过账号密码登录时才会进行更新,也就是只有这时才会执行这个onAuthenticationSuccess方法

三、总结

在用户登录成功后记录本次登录相关的信息,需要继承spring-security提供的SavedRequestAwareAuthenticationSuccessHandler类,重写其中的onAuthenticationSuccess方法,在其中进行记录用户信息的操作,在方法的最后调用父类的方法把用户引导到未登录前要去的页面。

测试工程代码的地址:工程示例

以上是 Spring security如何实现记录用户登录时间功能 的全部内容, 来源链接: utcz.com/z/323316.html

回到顶部