【发布时间】:2019-11-20 23:39:57
【问题描述】:
对于正在积极开发的软件,我们使用 Spring Boot(带有 Spring Security)和 Keycloak Adapter。
目标是:
- 要求对所有端点进行有效的身份验证,但用
@Public注释的端点除外(请参见代码 sn-p)(可行) - 身份验证必须通过 OAuth - 客户端直接从 Keycloak 获取令牌,Spring Security + Keycloak 适配器确保它有效
- 可选地,还支持基本身份验证(Keycloak 适配器可以配置为执行登录并使其在其余代码中看起来像常规令牌身份验证)(这也适用)
目前一切正常,但我在理解一些细节时遇到了一些问题:
-
KeycloakWebSecurityConfigurerAdapter启用CSRF保护。我认为这样做只是为了让它可以注册自己的 Matcher 以允许来自 Keycloak 的请求 - 它启用会话管理并需要一些相应的 bean
- 即使使用令牌身份验证发出请求,也会返回
JSESSIONIDcookie
据我了解:
- 由于使用了无状态令牌身份验证,因此不需要会话(那么为什么
KeycloakWebSecurityConfigurerAdapter启用它)。这仅适用于BASIC Auth部分吗? - 由于启用了会话,确实需要
CSRF保护 - 但我不希望首先使用会话,然后 API 就不需要CSRF保护,对吧? - 即使我在
super.configure(http)调用之后设置了http.sessionManagement().disable(),JSESSIONIDcookie 也已设置(那么这是从哪里来的?)
正如代码 sn-p 中所述,SessionAuthenticationStrategy 不会设置为 null 一次,因为我们使用 Keycloak 的 Authorization 部分并且应用程序是 Service Account Manager(因此管理这些资源记录)。
如果有人能把事情弄清楚就好了。提前致谢!
@KeycloakConfiguration
public class WebSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
@Inject private RequestMappingHandlerMapping requestMappingHandlerMapping;
@Override
protected void configure(final HttpSecurity http) throws Exception {
super.configure(http);
http
.authorizeRequests()
.requestMatchers(new PublicHandlerMethodMatcher(requestMappingHandlerMapping))
.permitAll()
.anyRequest()
.authenticated();
}
// ~~~~~~~~~~ Keycloak ~~~~~~~~~~
@Override
@ConditionalOnMissingBean(HttpSessionManager.class)
@Bean protected HttpSessionManager httpSessionManager() {
return new HttpSessionManager();
}
/**
* {@link NullAuthenticatedSessionStrategy} is not used since we initiate logins
* from our application and this would not be possible with {@code bearer-only}
* clients (for which the null strategy is recommended).
*/
@Override
@Bean protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
/**
* HTTP session {@link ApplicationEvent} publisher needed for the
* {@link SessionRegistryImpl} of {@link #sessionAuthenticationStrategy()}
* to work properly.
*/
@Bean public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Override
@Bean public KeycloakAuthenticationProvider keycloakAuthenticationProvider() {
return super.keycloakAuthenticationProvider();
}
}
【问题讨论】:
标签: spring-security csrf keycloak websecurity