Spring JWT中不存在的角色应该添加到身份验证对象的何处?
我们有一个Spring引导服务器,它使用JWT令牌对用户进行身份验证。应根据用户的身份为其分配角色 授予令牌的服务器不知道用户在每个系统中应该具有哪些角色,因此每个系统应该基于用户的标识授予角色 比如:Spring JWT中不存在的角色应该添加到身份验证对象的何处?,spring,spring-boot,spring-security,jwt,spring-security-oauth2,Spring,Spring Boot,Spring Security,Jwt,Spring Security Oauth2,我们有一个Spring引导服务器,它使用JWT令牌对用户进行身份验证。应根据用户的身份为其分配角色 授予令牌的服务器不知道用户在每个系统中应该具有哪些角色,因此每个系统应该基于用户的标识授予角色 比如: 验证用户身份 (用户已通过身份验证)在安全上下文中查找用户具有哪些角色并添加到身份验证中 检查角色。例如,@PreAuthorize(hasRole('some_role')) 我的问题是: 我该怎么做?或者,我是否应该这样做并以另一种方式处理这种情况?我找到了一种方法,使用定制的jwtAuth
@PreAuthorize(hasRole('some_role'))
我该怎么做?或者,我是否应该这样做并以另一种方式处理这种情况?我找到了一种方法,使用定制的
jwtAuthenticationConverter
来实现这一点
http
...
?.oauth2ResourceServer()
?.jwt()
?.jwtAuthenticationConverter(customConverter)
@组件
类自定义转换器(
私有值jwtGrantedAuthoritiesConverter:jwtGrantedAuthoritiesConverter
):转换器{
重写趣味转换(jwt:jwt):AbstractAuthenticationToken{
//添加角色的自定义逻辑
}
}
如前所述,JwtAuthenticationConverter
是预期的配置点
Spring Security将把它作为@Bean
:
@Bean
JwtAuthenticationConverter JwtAuthenticationConverter(){
JwtAuthenticationConverter转换器=
新的JwtAuthenticationConverter();
setJwtGrantedAuthoritiesConverter(…);
回流转换器;
}
正如在另一个答案中已经指出的,您也可以在DSL上设置一个
您可以在参考资料中阅读更多内容:您正朝着正确的方向前进。每次在每个请求上检查令牌时,总是从db获取用户角色数据。令牌提供用于获取用户数据的用户标识,然后创建会话用户对象,这反过来有助于创建安全上下文。是的,只要每个用户id有一个单独的角色,您的API就会有@PreAuthorize(hasRole('role'))检查。现在,对于如何在代码中完成所有这些,您将需要学习更多关于spring securityOk的知识,因此这似乎值得进一步研究。现在我正在考虑提供JwtAuthenticationProvider的自定义版本。谢谢@BeshambherChaukhwan
@Component
class CustomConverter(
private val jwtGrantedAuthoritiesConverter: JwtGrantedAuthoritiesConverter
) : Converter<Jwt, AbstractAuthenticationToken> {
override fun convert(jwt: Jwt): AbstractAuthenticationToken {
// Custom logic that adds roles
}
}