java Spring筛选器向来自令牌的请求添加角色
我正在寻找添加基于角色的身份验证的正确方法,从JWT中提取角色
理想情况下,我希望在进行身份验证后从JWT中提取角色。这将通过检查web令牌中与我们从身份验证系统KeyClope获得的角色相关的一些字段来实现
我的问题是:是否可以将角色附加到请求中,然后使用http配置来要求其中一个提取的角色
下面是一些相关代码,可以帮助解释我在做什么
在我的WebSecurityConfigurer
中,我使访问令牌可用,其作用域为每个请求
@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public AccessToken accessToken() {
try {
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();
return ((KeycloakSecurityContext) ((KeycloakAuthenticationToken) request
.getUserPrincipal())
.getCredentials()).getToken();
} catch (Exception exc) {
return null;
}
}
然后我覆盖了configure
方法中http的一些配置
http
// Disable session management
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
// Allow calls to OPTIONS
.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.and()
// Authenticate every other call
.authorizeRequests().anyRequest().authenticated()
.and()
.csrf().disable();
理想情况下,我想要实现的是:
http.antMatchers("/foo").hasRole("jwt_extracted_role")
我目前正在创建自定义过滤器,从令牌中提取角色,然后检查正确的角色,但这可能比需要的更麻烦
有没有关于我应该覆盖哪些配置类的哪些方法的指针,以便从请求中提取角色,并将它们添加到请求中
# 1 楼答案
我最终通过重写
KeycloakAuthenticationProvider
并在WebSecurityConfig
中作为bean提供我的重写类来解决这个问题。我的班级如下:然后在我的
class WebSecurityConfigurer extends KeycloakWebSecurityConfigurerAdapter
中,我覆盖AuthenticationProvider:这使我可以进行如下配置: