Spring Security Oauth2 token 续期

本文参考以下文章。该文章作者有很多优秀文章,需要的小伙伴可以去看看。

Spring Security系列(27)- Spring Security Oauth2之令牌过期和续签问题解决方案(1)_云烟成雨TD的博客-CSDN博客_怎么解决令牌已经过期Spring Security Oauth2 令牌机制Spring Security Oauth2利用令牌机制来实现认证授权及单点登录,获取到令牌后,携带令牌访问资源服务器,资源服务器针对每次访问,都会用令牌去查询认证信息,然后设置到线程SecurityContextHolder中,后续操作都会获取到用户信息,简单流程入下图所示:令牌过期问题问题在之前,我们分析过,申请到的令牌都是具有过期时间的,在返回的令牌是有字段显示其多久后会过期,单位为秒而这个过期时间,默认是无法修改的,如果用户一直在操https://yunyanchengyu.blog.csdn.net/article/details/121349989本文在上文的基础上做了修改。原文中是自己定义了一个 ResourceServerTokenServices 接口的实现类,而我在实践中发现需要的是一个 AuthorizationServerTokenServices 接口的实现类,可能是版本不同导致的,这点我没有去求证。方便起见,我定义了一个 DefaultTokenServices 的子类,因为 DefaultTokenServices 同时实现了上面提到的两个接口,所以都可以使用。以下是子类的代码:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 实现用户有操作时 token 自动续期
 */
@Component
@ConditionalOnProperty(prefix = "token.auto-renew", name = "enabled", havingValue = "true")
public class CustomResourceServerTokenServices extends DefaultTokenServices {
    private TokenStore tokenStore;

    private ClientDetailsService clientDetailsService;

    @Value("${token.auto-renew.interval}")
    private int interval;

    public CustomResourceServerTokenServices(TokenStore tokenStore) {
        super.setTokenStore(tokenStore);
        this.tokenStore = tokenStore;
    }

    @Override
    public void setClientDetailsService(ClientDetailsService clientDetailsService) {
        super.setClientDetailsService(clientDetailsService);
        this.clientDetailsService = clientDetailsService;
    }

    @Override
    public OAuth2Authentication loadAuthentication(String accessTokenValue) throws AuthenticationException, InvalidTokenException {
        DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken) tokenStore.readAccessToken(accessTokenValue);
        if (accessToken == null) {
            throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
        } else if (accessToken.isExpired()) {
            tokenStore.removeAccessToken(accessToken);
            throw new InvalidTokenException("Access token expired: " + accessTokenValue);
        }

        OAuth2Authentication result = tokenStore.readAuthentication(accessToken);
        if (result == null) {
            // in case of race condition
            throw new InvalidTokenException("Invalid access token: " + accessTokenValue);
        }
        if (clientDetailsService != null) {
            String clientId = result.getOAuth2Request().getClientId();
            try {
                ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
                Date nowTokenExpiration = accessToken.getExpiration();
                Date now = new Date();
                // 如果过期时间少于5分钟,则重新设置令牌对象的过期时间,并存储
                if ((nowTokenExpiration.getTime() - now.getTime()) < (interval * 1000L)) {
                    // 刷新过期时间
                    Date expiration = new Date(System.currentTimeMillis() + clientDetails.getAccessTokenValiditySeconds() * 1000L);
                    accessToken.setExpiration(expiration);
                    // 设置新的令牌 会自动再根据令牌对象过期时间设置 redis过期
                    tokenStore.storeAccessToken(accessToken, result);
                }
            } catch (ClientRegistrationException e) {
                throw new InvalidTokenException("Client not valid: " + clientId, e);
            }
        }
        return result;
    }
}

有几点需要说明:

  1. 基于配置文件决定是否启用此功能,只在开启的时候向容器注入该 Bean
  2. DefaultTokenServices 实现了 InitializingBean 接口,在 afterPropertiesSet 方法中判 tokenStore 是否为空,所以需要在子类的构造方法中配置父类的 tokenStore

  3. 同样的,clientDetailsService 也需要配置父类,但没必要在构造时配置

  4. loadAuthentication 方法的逻辑在原方法的逻辑上添加了 token 续期的逻辑

既然基于配置文件决定是否启用此功能,那么 Configurer 也需要做一些改动:

public class Configurer extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private DefaultTokenServices tokenServices;

    @Bean
    @ConditionalOnMissingBean(DefaultTokenServices.class)
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore);
        return defaultTokenServices;
    }
}

另外,可以对外提供一个接口来实现定期续期 token,接口的逻辑如下:

@Autowired
private TokenStore tokenStore;

@Autowired
private ClientDetailsService clientDetailsService;

public void renewToken() {
    String token = SecurityUtils.getToken();
    if (StringUtils.isNotBlank(token)) {
        DefaultOAuth2AccessToken accessToken = (DefaultOAuth2AccessToken) tokenStore.readAccessToken(token);
        OAuth2Authentication authentication = tokenStore.readAuthentication(accessToken);
        String clientId = authentication.getOAuth2Request().getClientId();
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
        // 刷新过期时间
        Date expiration = new Date(System.currentTimeMillis() + clientDetails.getAccessTokenValiditySeconds() * 1000L);
        accessToken.setExpiration(expiration);
        // 设置新的令牌 会自动再根据令牌对象过期时间设置 redis过期
        tokenStore.storeAccessToken(accessToken, authentication);
    }
}

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值