【问题标题】:Spring boot- keycloak hardcoded rolesSpring boot-keycloak 硬编码角色
【发布时间】:2021-08-18 16:11:47
【问题描述】:
是否可以动态实现“hasAnyRole”而不是在服务内部硬编码,以便用户可以随时更改它?
我知道有一种方法可以对范围做类似的事情,但它不符合所需的要求。
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.authorizeRequests()
.antMatchers("/*").permitAll()
.antMatchers("/test/roles").hasAnyRole("BYREAD", "BYEDIT")
.anyRequest().permitAll();
}
【问题讨论】:
标签:
spring
spring-boot
spring-security
keycloak
roles
【解决方案1】:
根据您希望用户更新角色的方式,您可以使用引用 Bean 的网络安全表达式来完成它。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/test/roles").access("@permission.check(authentication)")
// ...
}
@Bean
public PermissionChecker permission() {
// ...
}
static class PermissionChecker {
public boolean check(Authentication authentication) {
// ...
}
}
在上面的示例中,@permission 指的是 Bean,称为 permission。
您可以将所需的任何逻辑添加到 check 方法中。
有关更多详细信息,请参阅 Spring Security 参考文档中的this section。