SpringCloud、SpringBoot2.0 整合Oauth2 (五) 自定义token格式JWT(Json Web Token)

1、自定义 JwtAccessTokenConverter 添加声明版权
/**
 * ===================================
 * 描 述 : token声明版权
 * 包 名 : top.qinxq.single.common.auth
 * 创建人 : qinxq
 * ===================================
 */
public class MyJwtAccessTokenConverter extends org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter {
    @Override
    public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
        Map<String, Object> representation = (Map<String, Object>) super.convertAccessToken(token, authentication);
        representation.put("license", "your licence");
        return representation;
    }

    @Override
    public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
        return super.extractAccessToken(value, map);
    }

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
        return super.extractAuthentication(map);
    }
}
2、认证服务器添加token定制化处理(tokenEnhancer)
//添加 jwtAccessTokenConverter、tokenEnhancer 配置endpoints
//该实例 tokenStore 延续(三)redis存储方式 可更改为其他方式

/**
 * ===================================
 * 描 述 : 认证服务器(redis存储jwt token)
 * 包 名 : top.qinxq.single.common.auth
 * 创建人 : qinxq
 * ===================================
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    private UserDetailsService userDetailService;



    /**
     * =====================================
     * 描   述 : 配置客户端信息
     * 参   数 :  [clients]
     * 返 回 值 : void
     * 创 建 人 :  qinxq
     * 创建时间 :  2019/10/22
     * =====================================
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //这里直接把配置信息保存在内存中
        clients.inMemory()
                .withClient("app")
                //这里必须使用加密
               .secret(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("secret"))
                // 配置 GrantTypes 支持 刷新token 使用密码模式
                .authorizedGrantTypes("client_credentials","refresh_token","password")
                //服务域
                .scopes("server");
    }

    /**
     * =====================================
     * 描   述 : 配置 Token 的节点 和 Token 服务
     * 参   数 :  [endpoints]
     * 返 回 值 : void
     * 创 建 人 :  qinxq
     * 创建时间 :  2019/10/22
     * =====================================
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        //token增强配置
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
        
        endpoints.tokenStore(redisTokenStore())
                .tokenEnhancer(tokenEnhancerChain)
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailService);
    }

    /**
     ============================================
     * 描   述:tokenstore 定制化处理
     * 返回类型:org.springframework.security.oauth2.provider.token.TokenStore
     * 创 建 人:qinxq
     ============================================
     */
    @Bean
    public TokenStore redisTokenStore() {
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix("qin-");
        return tokenStore;
    }



    /**
     * =====================================
     * 描   述 : 密码加密方式
     * 参   数 :  []
     * 返 回 值 : org.springframework.security.crypto.password.PasswordEncoder
     * 创 建 人 :  qinxq
     * 创建时间 :  2019/10/18
     * =====================================
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }


    /**
     * =====================================
     * 描   述 : tokenConverter版权声明
     * 参   数 :  []
     * 返 回 值 : org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter
     * 创 建 人 :  qinxq
     * =====================================
     */
    @Bean
    public org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter jwtAccessTokenConverter() {
        MyJwtAccessTokenConverter jwtAccessTokenConverter = new MyJwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey("your jwt key");
        return jwtAccessTokenConverter;
    }

    /**
     * =====================================
     * 描   述 : jwt 生成token 定制化处理
     * 参   数 :  []
     * 返 回 值 : org.springframework.security.oauth2.provider.token.TokenEnhancer
     * 创 建 人 :  qinxq
     * 创建时间 :  2020/7/20
     * =====================================
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            final Map<String, Object> additionalInfo = new HashMap<>();
            String license = "your license";
            boolean enable = true;//是否设置token过期 建议配置文件获取值
            int expires = 120;//Token过期期时间:分钟 建议配置文件获取值
            //配置Token超期时间:分钟
            if(enable){
                Date expires = DateUtil.offset(new Date(), DateField.MINUTE, expires);
                ((DefaultOAuth2AccessToken) accessToken).setExpiration(expires);
            }
            //additionalInfo 中设置业务信息 如userId等
            additionalInfo.put("license", license);
            Authentication auth = authentication.getUserAuthentication();
            if(auth != null){
                UserDetailsImpl user = (UserDetailsImpl) auth.getPrincipal();
                if (user != null) {
                    additionalInfo.put("userId", user.getUserId());
                }
            }
            additionalInfo.put("code",1);
            additionalInfo.put("msg","success");
            additionalInfo.put("data",true);
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        };
    }

}

相关链接
SpringCloud、SpringBoot2.0 整合Oauth2 (一) 基本配置

SpringCloud、SpringBoot2.0 整合Oauth2 (一) 基本配置

SpringCloud、SpringBoot2.0 整合Oauth2 (二) 自定义返回格式及用户基本信息

SpringCloud、SpringBoot2.0 整合Oauth2 (二) 自定义返回格式及用户基本信息

SpringCloud、SpringBoot2.0 整合Oauth2 (三) token改为redis存储方式

SpringBoot2.0 整合Oauth2 (三) token改为redis存储方式

SpringCloud、SpringBoot2.0 整合Oauth2 (四) 配置文件快速配置url过滤

SpringCloud、SpringBoot2.0 整合Oauth2 (四) 配置文件快速配置url过滤

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值