Spring Security Oauth2 JWT 添加额外信息

目录

一、问题描述

二、实现步骤

1、自定义TokenEnhancer

2、配置授权服务器

3、自定义UserDetails的User类

三、参考文档


一、问题描述

Oauth2里默认生成的JWT信息并没有用户信息,在认证授权后一般会返回这一部分信息,我对此进行了改造。

Oauth 2.0 JWT 默认返回 OAuth2AccessToken 接口的实现类,默认实现类是 DefaultOAuth2AccessToken,返回字段有 5 个:

access_token:表示访问令牌,必选项
token_type:表示令牌类型,该值大小写不敏感,必选项,默认是 bearer 类型
expires_in:表示过期时间,单位为秒。如果省略该参数,必须其他方式设置过期时间。
refresh_token:表示更新令牌,用来获取下一次的访问令牌,可选项。
scope:表示权限范围,如果与客户端申请的范围一致,此处可省

改造后,最终实现效果:

可以看到额外信息已添加上。

二、实现步骤

1、自定义TokenEnhancer

public TokenEnhancer customTokenEnhancer() {
        return (accessToken, authentication) -> {
            Map<String, Object> additionalInfo = new HashMap<>();
            Object principal = authentication.getPrincipal();
            try {
                String s = objectMapper.writeValueAsString(principal);
                Map<?, ?> map = objectMapper.readValue(s, Map.class);
                /* 移除不需要的属性 */
                map.remove("accountNonExpired");
                map.remove("accountNonLocked");
                map.remove("credentialsNonExpired");
                map.remove("enabled");
                additionalInfo.put("data", map);
            } catch (JsonProcessingException e) {
                log.error("", e);
            }
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        };
    }

2、配置授权服务器

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(customTokenEnhancer(), jwtAccessTokenConverter())); //token转换器

        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenEnhancer(enhancerChain); //token拓展链
        tokenServices.setTokenStore(jwtTokenStore()); //采用JWT存储token
        /* 开启refresh_token */
        tokenServices.setReuseRefreshToken(true);
        tokenServices.setSupportRefreshToken(true);

        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                .tokenStore(jwtTokenStore()) //采用JWT存储token
                .tokenServices(tokenServices);
        super.configure(endpoints);
    }

3、自定义UserDetails的User类

@Getter
@Setter
@ApiModel("登录用户对象")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class JwtUser<T> extends User {

    @ApiModelProperty("账号信息")
    private T info;

    @ApiModelProperty("菜单")
    private List<TreeNode<SysMenu>> menus;

    public JwtUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
    }

    public JwtUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    }
}

并自定义UserDetailsService并在返回时返回自定义对象即可。

三、参考文档

https://www.cnblogs.com/kuangdaoyizhimei/p/14279979.html

Spring Security JWT 添加额外信息_jwts增加参数-CSDN博客

  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值