我正在开发一个使用 keycloak 身份验证服务器的 spring 后端。我正在努力获得基于角色的授权来工作。我在我的领域中创建了一个用户“dev_admin”,并赋予他领域角色“admin”。我有端点“debuf/admin”,只有具有管理员角色的用户才能访问该端点。我的安全配置如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final KeycloakLogoutHandler keycloakLogoutHandler;
SecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) {
this.keycloakLogoutHandler = keycloakLogoutHandler;
}
@Bean
public SecurityFilterChain clientFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> {
auth
.requestMatchers(new AntPathRequestMatcher("/debug/public")).permitAll()
.requestMatchers(new AntPathRequestMatcher("/debug/authenticated")).authenticated()
.requestMatchers(new AntPathRequestMatcher("/debug/admin")).hasAnyRole("admin")
.anyRequest().authenticated();
})
.oauth2Login(Customizer.withDefaults())
.logout((conf) -> {
conf.addLogoutHandler(keycloakLogoutHandler);
conf.logoutSuccessUrl("/index");
})
.build();
}
}
但是,当我以 dev_admin 用户身份登录并尝试访问管理端点后,我返回错误 403。这是来自 spring 控制台的:
https://hastebin.skyra.pw/uricuqahub.prolog
我还使用“模拟”功能检查了 dev_admin JWT 令牌,并且角色包含在令牌中。我还注意到,在我的浏览器中,保存为 cookie 的令牌要短得多并且不包含角色。这些是我找到的所有线索,但我仍然不知道为什么它不起作用。如果有人知道发生了什么,那将会非常有帮助。
您在
SecurityConfig
中指定角色的方式似乎可能存在问题。要将基于角色的授权与 Keycloak 结合使用,您需要使用特定于 Keycloak 的角色前缀来指定角色。默认情况下,Keycloak 使用 ROLE_
角色前缀。
以下是如何修改
SecurityConfig
以使用正确的角色前缀:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.authorizeRequests()
.antMatchers("/debug/public").permitAll()
.antMatchers("/debug/authenticated").authenticated()
.antMatchers("/debug/admin").hasRole("admin") // Use "hasRole" with the role name without "ROLE_" prefix
.anyRequest().authenticated()
.and()
.oauth2Login()
.defaultSuccessURL("/success")
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/index");
}
}
在此修改后的配置中:
我们扩展
KeycloakWebSecurityConfigurerAdapter
以利用 Keycloak 特定的功能。
我们将
AuthenticationManagerBuilder
配置为使用 Keycloak 提供的 keycloakAuthenticationProvider
。
确保您的 Keycloak 领域配置与此设置匹配,尤其是关于角色名称。 Keycloak 中的角色应命名为“admin”,不带
ROLE_
前缀。
希望我有帮助。
此外,请确保 Spring Boot 应用程序的 Keycloak 客户端配置包含正确的角色映射。
完成这些修改后,尝试再次访问
/debug/admin
端点。如果在 Keycloak 中正确分配了角色并且您的 Keycloak 客户端配置准确,则基于角色的授权应该按预期工作。