---
title: "spring security 实现remeber me（免登陆功能）的原理"
author: "json20080301"
date: "2014-03-19T17:28:56Z"
tags: []
categories: ["企业架构"]
slug: "spring-security-remeber-me"
draft: false
lastmod: "2014-03-19T17:28:56Z"
id: 2033683
url: "https://json20080301.iteye.com/blog/2033683"
---

spring security 实现免登陆功能大体也是基于COOKIE来实现的。

主要配置信息：

 &lt;remember-me  data-source-ref="dataSource" key="rememberMeCookie"  
   authentication-success-handler-ref="authenticationSuccessHandler"  
    services-alias="rememberMeServices" /&gt;

 

1.首先登陆表单要Post URL: /j\_spring\_security\_check 同时\_spring\_security\_remember\_me要等于yes，这时登陆后会记录cookie到数据库中；

/j\_spring\_security\_check?\_spring\_security\_remember\_me=yes

代码逻辑：

UsernamePasswordAuthenticationFilter 登陆验证过滤器拦截/j\_spring\_security\_check同时调用AbstractRememberMeServices 接口实现

 this.rememberMeServices.loginSuccess(request, response, authResult);

 

2.当会话失效时，这个时候RememberMeAuthenticationFilter 过滤器会调用this.rememberMeServices.autoLogin(request, response);自动登陆；

同时successHandler.onAuthenticationSuccess(request, response, rememberMeAuth); 可以进行一些会话信息加载，这个地方需要根据项目的需要进行改造。

 

AbstractRememberMeServices

   public final Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {

1.根据spring security 的cookiename获取spring security 保存的cookie

        String rememberMeCookie = extractRememberMeCookie(request);

 。。。。。

 

2.      解析rememberMeCookie的信息

         UserDetails user = null;

             String\[] cookieTokens = decodeCookie(rememberMeCookie);

3.     获取cookie中信息，并生成登陆的session  
            user = processAutoLoginCookie(cookieTokens, request, response);  
            userDetailsChecker.check(user);

            logger.debug("Remember-me cookie accepted");

            return createSuccessfulAuthentication(request, user);  
             cancelCookie(request, response);  
        return null;  
    }

 

processAutoLoginCookie方法由子类PersistentTokenBasedRememberMeServices  ，TokenBasedRememberMeServices来进行实现；

 

PersistentTokenBasedRememberMeServices 在登陆时保存登陆时的cookie备份，在处理processAutoLoginCookie时会首先比对cookie是否属于伪造的，

不是伪造的才可以获取登陆信息，进行登陆；这一点非常重要！！！

 

PersistentTokenBasedRememberMeServices 会实例化加密后的cookie信息到PersistentTokenRepository 接口的实现中，

private PersistentTokenRepository tokenRepository = new InMemoryTokenRepositoryImpl();

InMemoryTokenRepositoryImpl  的存储方式：Map&lt;String, PersistentRememberMeToken&gt; seriesTokens = new HashMap&lt;String, PersistentRememberMeToken&gt;();

JdbcTokenRepositoryImpl 的存储方式数据库表：推荐使用JdbcTokenRepositoryImpl 方式，这样集群环境下也可以实现cookie的信息的机器备份；

public static final String CREATE\_TABLE\_SQL =  
            "create table persistent\_logins (username varchar(64) not null, series varchar(64) primary key, " +  
                    "token varchar(64) not null, last\_used timestamp not null)";

 

官方配置reference参考：

##### &lt;remember-me&gt; Attributes

- **authentication-success-handler-ref** Sets the `authenticationSuccessHandler` property on the`RememberMeAuthenticationFilter` if custom navigation is required. The value should be the name of a`AuthenticationSuccessHandler` bean in the application context.

<!--THE END-->

- **data-source-ref** A reference to a `DataSource` bean. If this is set, `PersistentTokenBasedRememberMeServices` will be used and configured with a `JdbcTokenRepositoryImpl` instance.

<!--THE END-->

- **remember-me-parameter** The name of the request parameter which toggles remember-me authentication. Defaults to "\_spring\_security\_remember\_me". Maps to the "parameter" property of `AbstractRememberMeServices`.

<!--THE END-->

- **key** Maps to the "key" property of `AbstractRememberMeServices`. Should be set to a unique value to ensure that remember-me cookies are only valid within the one application \[[26](/admin/blogs/new#_footnote_26 "View footnote.")]. If this is not set a secure random value will be generated. Since generating secure random values can take a while, setting this value explicitly can help improve startup times when using the remember me functionality.

<!--THE END-->

- **services-alias** Exports the internally defined `RememberMeServices` as a bean alias, allowing it to be used by other beans in the application context.

<!--THE END-->

- **services-ref** Allows complete control of the `RememberMeServices` implementation that will be used by the filter. The value should be the `id` of a bean in the application context which implements this interface. Should also implement `LogoutHandler` if a logout filter is in use.

<!--THE END-->

- **token-repository-ref** Configures a `PersistentTokenBasedRememberMeServices` but allows the use of a custom`PersistentTokenRepository` bean.

<!--THE END-->

- **token-validity-seconds** Maps to the `tokenValiditySeconds` property of `AbstractRememberMeServices`. Specifies the period in seconds for which the remember-me cookie should be valid. By default it will be valid for 14 days.

<!--THE END-->

- **use-secure-cookie** It is recommended that remember-me cookies are only submitted over HTTPS and thus should be flagged as "secure". By default, a secure cookie will be used if the connection over which the login request is made is secure (as it should be). If you set this property to `false`, secure cookies will not be used. Setting it to `true` will always set the secure flag on the cookie. This attribute maps to the `useSecureCookie` property of `AbstractRememberMeServices`.

<!--THE END-->

- **user-service-ref** The remember-me services implementations require access to a `UserDetailsService`, so there has to be one defined in the application context. If there is only one, it will be selected and used automatically by the namespace configuration. If there are multiple instances, you can specify a bean `id` explicitly using this attribute.