Spring Security build Rest service-0900-rememberMe remember me,

Source: Internet
Author: User

Spring Security build Rest service-0900-rememberMe remember me,

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 <input type = "checkbox" name = "to the logon form"Remember-me"Value =" true "/>. SpringSecurity defines a constant in the SpringSessionRememberMeServices class. The default value is remember-me.

2. According to the schematic diagram above,To configure TokenRepository,Store the generated token in the database. This is a configuration bean and is stored inIn BrowserSecurityConfig

3,Configure in configure

4. Add the Automatic Logon Time in BrowserProperties to make my time configurable

// Remember my seconds Configuration
Private int rememberMeSeconds = 10; same active

Package com. imooc. security. browser; @ 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 ;}}

To deal with databases, You need to inject a Data source: application. properties.

Spring. datasource. driver-class-name = com. mysql. jdbc. Driver
Spring. datasource. url = jdbc: mysql: // FIG: 3306/imooc-demo
Spring. datasource. username = root
Spring. 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 restart it (comment out the jdbcTokenRepository that saves the token table. setCreateTableOnStartup (true, however, because I configured remember me, I was able to 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

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.