使用带有 spring webflux 的 keycloak 组保护 API 个端点

protect API endpoints using the keycloak groups with spring webflux

我正在使用 spring webflux 创建一个 API 服务器。

我了解 SecurityWebFilterChain 可以保护 API 端点如下:

@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
@Configuration
open class SecurityConfig : WebFluxConfigurer {
    @Bean
    fun security(http: ServerHttpSecurity): SecurityWebFilterChain =
        http
            .httpBasic().disable()
            .formLogin().disable()
            .logout().disable()
            .csrf().disable()
            .authorizeExchange()
            .anyExchange().authenticated()
            .and()
            .oauth2ResourceServer()
            .jwt()
            .and().and()
            .build()

限制作用,我想会是这样的

authorizeExchange()
    .pathMatchers("/admin/**")
    .hasRole("admin")

有没有办法以类似的方式使用密钥斗篷组?

示例:

authorizeExchange()
    .pathMatchers("/admin/**")
    .hasGroup("admin")

如果不行,还有别的办法吗?

我试过 keycloak-spring-security-adapter 但它似乎不适用于 spring webflux。

感谢您的帮助。

一般来说是可以的。

检查哪些权限存在

例如,通过向您的 RestController 添加一个 Authentication 参数并调用 getAuthorities() 来获取所有磨碎权限的列表。在这种情况下,角色以 ROLE_

为前缀

有团体吗?

只需使用hasRole()

组不存在?

注意使用的 UserDetailsService 实现,因为您必须扩展它才能添加您的组。

添加 hasGroups

这里有一个扩展函数可以做到这一点

fun ServerHttpSecurity.AuthorizeExchangeSpec.Access.hasGroup(group: String) =
  access(AuthorityReactiveAuthorizationManager.hasAuthority("GROUP_$group"))