SpringCloud Alibaba微服務實戰二十一 - JWT增強

 

今天內容主要是解決一位粉絲提的問題:如何在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;

/**
 * <p>
 * <code>JwtTokenEnhancer</code>
 * </p>
 * 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);
    }
}

 

  1. 在認證服務器 AuthorizationServerConfig中配置自定義token增強器

@Bean
public JwtAccessTokenConverter jwtTokenEnhancer(){
 //自定義jwt 輸出內容,若不需要就直接使用JwtAccessTokenConverter
 JwtAccessTokenConverter converter = new CustomJwtTokenConverter();
 // 設置對稱簽名
 converter.setSigningKey("javadaily");
 return converter;
}

通過上述兩步配置,我們生成的jwt token中就可以帶上 authorweixin 兩個屬性了,效果如下:

有的同學可能要問,爲什麼配置了這個增強器就會生成額外屬性了呢?

這是因爲我們會使用 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,代碼調試效果如下:

所以我們這裏需要自定一個 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;

/**
 * <p>
 * <code>CustomUser</code>
 * </p>
 * 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;
    }
}

 

  1. 在UserDetailServiceImpl中返回自定義對象

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

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

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

 

  1. 在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()獲取到的用戶信息還是隻包含用戶名。

這裏還是得從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<? extends GrantedAuthority> getAuthorities(Map<String, ?> 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");
    }

}

 

  1. 編寫自定義token轉換器,注入自定義解壓器

public class CustomAccessTokenConverter extends DefaultAccessTokenConverter{

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

 

  1. 在資源服務器中配置類ResourceServerConfig中注入自定義token轉換器

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

 return jwtAccessTokenConverter;
}

通過上面三步配置我們再調用 SecurityContextHolder.getContext().getAuthentication().getPrincipal()方法時就可以獲取到用戶的額外信息了。

當然我們可以再來一個工具類,從上下文中直接獲取用戶信息:

@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進階 - 事務消息

 

 

我就知道你“在看”

 

 

 

本文分享自微信公衆號 - JAVA日知錄(javadaily)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章