You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

配置Keycloak权限后仍可直接访问Spring Boot API,求RBAC保护方案

Keycloak Spring Boot API RBAC权限保护问题排查与实现步骤

一、确认Spring Boot端依赖与核心配置

首先检查项目依赖,确保引入对应版本的Keycloak Spring Boot Starter:

<!-- Maven 示例 -->
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-starter</artifactId>
    <version>匹配你的Keycloak版本</version>
</dependency>

核对application.yml配置,关键项必须正确:

keycloak:
  realm: 你的Realm名称
  auth-server-url: http://你的Keycloak服务地址:端口/auth
  ssl-required: external
  resource: 你的客户端ID
  credentials:
    secret: 你的客户端密钥(仅当客户端Access Type为confidential时需要)
  use-resource-role-mappings: true  # 必须开启,否则只会识别Realm级角色,忽略客户端角色
  bearer-only: true  # 服务端API专用,不处理前端登录跳转

二、API接口必须添加权限校验注解

在需要保护的接口上,明确标注权限校验规则,示例:

@RestController
public class ApiController {

    // 基于角色校验
    @PostMapping("/user/create")
    @RolesAllowed("USER_CREATE")  // 对应Keycloak客户端配置的角色名
    public ResponseEntity<String> createUser() {
        return ResponseEntity.ok("用户创建成功");
    }

    // 基于资源-权限校验
    @GetMapping("/test")
    @Resource(name = "test_resource", scopes = "test_access")  // 对应Keycloak的资源名与权限Scope
    public ResponseEntity<String> testAccess() {
        return ResponseEntity.ok("测试接口访问成功");
    }
}

三、Keycloak端配置验证要点

  1. 客户端配置:确保客户端Access Type为confidential,且开启Authorization Enabled。
  2. 资源与权限:资源的URI需与API接口路径完全匹配(注意前缀、大小写),权限的Scope要和代码中scopes参数一致。
  3. 策略与权限绑定:策略需关联目标角色,权限需绑定对应资源与策略,确保只有指定角色用户能触发权限校验通过。
  4. 用户角色绑定:确认用户绑定的是客户端级角色(而非Realm级角色,除非你刻意关闭use-resource-role-mappings)。

四、配置Spring Security拦截规则

通过配置类确保请求被权限拦截,示例:

@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider provider = keycloakAuthenticationProvider();
        provider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(provider);
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests()
                .antMatchers("/user/**").hasAnyRole("USER_CREATE")
                .antMatchers("/test").hasAuthority("test_access")
                .anyRequest().authenticated();
    }
}

五、调试验证方法

  1. 解析用户JWT令牌,查看realm_access.roles和resource_access.你的客户端ID.roles字段,确认包含目标角色。
  2. 调用API时携带Authorization: Bearer 令牌请求头,无权限时应返回403 Forbidden。
  3. 查看Keycloak日志,排查权限校验过程中是否存在策略匹配失败的记录。

内容的提问来源于stack exchange,提问作者grin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 09:25:14