Rob*_*eig 6 spring spring-security oauth-2.0 jwt
我有一个使用 Spring MVC 编写的 REST 服务。该服务器是一个 OAuth2 资源服务器,我使用 JwtAuthenticationProvider 来解析 JWT 并将其转换为主体。这一切正常。
但是,我真正想做的是使用从 JWT 中的 Claim 提供的用户名从数据库加载用户详细信息。然后,新的 Principal 应该替换或(理想情况下)包装 Jwt,以便它可以直接从 SecurityContext 中获得。
我真的很想知道如何做到这一点。JwtAuthenticationProvider 似乎不适用于 UserDetailsService。我还考虑过使用 Converter 来执行此操作 - 但扩展 JwtAuthenticationConverter 并不容易,因为 convert 方法是最终的(为什么?)。
所以要非常清楚,这是我理想中想要发生的事情:
我的 WebSecurityConfigurerAdapter 中的 configure 方法有这个:
http.authorizeRequests().antMatchers("/api/*").authenticated().and().oauth2ResourceServer().jwt();
Run Code Online (Sandbox Code Playgroud)
我不能是唯一一个想要将用户数据库与 OAuth2 一起使用的人,所以我一定错过了一些基本的东西吗?我正在使用 Spring Security 5.2.0。
不JwtAuthenticationProvider支持,UserDetailsService因为理论上您不应该UserDetails在不管理凭据的应用程序中使用。我并不是说您不能拥有任何类型的用户,但UserDetailsServiceSpring Security 不会使用或自动装配这些用户。
您可以注册一个 类型的 bean JwtAuthenticationConverter,在convert方法中执行您需要的任何操作并返回自定义身份验证令牌,如下所示:
@Component
public class JwtAuthenticationConverterAdapter implements Converter<Jwt, AbstractAuthenticationToken> {
private JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
@Override
public AbstractAuthenticationToken convert(Jwt jwt) {
var token = this.jwtAuthenticationConverter.convert(jwt);
// build your custom token with the properties from the token above
return customToken;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1401 次 |
| 最近记录: |