【发布时间】:2021-09-19 19:01:24
【问题描述】:
我正在尝试仅使用 keycloak 进行身份验证,并使用我自己的自定义过滤器进行授权。所以理想的流程是:首先 Keycloak 过滤器对请求进行身份验证并在上下文中设置身份验证对象。然后我的自定义过滤器应该运行,它应该获取现有的身份验证对象,在该身份验证对象中添加权限并将其设置回上下文中。
我的 securityConfig 正在像这样扩展 KeycloakWebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
super.configure(http);
http
.cors()
.and()
.csrf().ignoringAntMatchers("/","/auth","/auth/logout").csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(
"/",
"/auth",
"/password/**",
"/register/**",
"/v2/api-docs",
"/actuator/**",
"/configuration/ui",
"/swagger-resources",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**",
"/swagger-resources/configuration/ui",
"/swagger-resources/configuration/security",
"/browser/index.html#",
"/browser/**").permitAll()
.antMatchers(HttpMethod.POST, REGISTER).permitAll()
.antMatchers(HttpMethod.POST, CONFIRM).permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthorizationFilter(authenticationManager(),context))
// .addFilterAfter(new JWTAuthorizationFilter(authenticationManager(),context), KeycloakAuthenticationProcessingFilter.class)
.headers()
.contentSecurityPolicy("script-src 'self'");
}
它首先运行 KeycloakAuthenticationProcessingFilter,然后运行我的自定义过滤器(JWTAuthorizationFilter),但随后再次调用 KeycloakAuthenticationProcessingFilter,因为再次设置了身份验证对象并清除了权限。 (我尝试了几件事。当前代码加上注释行等等)
首先,在快速启动应用程序中使用 keycloak 是否是正确的方法,如果是这样,那么我怎样才能使我的过滤器在过滤器链中最后运行?
【问题讨论】:
-
我不熟悉
KeycloakAuthenticationProcessingFilter,但请确保它没有注册两次。有关类似建议,请参阅 this comment。 -
实际上 KeycloakAuthenticationProcessingFilter 不在我的应用程序中,我正在使用库。是否有任何解决方案,无论它运行多少次,我都可以将我的过滤器放在链的末尾?
-
我不熟悉 keycloak 库,但目前看来它可能没有得到很好的维护。我刚刚使用内置的
.oauth2Client(withDefaults())配置成功地针对 keycloak 测试了 Spring Security 5.5,它运行良好!所以我想.oauth2Login(withDefaults())也可以。
标签: spring spring-boot spring-security keycloak openid-connect