今天內容主要是解決一位粉絲提的問題:如何在jwt中添加用戶的額外資訊并在資源服務器中獲取這些資料,
涉及的知識點有以下三個:
-
如何在回傳的jwt中添加自定義資料
-
如何在jwt中添加用戶的額外資料,比如用戶id、手機號碼
-
如何在資源服務器中取出這些自定義資料
下面我們分別來看如何實作,
如何在回傳的jwt中添加自定義資料
這個問題比較簡單,只要按照如下兩步即可:
-
撰寫自定義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);
}
}
-
在認證服務器
AuthorizationServerConfig中配置自定義token增強器
@Bean
public JwtAccessTokenConverter jwtTokenEnhancer(){
//自定義jwt 輸出內容,若不需要就直接使用JwtAccessTokenConverter
JwtAccessTokenConverter converter = new CustomJwtTokenConverter();
// 設定對稱簽名
converter.setSigningKey("javadaily");
return converter;
}
通過上述兩步配置,我們生成的jwt token中就可以帶上 author 和 weixin 兩個屬性了,效果如下:
有的同學可能要問,為什么配置了這個增強器就會生成額外屬性了呢?
?
這是因為我們會使用 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就會呼叫 accessTokenEnhancer的 enhance() 方法進行token增強,我們是繼承了 JwtAccessTokenConverter,所以會在jwt token的基礎上增加額外的資訊,
如何在jwt中添加用戶的額外資料
要添加額外資料我們還是要從 CustomJwtTokenConverter想辦法,要添加用戶的額外資料比如用戶id和手機號碼那就必須要在用戶中包含這些資訊,
原來我們自定義的 UserDetailServiceImpl中回傳的是默認的 UserDetails,里面只包含用戶名屬性,即username,代碼除錯效果如下:
所以我們這里需要自定一個 UserDetails,包含用戶的額外屬性,然后在 UserDetailServiceImpl中再回傳我們這個自定義物件,最后在 enhance方法中強轉成自定義用戶物件并添加額外屬性,
實作順序如下:
-
自定義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;
}
}
-
在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
);
}
-
在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就可以回傳所有用戶資訊,
所以這里我們對應的實作方式也有兩種:
-
在資源服務器中也注入
UserDetailService,這種方法不推薦,資源服務器與認證服務器分開的情況下強行耦合在一起,也需要加入用戶認證的功能, -
擴展
DefaultUserAuthenticationConverter,重寫extractAuthentication方法,手動取出額外資料,然后在資源服務器配置中將其注入到AccessTokenConverter中,
這里我們采用第二種方法實作,實作順序如下:
-
自定義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");
}
}
-
撰寫自定義token轉換器,注入自定義解壓器
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter{
public CustomAccessTokenConverter(){
super.setUserTokenConverter(new CustomUserAuthenticationConverter());
}
}
-
在資源服務器中配置類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;
}
}
如果本文對你有幫助,
別忘記來個三連:
點贊,轉發,評論
,
咱們下期見!
收藏 等于白嫖,點贊 才是真情!
End
干貨分享
這里為大家準備了一份小小的禮物,關注公眾號,輸入如下代碼,即可獲得百度網盤地址,無套路領取!
001:《程式員必讀書籍》
002:《從無到有搭建中小型互聯網公司后臺服務架構與運維架構》
003:《互聯網企業高并發解決方案》
004:《互聯網架構教學視頻》
006:《SpringBoot實作點餐系統》
007:《SpringSecurity實戰視頻》
008:《Hadoop實戰教學視頻》
009:《騰訊2019Techo開發者大會PPT》
010: 微信交流群
近期熱文top
1、關于JWT Token 自動續期的解決方案
2、SpringBoot開發秘籍-事件異步處理
3、架構師之路-服務器硬體掃盲
4、架構師之路-微服務技術選型
5、RocketMQ進階 - 事務訊息
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/233125.html
標籤:java
