温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring security实现记录用户登录时间功能的案例分析

发布时间:2020-08-06 14:37:03 来源:亿速云 阅读:595 作者:小新 栏目:编程语言

小编给大家分享一下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字段。

Spring security实现记录用户登录时间功能的案例分析

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

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

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

以上是Spring security实现记录用户登录时间功能的案例分析的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI