Spring Security builds a rest service to implement rememberme and restrememberme
Spring security remembers my basic principles:
Upon login, the request is sent to the filter UsernamePasswordAuthenticationFilter. After the filter is successfully authenticated, RememberMeService is called and a token is generated to write the token to the browser cookie. In the RememberMeService, A TokenRepository, write the token and user information to the database. In this way, when you access the system again and access an interface, the user will go through a RememberMeAuthenticationFilter filter, and he will read the token from the cookie and hand it over to RememberService, rememberService will use TokenRepository to check whether there are records in the database based on the token. If there are records, the user name will be retrieved, and then the UserDetailService will be called to obtain user information based on the user name, and then placed in SecurityContext.
RememberMeAuthenticationFilterIn Spring Security, the last and last filter locations of the authentication filter chain. When other authentication filters fail to authenticate successfully, the RememberMeAuthenticationFilter will be called to try authentication.
Implementation:
1. Add the logon form<input type="checkbox" name="remember-me" value="true"/>, SpringSecuritySpringSessionRememberMeServicesClass defines a constant, the default value is remember-me
2. According to the schematic diagram above, you can configure TokenRepository and store the generated token in the database. This is a configuration bean, which is placed in BrowserSecurityConfig.
3. configure in configure
4. Add the Automatic Logon Time in BrowserProperties to make my time configurable
// Remember me the number of seconds to configure private int rememberMeSeconds = 10; Qi live package com. imooc. s @ Configuration // This is a Configuration of public class BrowserSecurityConfig extends websecurityjavaseradapter {// read the logon page Configuration configured by the user @ Autowired private SecurityProperties securityProperties; // The Custom processor @ Autowired private AuthenticationSuccessHandler handler after logon; // The processor @ Autowired private AuthenticationFailureHandler imoocAuthenticationFailureHandler after custom authentication fails; // data source @ Autowired private DataSource; @ Autowired private UserDetailsService userDetailsService; // org. springframework. security. crypto. password. passwordEncoder @ Bean public PasswordEncoder passwordencoder () {// BCryptPasswordEncoder implements PasswordEncoder return new BCryptPasswordEncoder ();}/*** remember my TokenRepository configuration, after successful logon, execute * @ Description of the token to the data inventory after successful logon: remember my TokenRepository configuration * @ param @ return response * @ return PersistentTokenRepository * @ throws * @ author lihaoyang * @ date March 5, 2018 */@ Bean public PersistentTokenRepository persistentTokenRepository () {JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl (); jdbcTokenRepository. setDataSource (dataSource); // the corresponding table is automatically generated at startup. You can run the CREATE_TABLE_ SQL script in JdbcTokenRepositoryImpl to generate the table jdbcTokenRepository. setCreateTableOnStartup (true); return jdbcTokenRepository;} // version 2: configurable logon page @ Override protected void configure (HttpSecurity http) throws Exception {// Verification Code filter ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter (); // use your own error in the verification code filter to handle validateCodeFilter. setAuthenticationFailureHandler (imoocAuthenticationFailureHandler); // The configured Verification Code filtering url validateCodeFilter. setSecurityProperties (securityProperties); validateCodeFilter. afterPropertiesSet (); // implement the interface to be authenticated to jump to the form login, security = Authentication + authorization // http. httpBasic () // This is the default pop-up authentication // http // load the verification code filter to the front of the logon filter. addFilterBefore (validateCodeFilter, UsernamePasswordAuthenticationFilter. class) // configuration related to form authentication. formLogin (). loginPage ("/authentication/require") // process user authentication BrowserSecurityController // logon filter UsernamePasswordAuthenticationFilter the default logon url is "/login", which can be changed here. loginProcessingUrl ("/authentication/form "). successHandler (imoocAuthenticationSuccessHandler) // custom post-Authentication processor. failureHandler (imoocAuthenticationFailureHandler) // processing after logon failure. and () // remember my configuration. rememberMe (). tokenRepository (persistentTokenRepository () // TokenRepository. tokenValiditySeconds (securityProperties. getBrowser (). getRememberMeSeconds () // remember my seconds. userDetailsService (userDetailsService) // After remembering my success, call userDetailsService to query user information. and () // authorization-related configuration. authorizeRequests () // authentication/require: Processes logon, securityProperties. getBrowser (). getLoginPage (): the logon page configured by the user. antMatchers ("/authentication/require", securityProperties. getBrowser (). getLoginPage (), // leave the logon page blank and do not filter. Otherwise, the error "/verifycode/image" is returned "). permitAll () // verification code. anyRequest () // any request. authenticated () // authentication is required. and (). csrf (). disable () // disable csrf protection;} ecurity. browser;
To deal with databases, You need to inject a Data source: application. properties.
spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://127.0.0.1:3306/imooc-demospring.datasource.username=rootspring.datasource.password=root
Start the application and access localhost: 8080/user. You need to log on
Logon successful:
Database: generate a persistent_logins table and store a piece of data.
Stop the service and start the service again (comment outjdbcTokenRepository.setCreateTableOnStartup(true);) Because our user logon information is stored in the session, after the service is restarted, visit localhost: 8080/user again. This should have been redirected to the logon page again, but because of the configuration, remember me, so we can directly access and get the interface data.
Request Header:
Now the basic rememberMe is ready
The complete code is put on github: https://github.com/lhy1234/spring-security
Summary
The above is a small part of the Spring Security build rest Service to achieve rememberme remember my function, I hope to help you, if you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!