Spring security builds rest services to implement the remember me function

Spring security remembers my basic principles:

When logging in, the request is sent to the filter usernamepasswordauthenticationfilter. When the filter is authenticated successfully, it will call remembermeservice to generate a token and write the token to the browser cookie. At the same time, there is a tokenrepository in remembermeservice to write the token and user information to the database. In this way, when a user accesses the system again and accesses an interface, he will pass through a filter of membermeauthenticationfilter. He will read the token in the cookie and give it to memberservice. Memberservice will use tokenrepository to check whether there is a record from the database according to the token. If there is a record, the user name will be taken out, Then call userdetailservice to obtain the user information according to the user name and put it in the securitycontext.

Membermeauthenticationfilter is the penultimate filter position in the authentication filter chain in spring security. When other authentication filters fail to authenticate successfully, it will call membermeauthenticationfilter to attempt authentication.

realization:

1. Add < input type to the login form=“ check@R_707_2419 @"Name =" remember me "value =" true "/ >, springsecurity defines a constant in the springsessionremembermeservices class, and the default value is remember me

2. According to the above schematic diagram, to configure the tokenrepository, save the generated token into the database, which is a configuration bean and placed in browsersecurityconfig

3. Configure in configure

4. Add the automatic login time in browser properties to make the time to remember me configurable

Because we need to deal with the database, we need to inject a data source: application properties

Start the application and access localhost: 8080 / user. You need to log in

Login succeeded:

Database: generate a persistent_ Logins table, a piece of data is saved

Stop the service and start again (comment out the jdbctokenrepository. Setcreatetableonstartup (true) that generates and saves the token table) Because our user login information exists in the session, after restarting the service, visit localhost: 8080 / user. You should have rebooted to the login page, but because you configured remember me, you can access it directly and get the interface data

Request header:

So far, the basic rememberme has been completed

The complete code is placed in GitHub: https://github.com/lhy1234/spring-security

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>