我正在實作 spring 授權服務器,我想向令牌回應 json 添加一些自定義屬性。以下是我希望的回應方式。
{
"access_token": *jwt*,
"scope": "articles.read openid",
"token_type": "Bearer",
"expires_in": 299,
***"customvalue1":99***
}
我在堆疊溢位中看到了多個討論類似主題的帖子,但在這些情況下,附加資料被添加到 jwt 的宣告或標題中。我的要求是將它添加到 jwt 之外。我嘗試實作 OAuth2TokenCustomizer,但這只允許修改 jwt 的宣告或標頭。有人可以幫忙嗎?
uj5u.com熱心網友回復:
如果您使用新的授權服務器,那么創建此 bean 將幫助您實作目標。好訊息是,一旦檢測到 bean,它將自動應用。
@Bean
public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
return context -> {
Authentication principal = context.getPrincipal();
//context.getTokenType().getValue().equals("access_token")
if (Objects.equals(context.getTokenType().getValue(), "access_token") && principal instanceof UsernamePasswordAuthenticationToken) {
Set<String> authorities = principal.getAuthorities().stream()
.map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
User user = (User) principal.getPrincipal();
context.getClaims().claim("authorities", authorities)
.claim("user", user);
}
};
}

這個類和方法可能對你有幫助。你可以找到類的初始位置
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419983.html
標籤:
