我正在尝试使用Keycloak保护Spring Boot应用程序并通过Java(而不是XML)对其进行配置。我的SecurityConfig类看起来像这样:
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class,
excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.keycloak.adapters.springsecurity.management.HttpSessionManager"))
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.anyRequest().hasRole("admin");
}
}
据我了解,如果用户当前未登录,对anyRequest
的调用应确保将所有请求重定向到KeyCloak登录页面。但是,这似乎仅能正常工作用于不是根URL的URL。该项目当前有两个端点,“ /”“ / sync”。尝试访问同步端点会正确重定向到登录页面。尝试访问根页面不会,因此似乎被忽略了。我也尝试过使用antMatchers("*", "**", "/", "/*", "/**").hasRole("admin")
,但是这些模式似乎都无法确保根URL的安全。
罪魁祸首似乎是致电super.configure(http)
。但是,这执行了一些相对重要的事情,例如CSRF保护,登录/注销端点等。这是提取到方法中的等效代码,而不是超级调用:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().requireCsrfProtectionMatcher(this.keycloakCsrfRequestMatcher())
.and().sessionManagement().sessionAuthenticationStrategy(this.sessionAuthenticationStrategy())
.and().addFilterBefore(this.keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(this.keycloakAuthenticationProcessingFilter(), BasicAuthenticationFilter.class)
.addFilterBefore(this.keycloakAuthenticatedActionsFilter(), BasicAuthenticationFilter.class)
.addFilterAfter(this.keycloakSecurityContextRequestFilter(), SecurityContextHolderAwareRequestFilter.class)
.exceptionHandling().authenticationEntryPoint(this.authenticationEntryPoint())
.and().logout().addLogoutHandler(this.keycloakLogoutHandler()).logoutUrl("/sso/logout").permitAll().logoutSuccessUrl("/");
http.authorizeRequests()
.anyRequest().hasRole("admin");
}
颠倒超级调用和我自己的授权代码之间的顺序也没有导致根URL受到保护。
答案 0 :(得分:1)
默认情况下,logoutSuccessUrl为“ /”,因此不安全,因此为了保护“ /”,您需要对其进行更改。
.and().logout().logoutSuccessUrl("/logout-success")
我还建议您使用keycloak-spring-boot-starter
答案 1 :(得分:0)
我只是遇到了同样的问题,您需要将logoutSuccessUrl更改为要保护的“ /”以外的其他名称。
.and().logout().addLogoutHandler(this.keycloakLogoutHandler()).logoutUrl("/sso/logout").permitAll().logoutSuccessUrl("/");
到
.and().logout().addLogoutHandler(this.keycloakLogoutHandler()).logoutUrl("/sso/logout").permitAll().logoutSuccessUrl("/somethingelse");