【Spring Security】 Oauth2 令牌增强器 TokenEnhancer

Metadata

title: 【Spring Security】 Oauth2 令牌增强器 TokenEnhancer
date: 2023-02-05 15:19
tags:
  - 行动阶段/完成
  - 主题场景/组件
  - 笔记空间/KnowladgeSpace/ProgramSpace/ModuleSpace
  - 细化主题/Module/SpringSecurity
categories:
  - SpringSecurity
keywords:
  - SpringSecurity
description: 【Spring Security】 Oauth2 令牌增强器 TokenEnhancer

【Spring Security】 Oauth2 令牌增强器 TokenEnhancer

在之前的案例中,认证获取到了访问令牌信息,但是这些信息完全不够,比如没有登录用户名,如果还需要添加其他额外信息应该怎么做呢?

源码分析

创建令牌

之前我们分析过,DefaultTokenServices 在其 createAccessToken 方法中会进行令牌的创建和存储。

private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
        // 1. 使用UUID创建一个默认的令牌
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
        // 2. 调用ClientDetailsService 查询令牌的过期时间
        int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
        // 3. 设置令牌的过期时间 Mon Nov 15 10:11:16 CST 2021
        if (validitySeconds > 0) {
            token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
        }
        // 4. 设置刷新令牌 授权范围
        token.setRefreshToken(refreshToken);
        token.setScope(authentication.getOAuth2Request().getScope());
        // 5. 是否设置了令牌增强,如有则增强后再返回
        return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
    }

可以看到在第 5 步骤中,会调用 TokenEnhancer 接口的 enhance 方法对令牌进行增强处理。

TokenEnhancer

TokenEnhancer 接口位于org.springframework.security.oauth2.provider.token包下,它的主要作用是在令牌存储之前,对令牌进行增强处理,只声明了一个 enhance 方法。

public interface TokenEnhancer {

    /**
     * 增强令牌
     * 
     * @param accessToken 当前具有scope及过期时间的访问令牌
     * @param authentication 当前认证用户信息
     * @return 添加了额外信息的新令牌
     */
    OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication);

}