今日のコンテンツは、主にファンが提起した問題を解決することです。jwtにユーザー情報を追加し、リソースサーバーでこれらのデータを取得する方法です。
関連する3つの知識ポイントがあります。
-
返されたjwtにカスタムデータを追加する方法
-
ユーザーIDや携帯電話番号などのユーザーデータをjwtに追加する方法
-
これらのカスタムデータをリソースサーバーから取得する方法
それを達成する方法を見てみましょう。
返されたjwtにカスタムデータを追加する方法
この質問は比較的単純です。次の2つの手順に従ってください。
-
カスタムトークンエンハンサーを書く
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
カスタムトークンエンハンサーを構成する
@Bean
public JwtAccessTokenConverter jwtTokenEnhancer(){
//自定义jwt 输出内容,若不需要就直接使用JwtAccessTokenConverter
JwtAccessTokenConverter converter = new CustomJwtTokenConverter();
// 设置对称签名
converter.setSigningKey("javadaily");
return converter;
}
上記の2段階の構成、生成されたjwtトークン、author
およびweixin
2つのプロパティにより、効果は次のようになります。
一部の学生は質問したいと思うかもしれません、なぜこのエンハンサーは余分な属性を生成するのですか?
❞
これは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
、それが呼び出されます強化されたトークンの方法を。を継承しているので、jwtトークンに基づいて追加情報を追加します。accessTokenEnhancer
enhance()
JwtAccessTokenConverter
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トークンに追加できますが、リソースサーバーではまだ利用できません。
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
取得したユーザー情報には、ユーザー名のみが含まれています。
ここでもトークンコンバーターから開始する必要があります。デフォルトでJwtAccessTokenConverter
は、トークンからユーザー情報を取得DefaultUserAuthenticationConverter
するextractAuthentication
メソッドを呼び出します。
まず、特定の実装ロジックを見てみましょう。
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
すべてのユーザー情報を返すことができます。
したがって、ここには2つの対応する実装メソッドもあります。
-
リソースサーバーにも注入されます
UserDetailService
。この方法はお勧めしません。リソースサーバーが認証サーバーから分離されている場合は、ユーザー認証機能を追加する必要があります。 -
拡張し
DefaultUserAuthenticationConverter
、extractAuthentication
メソッドを書き直し、手動で追加データをフェッチしてから、それをリソースサーバー構成に挿入しますAccessTokenConverter
。
ここでは、2番目の方法を使用して、実装シーケンスを次のように実行します。
-
jwtトークンからユーザー情報を解析するカスタムトークンパーサー。
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");
}
}
-
カスタムトークンコンバーターを作成し、カスタムデコンプレッサーを挿入します
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter{
public CustomAccessTokenConverter(){
super.setUserTokenConverter(new CustomUserAuthenticationConverter());
}
}
-
リソースサーバー構成クラスResourceServerConfigにカスタムトークンコンバーターを挿入します
@Bean
public JwtAccessTokenConverter jwtTokenConverter(){
JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
jwtAccessTokenConverter.setSigningKey("javadaily");
jwtAccessTokenConverter.setAccessTokenConverter(new CustomAccessTokenConverter());
return jwtAccessTokenConverter;
}
次に、上記の3つのステップの構成を通じて、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;
}
}
この記事がお役に立てば、
3つのリンクに来ることを忘れないでください:
いいね、再投稿、コメント
。
またね!
白い売春婦に匹敵するお気に入り 、親指を立てるの は真実です!
終わり
乾物共有
これは皆へのささやかな贈り物です。公式アカウントに従って、次のコードを入力してください。Baiduネットワークディスクアドレスを取得できます。ルーチンはありません。
001:「プログラマーにとって必読の本」
002:「中小規模のインターネット企業向けのバックエンドサービスアーキテクチャと運用および保守アーキテクチャをゼロから構築する」
003:「インターネット企業向けの高同時実行ソリューション」
004:「インターネットアーキテクチャ教育ビデオ "
006:
注文システムのSpringBoot実現" 007: "SpringSecurity実際の戦闘ビデオ"
008: "Hadoop実際の戦闘教育ビデオ"
009: "Tencent 2019 Techo Developer Conference PPT"
010:WeChat交換グループ
最近のホット記事トップ
5. RocketMQAdvanced-トランザクションメッセージ