SpringCloud Alibaba微服务实战二十一

Easter79
• 阅读 625

SpringCloud Alibaba微服务实战二十一

今天内容主要是解决一位粉丝提的问题:如何在jwt中添加用户的额外信息并在资源服务器中获取这些数据。

涉及的知识点有以下三个:

  • 如何在返回的jwt中添加自定义数据

  • 如何在jwt中添加用户的额外数据,比如用户id、手机号码

  • 如何在资源服务器中取出这些自定义数据

下面我们分别来看如何实现。

如何在返回的jwt中添加自定义数据

这个问题比较简单,只要按照如下两步即可:

  1. 编写自定义token增强器

    package com.javadaily.auth.security;

    import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

    import java.util.HashMap; import java.util.Map;

    /**  * 

     * JwtTokenEnhancer  * 

     * Description:  * 自定义Token增强  * @author javadaily  * @date 2020/7/4 15:56  */ public class CustomJwtTokenConverter extends JwtAccessTokenConverter{     @Override     public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication) {         Object principal = authentication.getUserAuthentication().getPrincipal();         final Map<String,Object> additionalInformation = new HashMap<>(4);         additionalInformation.put("author","java日知录");         additionalInformation.put("weixin","javadaily");         ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(additionalInformation);         return super.enhance(oAuth2AccessToken,authentication);     } }

  2. 在认证服务器 AuthorizationServerConfig中配置自定义token增强器

    @Bean public JwtAccessTokenConverter jwtTokenEnhancer(){  //自定义jwt 输出内容,若不需要就直接使用JwtAccessTokenConverter  JwtAccessTokenConverter converter = new CustomJwtTokenConverter();  // 设置对称签名  converter.setSigningKey("javadaily");  return converter; }

通过上述两步配置,我们生成的jwt token中就可以带上 authorweixin 两个属性了,效果如下:SpringCloud Alibaba微服务实战二十一

有的同学可能要问,为什么配置了这个增强器就会生成额外属性了呢?

这是因为我们会使用 DefaultTokenServices#createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken)方法时有如下一段代码:

private OAuth2AccessToken createAccessToken(OAuth2Authentication authentication, OAuth2RefreshToken refreshToken) {
 DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
 int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
 if (validitySeconds > 0) {
  token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
 }
 token.setRefreshToken(refreshToken);
 token.setScope(authentication.getOAuth2Request().getScope());

 return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
}

如果系统配置了 accessTokenEnhancer就会调用 accessTokenEnhancerenhance() 方法进行token增强。我们是继承了 JwtAccessTokenConverter,所以会在jwt token的基础上增加额外的信息。

如何在jwt中添加用户的额外数据

要添加额外数据我们还是要从 CustomJwtTokenConverter想办法,要添加用户的额外数据比如用户id和手机号码那就必须要在用户中包含这些信息。

原来我们自定义的 UserDetailServiceImpl中返回的是默认的 UserDetails。里面只包含用户名属性,即username,代码调试效果如下:

SpringCloud Alibaba微服务实战二十一

所以我们这里需要自定一个 UserDetails,包含用户的额外属性,然后在 UserDetailServiceImpl中再返回我们这个自定义对象,最后在 enhance方法中强转成自定义用户对象并添加额外属性。

实现顺序如下:

  1. 自定义UserDetails

    import lombok.Getter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User;

    import java.util.Collection;

    /**  * 

     * CustomUser  * 

     * Description:  * 自定义用户信息  * @author jianzh5  * @date 2020/11/17 15:05  */ public class SecurityUser extends User {     @Getter     private Integer id;

        @Getter     private String mobile;

        public SecurityUser(Integer id, String mobile,                         String username, String password,                         Collection<? extends GrantedAuthority> authorities) {         super(username, password, authorities);         this.id = id;         this.mobile = mobile;     } }

  2. 在UserDetailServiceImpl中返回自定义对象

    private UserDetails buildUserDetails(SysUser sysUser) {  Set authSet = new HashSet<>();  List roles = sysUser.getRoles();  if(!CollectionUtils.isEmpty(roles)){   roles.forEach(item -> authSet.add(CloudConstant.ROLE_PREFIX + item));   authSet.addAll(sysUser.getPermissions());  }

     List authorityList = AuthorityUtils.createAuthorityList(authSet.toArray(new String[0]));

     return new SecurityUser(    sysUser.getId(),    sysUser.getMobile(),    sysUser.getUsername(),    sysUser.getPassword(),    authorityList  ); }

  3. 在ehance方法中获取当前用户并设置用户信息

    public class CustomJwtTokenConverter extends JwtAccessTokenConverter{     @Override     public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication authentication) {         SecurityUser securityUser = (SecurityUser) authentication.getUserAuthentication().getPrincipal();         final Map<String,Object> additionalInformation = new HashMap<>(4);         additionalInformation.put("userId", securityUser.getId());         additionalInformation.put("mobile", securityUser.getMobile());   ...         ((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(additionalInformation);         return super.enhance(oAuth2AccessToken,authentication);     } }

如何在资源服务器中获取这些自定义信息

通过上面的配置我们可以往jwt的token中添加上用户的数据信息,但是在资源服务器中还是获取不到,通过

SecurityContextHolder.getContext().getAuthentication().getPrincipal()获取到的用户信息还是只包含用户名。

SpringCloud Alibaba微服务实战二十一

这里还是得从token的转换器入手,默认情况下 JwtAccessTokenConverter 会调用 DefaultUserAuthenticationConverter中的 extractAuthentication方法从token中获取用户信息。

我们先看看具体实现逻辑:

public class DefaultUserAuthenticationConverter implements UserAuthenticationConverter {
 ...
 public Authentication extractAuthentication(Map<String, ?> map) {
  if (map.containsKey(USERNAME)) {
   Object principal = map.get(USERNAME);
   Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
   if (userDetailsService != null) {
    UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME));
    authorities = user.getAuthorities();
    principal = user;
   }
   return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
  }
  return null;
 }
 ...
}

在没有注入 UserDetailService的情况下oauth2只会获取用户名 user_name。如果注入了 UserDetailService就可以返回所有用户信息。

所以这里我们对应的实现方式也有两种:

  1. 在资源服务器中也注入 UserDetailService,这种方法不推荐,资源服务器与认证服务器分开的情况下强行耦合在一起,也需要加入用户认证的功能。

  2. 扩展 DefaultUserAuthenticationConverter,重写 extractAuthentication方法,手动取出额外数据,然后在资源服务器配置中将其注入到 AccessTokenConverter中。

这里我们采用第二种方法实现,实现顺序如下:

  1. 自定义token解析器,从jwt token中解析用户信息。

    package com.javadaily.common.security.component;

    import com.javadaily.common.security.user.SecurityUser; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter; import org.springframework.util.StringUtils;

    import java.util.Collection; import java.util.Map;

    public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

        /**      * 重写抽取用户数据方法      * @author javadaily      * @date 2020/11/18 10:56      * @param map 用户认证信息      * @return Authentication      */     @Override     public Authentication extractAuthentication(Map<String, ?> map) {         if (map.containsKey(USERNAME)) {             Collection<? extends GrantedAuthority> authorities = getAuthorities(map);             String username = (String) map.get(USERNAME);             Integer id = (Integer) map.get("userId");             String mobile  = (String) map.get("mobile");             SecurityUser user = new SecurityUser(id, mobile, username,"N/A", authorities);             return new UsernamePasswordAuthenticationToken(user, "N/A", authorities);         }         return null;     }

        private Collection getAuthorities(Map map) {         Object authorities = map.get(AUTHORITIES);         if (authorities instanceof String) {             return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);         }         if (authorities instanceof Collection) {             return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils                     .collectionToCommaDelimitedString((Collection<?>) authorities));         }         throw new IllegalArgumentException("Authorities must be either a String or a Collection");     }

    }

  2. 编写自定义token转换器,注入自定义解压器

    public class CustomAccessTokenConverter extends DefaultAccessTokenConverter{

        public CustomAccessTokenConverter(){         super.setUserTokenConverter(new CustomUserAuthenticationConverter());     } }

  3. 在资源服务器中配置类ResourceServerConfig中注入自定义token转换器

    @Bean public JwtAccessTokenConverter jwtTokenConverter(){  JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();  jwtAccessTokenConverter.setSigningKey("javadaily");  jwtAccessTokenConverter.setAccessTokenConverter(new CustomAccessTokenConverter());

     return jwtAccessTokenConverter; }

通过上面三步配置我们再调用 SecurityContextHolder.getContext().getAuthentication().getPrincipal()方法时就可以获取到用户的额外信息了。

SpringCloud Alibaba微服务实战二十一

当然我们可以再来一个工具类,从上下文中直接获取用户信息:

@UtilityClass
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public SecurityUser getUser(){
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    /**
     * 获取当前用户
     * @param authentication 认证信息
     * @return 当前用户
     */
    private static SecurityUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if(principal instanceof SecurityUser){
            return (SecurityUser) principal;
        }
        return null;
    }
}

SpringCloud alibaba 系列实战教程

如果本文对你有帮助,

别忘记来个三连:****点赞,转发,评论。

咱们下期见!

收藏 等于白嫖点赞 才是真情!

 

干货分享

这里为大家准备了一份小小的礼物,关注公众号,输入如下代码,即可获得百度网盘地址,无套路领取!

001:《程序员必读书籍》
002:《从无到有搭建中小型互联网公司后台服务架构与运维架构》
003:《互联网企业高并发解决方案》
004:《互联网架构教学视频》
006:《SpringBoot实现点餐系统》
007:《SpringSecurity实战视频》
008:《Hadoop实战教学视频》
009:《腾讯2019Techo开发者大会PPT》

010: 微信交流群

近期热文top

1、关于JWT Token 自动续期的解决方案

2、SpringBoot开发秘籍-事件异步处理

3、架构师之路-服务器硬件扫盲

4、架构师之路-微服务技术选型

5、RocketMQ进阶 - 事务消息

SpringCloud Alibaba微服务实战二十一

我就知道你“在看”

SpringCloud Alibaba微服务实战二十一

本文分享自微信公众号 - JAVA日知录(javadaily)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
4个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k