At the beginning of a user’s visit and log in your website, but again the next day, but must log in again So there will be a “remember me” feature to the convenient user use, has a self-evident thing, however, that’s what the certification status of “long” is already more than the user originally need use scope This means that they can close the browser, Then turn it off and come back the next week or month or more, and as long as it’s not too late, the site will know who’s who and provide them with all the same features and services as they did when they left so long ago.

1 Basic Principles

  • Called after the user is successfully authenticatedRemeberMeServiceGenerate tokens based on user namesTokenRepositoryWrites the Token to the database and also writes the Token to the browser’s Cookie
  • After the service is restarted, the user will log in to the system againRememberMeAuthenticationFilterFilter, read Token information from Cookie, andpersistent_loginsThe table matches to determine whether the remember me function is used
  • Finally byUserDetailsServiceQuerying User Information

2 implementation

Table 2.1 built

2.2 Login page add the remember me check box

The name should be remeber me




2.3 configuration MerryyouSecurityConfig

3 the effect


4 Source code Analysis

4.1 Initial Login

AbstractAuthenticationProcessingFilter#successfulAuthentication

protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { ... / / 1 puts the Authentication has been verified SecurityContext SecurityContextHolder. GetContext () setAuthentication (authResult); / / 2 login successful call rememberMeServices rememberMeServices. LoginSuccess (request, response, authResult); // Fire event if (this.eventPublisher ! = null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent( authResult, this.getClass())); } successHandler.onAuthenticationSuccess(request, response, authResult); }Copy the code

AbstractRememberMeServices#loginSuccess

  • . Check whether remember me is checked


protected void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) { //#1. Get the user name String username = successfulAuthentication. GetName (); logger.debug("Creating new persistent login for user " + username); / / # 2. Create a Token PersistentRememberMeToken persistentToken = new PersistentRememberMeToken (username, generateSeriesData (), generateTokenData(), new Date()); Try {/ / # 3. Storage is database tokenRepository. CreateNewToken (persistentToken); AddCookie (persistentToken, request, response); } catch (Exception e) { logger.error("Failed to save persistent token ", e); }}Copy the code