You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Spring Security 5 OAuth2 Client与GitLab集成失败求助

解决Spring Security 5 OAuth2/OIDC与GitLab集成失败的问题

我帮你梳理下集成GitLab OAuth2/OIDC时容易踩的坑,结合你给出的配置片段,大概率是这几个地方出了问题:

  • 补全Scope配置:你的配置里sc开头的内容没写完,GitLab OAuth2需要明确指定所需的权限范围,常用的比如read_user(获取用户基本信息)、openid(启用OIDC模式)、profileemail这些,得把这部分补全。
  • 添加GitLab Provider配置:Spring Security默认没有内置GitLab的OAuth2端点信息,所以必须手动指定GitLab的授权、令牌、用户信息等端点地址,否则客户端不知道去哪里请求认证。
  • 核对Redirect URI一致性:确保GitLab应用配置里的回调地址和你redirectUriTemplate配置的完全一致,GitLab对这个地址的匹配很严格,多一个斜杠或者域名不对都会直接失败。

给你一份完整的配置参考,你可以对照调整:

security:
  oauth2:
    client:
      registration:
        gitlab:
          client-id: 0cef9527091bb2faec01610a0fb330e3a915672110cf3298ff3aadceaa8ab11f
          client-secret: fd84439d06f7a2dabb5d5a64ac478211ab4009aa0fa62d478661a52f4234de72
          authorization-grant-type: authorization_code
          redirect-uri: '{baseUrl}/login/oauth2/code/{registrationId}'
          scope: read_user, openid, profile, email
          client-name: GitLab
      provider:
        gitlab:
          authorization-uri: https://gitlab.com/oauth/authorize
          token-uri: https://gitlab.com/oauth/token
          user-info-uri: https://gitlab.com/api/v4/user
          user-name-attribute: id

另外还要注意这几点:

  • 如果你用的是自托管GitLab,要把上面的端点域名换成你自己的GitLab地址,比如https://your-gitlab-domain.com/oauth/authorize
  • 去GitLab的应用设置页面,确认Confidential选项是否勾选(authorization_code模式需要保密客户端),同时回调地址要和配置里的redirect-uri完全匹配,比如你的应用跑在http://localhost:8080,那回调地址就是http://localhost:8080/login/oauth2/code/gitlab
  • 要是还是排查不出问题,可以开启Spring Security的调试日志,在application.yml里加这段配置,能帮你看到认证流程里的详细错误信息:
logging:
  level:
    org.springframework.security: DEBUG

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

火山引擎 最新活动