如何在 Spring 服务或控制器中获取 JWT 声明

Boo*_*aka 7 spring spring-security jwt spring-boot

我已经在互联网的深处搜索过,但在任何地方都找不到合适的答案。如何在 Spring 服务中访问 JWT 中的声明?

\n

我们有一个发布 JWT 的独立身份验证服务。我正在构建一个单独的 spring 服务,需要使用这个 Jwt。我拥有用于​​签署 JWT 的私钥的公钥,并拼凑了足够的教程,以便能够验证 JWT(使用公钥)并允许访问我想要的控制器。

\n

在我的服务中,我现在需要提取 JWT(以及其他)中的 userId \xe2\x80\x8bclaim ,以便我可以用它调用我的数据库等。

\n

https://www.baeldung.com/spring-security-oauth-jwt(第 5.1 节)似乎是最相关的搜索结果:

\n
@GetMapping("/user/info")\npublic Map<String, Object> getUserInfo(@AuthenticationPrincipal Jwt principal) {\n    Map<String, String> map = new Hashtable<String, String>();\n    map.put("user_name", principal.getClaimAsString("preferred_username"));\n    map.put("organization", principal.getClaimAsString("organization"));\n    return Collections.unmodifiableMap(map);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但是,当我的代码运行时,主体始终是null. 我假设我需要在某个地方实现一些其他接口。

\n

我的应用程序中的所有路径都需要身份验证,因此我有:

\n
@Configuration\n@EnableResourceServer\npublic class ResourceServerConfig extends ResourceServerConfigurerAdapter {\n@Override\npublic void configure(HttpSecurity http) throws Exception {\n    // http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();\n    http.csrf().disable()\n        .authorizeRequests()\n        .antMatchers("/**").authenticated();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Ste*_*erg 10

@EnableResourceServerspring-security-oauth是生命周期的一部分,您应该迁移掉,因为不建议将其用于新项目。

查看新的oauth2-resource-server支持的参考,它应该可以@AuthenticationPrincipal Jwt principal在您的控制器中正常工作。另请参阅此存储库的 SecurityConfiguration,或观看SpringOne 2021 的视频演示

在阅读参考文档时,您最感兴趣的是覆盖 Spring Boot 的配置以提供您自己@BeanJwtDecoder使用可用公钥的配置。

您还可以选择提供自己的@Bean声明JwtAuthenticationConverterConverter<Jwt, AbstractAuthenticationToken>访问声明,并Authentication根据JwtAuthenticationToken需要将它们映射到声明中。