【发布时间】:2021-11-13 01:26:34
【问题描述】:
我已经用谷歌搜索了互联网的深度,但在任何地方都找不到合适的答案。如何在 Spring 服务中访问 JWT 中的声明?
我们有一个独立的身份验证服务来发布 JWT。我正在构建一个需要使用这个 Jwt 的单独的 spring 服务。我有用于签署 JWT 的私钥的公钥,并且拼凑了足够多的教程,以便能够验证 JWT(使用公钥)并允许访问我想要的控制器。
在我的服务中,我现在需要在 JWT(以及其他)中提取 userId 声明,以便我可以使用它调用我的数据库等。
https://www.baeldung.com/spring-security-oauth-jwt(第 5.1 节)似乎是最相关的搜索结果:
@GetMapping("/user/info")
public Map<String, Object> getUserInfo(@AuthenticationPrincipal Jwt principal) {
Map<String, String> map = new Hashtable<String, String>();
map.put("user_name", principal.getClaimAsString("preferred_username"));
map.put("organization", principal.getClaimAsString("organization"));
return Collections.unmodifiableMap(map);
}
但是,当我的代码运行时,主体始终是 null。我假设我需要在某个地方实现其他一些接口。
我的应用程序中的所有路径都需要身份验证,所以我有:
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
http.csrf().disable()
.authorizeRequests()
.antMatchers("/**").authenticated();
}
【问题讨论】:
标签: spring spring-boot spring-security jwt