Oauth2使用redisTokenStore每次认证后token不刷新,多点登录异常

多点登录,token有效期内,每次获取的token的都不刷新,造成登录异常。

关键类和方法如下

重写获取token的方法

package com.datarj.sbacn.common.oauth;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeSet;

import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;

public class MyAuthenticationKeyGenerator extends DefaultAuthenticationKeyGenerator{
    private static final String CLIENT_ID = "client_id";

    private static final String SCOPE = "scope";

    private static final String USERNAME = "username";
    public String extractKey(OAuth2Authentication authentication) {
        Map<String, String> values = new LinkedHashMap<String, String>();
        OAuth2Request authorizationRequest = authentication.getOAuth2Request();
        if (!authentication.isClientOnly()) {
            values.put(USERNAME, authentication.getName()+System.currentTimeMillis());
        }
        values.put(CLIENT_ID, authorizationRequest.getClientId());
        if (authorizationRequest.getScope() != null) {
            values.put(SCOPE, OAuth2Utils.formatParameterList(new TreeSet(authorizationRequest.getScope())));
        }
        return generateKey(values);
    }
}  

使用重写的获取token的类

  public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
            redisTokenStore.setAuthenticationKeyGenerator(new MyAuthenticationKeyGenerator());
            //token放到redis
            endpoints.tokenStore(redisTokenStore)
                    //密码授权必须加
                    .authenticationManager(authenticationManager)
                    //刷新token必须加
                    .userDetailsService(userDetailsService)
                    .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        }

评论

暂无评论