Remember me next spring security to achieve automatic logon

Remember me next spring security to achieve automatic logon

Previous: BCryptPasswordEncoder spring security encryption and password verification principle

First, the principle analysis

The first landing, if you check the readme options, after the successful landing springsecurity will generate a cookie back to the browser, the browser next visit If you carry this cookie, springsecurity will be released this visit.

Second, implementation

2.1 simple implementation

(1) In springsecurity configuration file, add a remember-me configuration node http

<security:http auto-config="true" use-expressions="false">
        <!-- 配置链接地址,表示任意路径都需要ROLE_USER权限,这里可以配置
         一个逗号隔开的角色列表-->
        <security:intercept-url pattern="/**" access="ROLE_USER"/>

        <!--自定义登录页面-->
        <security:form-login login-page="/login.html" login-processing-url="/login"
                             username-parameter="username" password-parameter="password"
                             authentication-failure-forward-url="/failed.html"
                             default-target-url="/index.html"

        />
        <!--关闭csrf,默认是开启的-->
        <security:csrf disabled="true"/>

        <security:remember-me remember-me-parameter="remembermeParamater" />
        <!-- 退出 -->
        <security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.html"/>
    </security:http>

Which remember-me-parameter="remembermeParamater"specify whether the transfer front desk rememberme parameter name, parameter value to be passed foreground is true or false

(2) add a checkbox on the login page Front

<form action="/login" method="post">
        用户名:<input type="text" name="username" placeholder="请输入用户名"><br>
        密 码:<input type="password" name="password" placeholder="请输入密码"><br>
        记住我:<input id="_spring_security_remember_me" type="checkbox" name="remembermeParamater" value="true">
        <input type="submit" value="登录">
    </form>

To name attribute checkbox and upper profile remember-me-parameter="remembermeParamater"consistent.

(3) Testing

Start project, log in, the login is successful observation cookie, will find the server returns a cookie called the remember-me

Now close your browser, and access to open again, they do not clear the cookie can access resources directly, you do not need to log in again.

In this way there is malpractice, the browser cookie values ​​to be carried by the server is stored in memory, and no persistent, so if the value of the service to restart the server-side storage is lost, browser-side rememberme They will fail. To solve this problem you need to be generated by the server the cookie values ​​persisted to the database.

2.2 database implementations

(1) create a table to record the persistence of rememberme

-- 创建记录rememberme记录的表
CREATE TABLE persistent_logins
(
  username  VARCHAR(64),
  series   VARCHAR(64),
  token     VARCHAR(64),
  last_used DATE 
 );

(2) the content rememberme spring-security tag in the configuration file to the following

<security:remember-me remember-me-parameter="remembermeParamater" data-source-ref="dataSource"
                              token-validity-seconds="86400"/>

data-source-ref="dataSource"It is used to specify the data source, spring-security to the operation table through the database and the data source persistent_logins

token-validity-seconds indicates the effective time rememberme, in seconds, where 86400 = 24 * 3600 represents one day

(3) Testing

Start project, log in, the login is successful will generate a record in persistent_logins table,


Will be to find this record in a database based on the carrying value of the cookie in the browser when the browser is closed again to access, if the query on to the certification by

Third, the distinction is password Login or rememberme

When the user performs some sensitive operations need to distinguish whether it is rememberme login, if it is required to let the user to jump to the login page.

In congtroller layer provides a method for determining

@GetMapping("/isRemembermeUser")
public boolean isRemembermeUser(){
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if(authentication==null){
        return false;
    }
    //判断当前用户是否是通过rememberme登录,是返回true,否返回false
    return RememberMeAuthenticationToken.class.isAssignableFrom(authentication.getClass());
}

First log in using passwords, visit http: //localhost/user/isRemembermeUser.do, backstage interfaces returns false, then close the browser to access the address again, the interface returns true background to indicate this is carried out using the authentication rememberme.

Address Test Project code: engineering example

Guess you like

Origin www.cnblogs.com/chengxuxiaoyuan/p/11961102.html