gpt4 book ai didi

java - 访问资源服务器 Controller 内的 Spring OAuth 2 JWT 负载?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:47 25 4
gpt4 key购买 nike

我正在浏览 this tutorial关于如何使用 jwt 设置 spring boot oauth。它涵盖了使用 Angular 解码 JWT token ,但我们如何解码它并访问资源服务器 Controller 内的自定义声明?

例如,对于 JJWT,它可以像这样完成(Based on this article):

    String subject = "HACKER";
try {
Jws jwtClaims =
Jwts.parser().setSigningKey(key).parseClaimsJws(jwt);

subject = claims.getBody().getSubject();

//OK, we can trust this JWT

} catch (SignatureException e) {

//don't trust the JWT!
}

Spring 有一个 JWTAccessTokenConverter.decode()方法,但缺少 javadoc,它是 protected 。

最佳答案

这是我在 Spring Boot 中访问自定义 JWT 声明的方式:

1)让Spring将JWT内容复制到Authentication中:

@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends ResourceServerConfigurerAdapter{

@Override
public void configure(ResourceServerSecurityConfigurer config) {
config.tokenServices( createTokenServices() );
}

@Bean
public DefaultTokenServices createTokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore( createTokenStore() );
return defaultTokenServices;
}

@Bean
public TokenStore createTokenStore() {
return new JwtTokenStore( createJwtAccessTokenConverter() );
}

@Bean
public JwtAccessTokenConverter createJwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setAccessTokenConverter( new JwtConverter() );
return converter;
}

public static class JwtConverter extends DefaultAccessTokenConverter implements JwtAccessTokenConverterConfigurer {

@Override
public void configure(JwtAccessTokenConverter converter) {
converter.setAccessTokenConverter(this);
}

@Override
public OAuth2Authentication extractAuthentication(Map<String, ?> map) {
OAuth2Authentication auth = super.extractAuthentication(map);
auth.setDetails(map); //this will get spring to copy JWT content into Authentication
return auth;
}
}
}

2) 在您的代码中的任何位置访问 token 内容:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();        
Object details = authentication.getDetails();
if ( details instanceof OAuth2AuthenticationDetails ){
OAuth2AuthenticationDetails oAuth2AuthenticationDetails = (OAuth2AuthenticationDetails)details;

Map<String, Object> decodedDetails = (Map<String, Object>)oAuth2AuthenticationDetails.getDecodedDetails();

System.out.println( "My custom claim value: " + decodedDetails.get("MyClaim") );
}

关于java - 访问资源服务器 Controller 内的 Spring OAuth 2 JWT 负载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com