OAuth2 client 在分布式环境中使用redis保存token

在集群环境中,作为oauth2客户端,使用Redis再来保存token
本文介绍在spring中的配置

在 OAuth2RestTemplate 配置项里,构建 OAuth2RestTemplate 时传入自定义的 RedisOAuth2ClientContext 类

@Configuration
public class MyOauth2RestTemplate {
    private static final LoggerWithMDC logger = LoggerWithMDC.getLogger(MyOauth2RestTemplate.class, "MyOauth2RestTemplate");

    @Bean
    public OAuth2RestTemplate oauth2RestTemplate() {
        ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
        resource.setClientId(MyConfig.getClientId());
        resource.setClientSecret(MyConfig.getClientSecret());
        resource.setAccessTokenUri(MyConfig.getLoginUrl());
        OAuth2RestTemplate oAuth2RestTemplate = new OAuth2RestTemplate(resource, new RedisOAuth2ClientContext());
        return oAuth2RestTemplate;
    }
}

自定义的 RedisOAuth2ClientContext 类

import org.apache.commons.lang.StringUtils;

public class RedisOAuth2ClientContext extends DefaultOAuth2ClientContext {

    private static final String redisKey = String.format("oauth:%s", MyConfig.getClientId());
    private static final Gson gson = new Gson();
    private static final LoggerWithMDC logger = LoggerWithMDC.getLogger(RedisOAuth2ClientContext.class, "RedisOAuth2ClientContext");


    public RedisOAuth2ClientContext() {

    }

    @Override
    public OAuth2AccessToken getAccessToken() {
        String tokenJson = CodisConnector.get(redisKey);
        if (StringUtils.isBlank(tokenJson)) {
            return null;
        }
        return gson.fromJson(tokenJson, DefaultOAuth2AccessToken.class);
    }

    @Override
    public void setAccessToken(OAuth2AccessToken accessToken) {
        DefaultOAuth2AccessToken accessToken2 = (DefaultOAuth2AccessToken) accessToken;
        String tokenJson = gson.toJson(accessToken2);
        if (accessToken.getExpiresIn() <= 20) {
            CodisConnector.set(redisKey, 1, tokenJson);
        } else {
            CodisConnector.set(redisKey, accessToken.getExpiresIn() - 20, tokenJson);
        }
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 May 29, 2021 01:40 +0800
Built with Hugo
Theme Stack designed by Jimmy