Springsecurity remember-me function,

Source: Internet
Author: User

Springsecurity remember-me function,

 

This paper is based on spring-security-web-4.1.2.RELEASE.

 

There are two solutions to implement rememberMe.

1. Simple encryption token-Based Method

First, add <remember-me/> to the configuration file, and then add the check box to the logon page form.

<Input type = "checkbox" name = "remember-me" value = "true" checked = "checked"/> do not log on within two weeks

Analysis:

This method is implemented when the user selects "remember me" to log on successfully, Spring Security checks whether the request contains the remember-me parameter and determines whether the logic is in the spring-security-web package.

Org. springframework. security. web. authentication. rememberme. AbstractRememberMeServices:

        String paramValue = request.getParameter(parameter);        if (paramValue != null) {            if (paramValue.equalsIgnoreCase("true") || paramValue.equalsIgnoreCase("on")                    || paramValue.equalsIgnoreCase("yes") || paramValue.equals("1")) {                return true;            }        }

Then the server will generate a token and put it in the cookie (the default name of this cookie is remember-me. The token value is composed of the following methods:

Base64 (username + ":" + expirationTime + ":" + md5Hex (username + ":" + expirationTime + ":" + password + ":" + key ))

  • Username: the user name for logon.
  • Password: the logon password.
  • ExpirationTime: the date and time when the token expires, expressed in milliseconds.
  • Key: A key used to prevent the token from being modified.

The cookie generation logic is in org. springframework. security. web. authentication. rememberme. TokenBasedRememberMeServices. The source code is as follows:

String username = retrieveUserName (successfulAuthentication); String password = retrievePassword (successfulAuthentication); // If unable to find a username and password, just abort as // TokenBasedRememberMeServices is // unable to construct a valid token in this case. if (! StringUtils. hasLength (username) {logger. debug ("Unable to retrieve username"); return;} if (! StringUtils. hasLength (password) {UserDetails user = getUserDetailsService (). loadUserByUsername (username); password = user. getPassword (); if (! StringUtils. hasLength (password) {logger. debug ("Unable to obtain password for user:" + username); return ;}int tokenLifetime = calculateLoginLifetime (request, successfulAuthentication); long expiryTime = System. currentTimeMillis (); // SEC-949 expiryTime + = 1000L * (tokenLifetime <0? TWO_WEEKS_S: tokenLifetime); // generate the encrypted token String signatureValue = makeTokenSignature (expiryTime, username, password); setCookie (new String [] {username, Long. toString (expiryTime), signatureValue}, tokenLifetime, request, response );

When the client accesses restricted resources again in the future, spring-security decodes the cookie named remember-me, obtains the validity period and username, and automatically authenticates the cookie in the system after judgment to avoid logon.

In this way, there is a security risk, that is, after the user obtains the cookie that implements the remember me function, any user can automatically log on to the cookie before the cookie expires, that is to say, it cannot prevent the risk of cookie Theft.

If you want our applications to be more secure, you can use the persistent token method described later, or do not use the Remember-Me function, because the Remember-Me function is always a bit insecure.

2. persistent (persistent) token-Based Method

The simplest implementation method is as follows:

A. configuration file:

<! -- Token has two persistence solutions: memory-based (InMemoryTokenRepositoryImpl) and database-based (JdbcTokenRepositoryImpl) --> <! -- Here we select the database-based method, and dataSource needs to be injected (Please configure DataSource yourself) --> <remember-me data-source-ref = "dataSource"/>

B. insert the persistent_logins table in the database. The statement for inserting the table is org. springframework. security. web. authentication. rememberme. jdbcTokenRepositoryImpl provides a fixed SQL statement to query the token. Please read the source code yourself.

 create table persistent_logins (username varchar(64) not null default '', series varchar(64) primary key, token varchar(64) not null , last_used timestamp not null)

C. Add the check box to the logon page form.

<Input type = "checkbox" name = "remember-me" value = "true" checked = "checked"/> do not log on within two weeks

This completes the persistent token settings.

 

Analysis:

The persistent token-based method adopts the following implementation logic:

(1) After the user selects "remember me" to log on successfully, the username, random serial number, and generated token will be saved to a database table, at the same time, they are combined to generate a cookie and sent to the client browser.

(2) When a user who has not logged on to the system accesses the system, first check the cookie. If the username, serial number, and token contained in the cookie are consistent with those saved in the database, it indicates that it has passed verification. The system will generate a new token to replace the old token of the corresponding combination in the database. The serial number remains unchanged and the old cookie is deleted, generate a new token, and send the cookie of the serial number and username to the client.

(3) When the cookie is checked, the username and serial number contained in the cookie match those saved in the database, but the token does not match. This situation is very likely because your cookie has been stolen. Because hackers use your authenticated cookie to log on, the old token becomes invalid and a new token is generated. At this time, Spring Security can find that the cookie is stolen. It will delete all tokens related to the current user in the database, so that the hacker can no longer Log On with the original cookie, remind users of the possibility of account theft.

(4) If the cookie does not exist or the username and serial number are inconsistent with those saved in the database, the user will be directed to the logon page.

From the above logic, we can see that the persistent token method is safer than the simple encryption token method, because once your cookie is stolen, you only need to use the original cookie to try to log on automatically once, the user's token will be invalid, and the user can find that his or her cookie may be stolen.

In addition, you can use the rewrite class org. springframework. security. web. authentication. rememberme. jdbcTokenRepositoryImpl and configure <remember-me token-repository-ref = ''/> to apply the custom database table. I believe all the users who have read the source code can do this.

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.