欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring security 实现免登陆功能 Spring

程序员文章站 2022-07-14 23:28:45
...
spring security 实现免登陆功能大体也是基于COOKIE来实现的。

主要配置信息:

<remember-me  data-source-ref="dataSource" key="rememberMeCookie"
   authentication-success-handler-ref="authenticationSuccessHandler"
    services-alias="rememberMeServices" />



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<String, PersistentRememberMeToken> seriesTokens = new HashMap<String, PersistentRememberMeToken>();

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参考:

<remember-me> Attributes
authentication-success-handler-ref Sets the authenticationSuccessHandler property on theRememberMeAuthenticationFilter if custom navigation is required. The value should be the name of aAuthenticationSuccessHandler bean in the application context.

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

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.

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]. 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.

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

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.

token-repository-ref Configures a PersistentTokenBasedRememberMeServices but allows the use of a customPersistentTokenRepository bean.

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.

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.

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.
相关标签: Spring