Spring security can automatically log in to “remember me” within two weeks
This article is part of the spring security series. In the previous article, we implemented userdetailsservice and userdetails interfaces to dynamically load user, role and permission related information from the database, so as to realize the functions related to login and authorization. On this basis, this section adds the "remember me" function often used in the login process, that is, the functions of "no login within two weeks" and "no login within three days" we often see when logging in various websites. The function is: when we log in successfully, we don't need to log in again when we visit the website again within a certain period.
1、 Simplest practice
In fact, the implementation of this function is very simple. We only need to add the rememberme () method when overriding the websecurityconfigureradapter method to configure httpsecurity. (the following code omits a large number of configurations on spring security login authentication, which have been described in previous articles of this number)
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.rememberMe(); //实现记住我自动登录配置,核心的代码只有这一行 } }
Then add one to the login form check@R_235_2419 @Check the box. The value of the name attribute must be "remember me" (the method of personalized change will be described later).
<label><input type="check@R_235_2419@" name="remember-me"/>自动登录</label>
It's that simple. We have realized the remember me function. The default effect is: no login within 2 weeks.
2、 Implementation principle
Many friends may be confused after reading the above implementation process. Is this the realization? Let's explain what we have done in the process.
The token token is an MD5 hash string: it contains username, expirationtime, passwod and a predefined key, which are encrypted by MD5. Some friends may ask: is it safe? If the cookie is hijacked, it must be unsafe. Others can access your application within the validity period after they get this string. This is the same reason that your key token was stolen. Your home must be unsafe. However, there is no possibility that the password can be cracked into plaintext, and MD5 hash is irreversible.
The remembermeauthenticationfilter is in a backward position in the spring security filter chain as a whole. Therefore, the remembermeauthenticationfilter can only be used when various traditional login methods cannot complete authentication, which is also in line with the actual needs.
3、 Personalized configuration
In the actual development process, we can also make some personalized settings according to our needs, as follows:
.rememberMe() .rememberMeParameter("remember-me-new") .rememberMeCookieName("remember-me-cookie") .tokenValiditySeconds(2 * 24 * 60 * 60);
Tokenvalidityseconds is used to set the validity period of a token, that is, how long it can be exempted from repeated login. The unit is seconds. The default is 2 weeks without modifying the configuration.
Set the parameter name of the "auto login" check box in the from form through the remembermeparameter. If it's changed here, it's in the from form check@R_235_2419 @The name attribute of the to be changed. If not set, the default is remember me.
Remembermecookie name sets the name of the cookie saved on the browser side. If it is not set, it is also remember me by default. View the browser's cookie as shown in the figure below.
4、 Token database storage method
The way we mentioned above is the simplest way to realize the "remember me - auto login" function. The disadvantage of this method is that the corresponding relationship between tokens and users is stored in memory. When we restart the application, all tokens will disappear, that is, all users must log in again. Therefore, spring security also provides us with a way to store tokens in the database, and restarting the application will not be affected.
Some articles say that the use of database storage is because it is more secure. The author doesn't think so. Although the token stored in the database is no longer the user name and password MD5 encrypted string, but a random serial number. But once your random serial number cookie is hijacked, the effect is the same. For example, you have a password lock in your home: if you lose your key, the harm is the same as if you lost your password.
The above figure shows the implementation principle and verification process of token database storage mode. Let's 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;
Initialize a spring bean of persistenttokenrepository type, and inject the datasource used by the system into the bean. (of course, the premise must be that you have configured the connection properties related to datasource in application.yml of spring boot, which will not be repeated here.)
@Autowired private DataSource dataSource; @Bean public PersistentTokenRepository persistentTokenRepository(){ JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl(); tokenRepository.setDataSource(dataSource); return tokenRepository; }
Finally, add the following personalized configuration to the spring security configuration method configure (httpsecurity HTTP):
.rememberMe() .tokenRepository(persistentTokenRepository())
summary
The above is what Xiaobian introduced to you. Spring security realizes the automatic login "remember me" function within two weeks. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to our website! If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!