小编Rob*_*eig的帖子

Spring Security:如何将 UserDetailsS​​ervice 与 JwtAuthenticationProvider 一起使用?

我有一个使用 Spring MVC 编写的 REST 服务。该服务器是一个 OAuth2 资源服务器,我使用 JwtAuthenticationProvider 来解析 JWT 并将其转换为主体。这一切正常。

但是,我真正想做的是使用从 JWT 中的 Claim 提供的用户名从数据库加载用户详细信息。然后,新的 Principal 应该替换或(理想情况下)包装 Jwt,以便它可以直接从 SecurityContext 中获得。

我真的很想知道如何做到这一点。JwtAuthenticationProvider 似乎不适用于 UserDetailsS​​ervice。我还考虑过使用 Converter 来执行此操作 - 但扩展 JwtAuthenticationConverter 并不容易,因为 convert 方法是最终的(为什么?)。

所以要非常清楚,这是我理想中想要发生的事情:

  1. 不记名令牌被提供给服务。
  2. 解析 Jwt 并提取声明
  3. 使用这些声明之一作为我的用户数据库的键,我可以在其中查找属性、权利等
  4. 将这些转换为一个新的 Principal 对象,该对象在 SecurityContext 的 Authentication 对象中可用。

我的 WebSecurityConfigurerAdapter 中的 configure 方法有这个:

http.authorizeRequests().antMatchers("/api/*").authenticated().and().oauth2ResourceServer().jwt();
Run Code Online (Sandbox Code Playgroud)

我不能是唯一一个想要将用户数据库与 OAuth2 一起使用的人,所以我一定错过了一些基本的东西吗?我正在使用 Spring Security 5.2.0。

spring spring-security oauth-2.0 jwt

6
推荐指数
1
解决办法
1401
查看次数

标签 统计

jwt ×1

oauth-2.0 ×1

spring ×1

spring-security ×1