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

Spring Security集成Keycloak登录后出现403权限问题

问题解决:Spring Boot + Keycloak 登录后访问受保护路径报403

问题根源分析

从调试日志可见,用户登录后的认证信息里,Granted Authorities仅包含OIDC_USER、SCOPE_email等权限,没有ROLE_user,但你的SecurityConfig配置了/customers*路径需要user角色;同时资源服务器的issuer-uri配置错误,指向本地而非Keycloak实际部署地址。

修复步骤

1. 修正资源服务器配置

application.properties中资源服务器的issuer-uri指向了localhost,但Keycloak部署在另一台机器,需改成和客户端provider一致的地址:

spring.security.oauth2.resourceserver.jwt.issuer-uri=http://192.168.254.1:8184/realms/***

2. 配置Keycloak角色映射

确保Keycloak将用户角色正确注入到JWT中:

  • 登录Keycloak控制台,进入目标Realm
  • 找到你的客户端,切换到「Client scopes」标签,选择roles客户端范围
  • 进入「Mappers」标签,添加/修改「realm roles」映射器:
    • 名称:realm roles
    • 映射器类型:User Realm Role
    • Token Claim Name:roles
    • 开启「Add to ID Token」「Add to Access Token」「Add to Userinfo」
    • 勾选「Multivalued」
    • Client Role Prefix:填写ROLE_(映射后的角色会自动带上ROLE_前缀,匹配Spring Security的hasRole规则)

3. 调整SecurityConfig权限校验(可选)

如果不想在Keycloak中配置前缀,也可以将SecurityConfig中的hasRole("user")改为hasAuthority("user"),直接匹配Keycloak中定义的角色名称:

http.authorizeHttpRequests((requests) -> requests
    .requestMatchers("/customers*")
    .hasAuthority("user")
    .anyRequest()
    .permitAll()
);

验证

修改完成后重启应用,重新登录,此时用户的Granted Authorities会包含ROLE_user(或user),访问/customers*路径即可正常通过权限校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:05:04