This article is part of the Spring Security series. In the previous article, we implemented the UserDetailsService and UserDetails interfaces to dynamically load user, role and permission related information from the database, thus realizing login and authorization related functions. This section is on this basis, the login process is often used in the “remember me” function, that is, we often see in various websites login “two weeks free”, “three days free” function. What this function does is: once we have logged in successfully, we do not need to log in again when we visit the site within a certain period of time.

First, the simplest practice

Actually achieve this function is very simple, need only when rewriting WebSecurityConfigurerAdapter method configuration HttpSecurity we increase rememberMe () method. (The following code omits much of the configuration for Spring Security login authentication, which was covered in previous articles in this issue.)

@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.rememberMe(); // Remember my automatic login configuration, the core code is only this line}}Copy the code

Then add a checkbox to the login form, and the value of the name property must currently be “remember-me” (how to personalize changes will be covered later).

<label><input type="checkbox" name="remember-me"/>Copy the code

It’s as simple as that, and we’ve implemented the Remember me feature, which defaults to 2 weeks without logging in.

Two, the implementation principle

Many friends may see the above implementation process in the mind are confused, so achieved? And I’m going to show you what happens in the process.

  • When we log in, in addition to username and password, we can also check remember-me.
  • If we check remember-me, when we log in successfully, the server will generate a Cookie and return it to the browser. The default name of the Cookie is remember-me. The value is a token token.
  • When we visit application again in the period of validity, after RememberMeAuthenticationFilter, read the token Cookie validation. The application can be accessed without the need to log in again.

The token is an MD5 hash string: contains username, expirationTime, and Passwod with a predefined key that is MD5 encrypted. Some friends may ask: Is it safe? If a cookie is hijacked, it’s not secure, someone else gets hold of that string and can access your application within the expiration date. This is the same reason your home is not safe if your key token is stolen. However, there is no possibility that the password can be decrypted into plaintext. MD5 hash is irreversible.

RememberMeAuthenticationFilter in Spring Security in the filter chain in the position of the whole after partial, so only when all sorts of traditional way of login are unable to complete the verification, just walk RememberMeAuthenticationFilter, This is also in line with practical needs.

Three, personalized configuration

In the actual development process, we can also do some personalized Settings according to the requirements, as follows:

.rememberMe()
    .rememberMeParameter("remember-me-new")
    .rememberMeCookieName("remember-me-cookie")
    .tokenValiditySeconds(2 * 24 * 60 * 60);  Copy the code
  • TokenValiditySeconds Is used to set the validity period (in seconds) for a token. If the configuration is not modified, the default value is 2 weeks.
  • Set the parameter name for the automatic login check box on the from form with a rememberMeParameter. If this is changed, the name property of the checkbox in the FROM form should be changed accordingly. If not set, the default is remember-me.
  • RememberMeCookieName specifies the name of the cookie saved in the browser or remember-me if left unremembered. View the browser cookie in the figure below.

Token Database storage mode

The way we talk about above is the simplest way to achieve the “remember me – automatic login” function. The disadvantage of this approach is that the tokens and user mappings are stored in memory, and when we restart the application all tokens disappear, i.e., all users must log in again. To do this, Spring Security also provides a way to store tokens in the database without affecting the restart of the application.

Some articles say that the use of database storage because this way is more secure, I do not think so. Although it’s true that the token stored in the database is no longer a username/password MD5 encrypted string, it’s a random serial number. But once your random serial number cookie is hijacked, the effect is the same. It’s like having a combination lock in your house: losing your key is just as bad as losing your password.

The figure above is the realization principle and verification process of token database storage mode, and we will implement it below. First, we need to key a database table persistent_logins:

CREATE TABLE `persistent_logins` (
  `username` varchar(64) NOT NULL,
  `series` varchar(64) NOT NULL,
  `token` varchar(64) NOT NULL,
  `last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;Copy the code

Initialize a PersistentTokenRepository type Spring bean, and the system using the DataSource into the bean. (Of course, you must have configured the DataSource connection properties in the Spring Boot application. Yml, which will not be described here.)

@Autowired
private DataSource dataSource;

 @Bean
 public PersistentTokenRepository persistentTokenRepository(){
     JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
     tokenRepository.setDataSource(dataSource);
     return tokenRepository;
 }Copy the code

Configure (HttpSecurity HTTP);

.rememberMe()
    .tokenRepository(persistentTokenRepository())Copy the code

We look forward to your attention

  • I recommend the blogger’s series of documents: “Hand on Hand to teach you to learn SpringBoot Series – Chapter 16, Section 97”.
  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.