【Spring Security】 TokenEnhancer Token增强 示例

Metadata

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

【Spring Security】 TokenEnhancer Token增强 示例

1. 实现 TokenEnhancer 接口

实现 TokenEnhancer 接口,重写 enhance 方法,该方法传入了 OAuth2AccessToken 及 OAuth2Authentication 对象,所以可以获取到认证信息,添加到令牌对象中,也可以添加其他额外信息。

public class MyTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object> additionalInformation = new HashMap<>();
        // 1. 获取认证信息
        // 客户端
        String clientId = authentication.getOAuth2Request().getClientId();// 客户端ID
        Set<String> resourceIds = authentication.getOAuth2Request().getResourceIds(); // 资源集合
        // 用户
        Authentication userAuthentication = authentication.getUserAuthentication();
        Object principal = userAuthentication.getPrincipal();
        if (principal instanceof User){
            User user= (User) principal;
            additionalInformation.put("userName", user.getUsername());
        }
        // 2.设置到accessToken中
        additionalInformation.put("resourceIds", resourceIds);
        additionalInformation.put("clientId", clientId);
        additionalInformation.put("deptId", "0001");
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
        return accessToken;
    }
}

2. 添加配置

在 AuthorizationServer 配置类中声明 TokenEnhancer Bean 对象,然后在端点配置类中添加令牌增强器。

    // 端点配置
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // 配置端点允许的请求方式
        endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        // 配置认证管理器
        endpoints.authenticationManager(authenticationManager);
        // 自定义异常翻译器,用于处理OAuth2Exception
        endpoints.exceptionTranslator(myWebResponseExceptionTranslator);
        // 重新组装令牌颁发者,加入自定义授权模式
        endpoints.tokenGranter(getTokenGranter(endpoints));
/*      // 添加JWT令牌
        // JWT令牌转换器
        endpoints.accessTokenConverter(jwtAccessTokenConverter);
        // JWT 存储令牌*/
        endpoints.tokenStore(redisTokenStore);
        // 刷新令牌模式添加 userDetailsService
        endpoints.userDetailsService(userDetailsService);
        // 添加令牌增强器
        endpoints.tokenEnhancer(tokenEnhancer());
    }
     @Bean
    public TokenEnhancer tokenEnhancer() {
        return new MyTokenEnhancer();
    }

3. 测试

访问令牌端点,发现返回了自定义的额外信息。