Help us learn about your current experience with the documentation. Take the survey.

使用 Google OAuth 2.0 作为 OAuth 2.0 认证提供商

  • Tier: Free, Premium, Ultimate
  • Offering: GitLab Self-Managed

要启用 Google OAuth 2.0 OmniAuth 提供商,您必须在 Google 上注册您的应用。Google 会为您生成一个客户端 ID 和密钥供您使用。

要启用 Google OAuth,您必须配置以下内容:

  • Google Cloud Resource Manager
  • Google API Console
  • GitLab 服务器

配置 Google Cloud Resource Manager

  1. 前往 Google Cloud Resource Manager
  2. 选择 创建项目
  3. Project name 中,输入 GitLab
  4. Project ID 中,Google 默认会提供一个随机生成的项目 ID。您可以使用这个随机生成的 ID,也可以创建一个新的。如果您创建新 ID,它必须对所有 Google Developer 注册的应用程序都是唯一的。

要在列表中看到您的新项目,请刷新页面。

配置 Google API Console

  1. 前往 Google API Console

  2. 在左上角,选择您之前创建的项目。

  3. 选择 OAuth consent screen 并填写字段。

  4. 选择 Credentials > Create credentials > OAuth client ID

  5. 填写字段:

    • Application type: 选择 Web application

    • Name: 使用默认名称或输入您自己的名称。

    • Authorized JavaScript origins: 输入 https://gitlab.example.com

    • Authorized redirect URIs: 输入您的域名,然后逐个添加以下回调 URI:

      https://gitlab.example.com/users/auth/google_oauth2/callback
      https://gitlab.example.com/-/google_api/auth/callback
  6. 您应该会看到一个客户端 ID 和客户端密钥。请记下它们,或者保持此页面打开,因为您稍后会需要它们。

  7. 要使项目能够访问 Google Kubernetes Engine,您还必须启用以下 API:

    • Google Kubernetes Engine API
    • Cloud Resource Manager API
    • Cloud Billing API

    操作方法如下:

    1. 前往 Google API Console
    2. 在页面顶部选择 启用 API 和服务
    3. 找到之前提到的每个 API。在 API 的页面上,选择 启用。API 可能需要几分钟才能完全生效。

配置 GitLab 服务器

  1. 打开配置文件。

    对于 Linux 包安装:

    sudo editor /etc/gitlab/gitlab.rb

    对于自行编译的安装:

    cd /home/git/gitlab
    sudo -u git -H editor config/gitlab.yml
  2. 配置 通用设置,将 google_oauth2 添加为单点登录 (Single Sign-On, SSO) 提供商。这将启用即时 (Just-In-Time) 账户预配,为没有现有 GitLab 账户的用户创建账户。

  3. 添加提供商配置。

    对于 Linux 包安装:

    gitlab_rails['omniauth_providers'] = [
      {
        name: "google_oauth2",
        # label: "Provider name", # optional label for login button, defaults to "Google"
        app_id: "<YOUR_APP_ID>",
        app_secret: "<YOUR_APP_SECRET>",
        args: { access_type: "offline", approval_prompt: "" }
      }
    ]

    对于自行编译的安装:

    - { name: 'google_oauth2',
        # label: 'Provider name', # optional label for login button, defaults to "Google"
        app_id: 'YOUR_APP_ID',
        app_secret: 'YOUR_APP_SECRET',
        args: { access_type: 'offline', approval_prompt: '' } }
  4. <YOUR_APP_ID> 替换为 Google Developer 页面上的客户端 ID。

  5. <YOUR_APP_SECRET> 替换为 Google Developer 页面上的客户端密钥。

  6. 请确保您将 GitLab 配置为使用完全限定域名,因为 Google 不接受原始 IP 地址。

    对于 Linux 包安装:

    external_url 'https://gitlab.example.com'

    对于自行编译的安装:

    gitlab:
      host: https://gitlab.example.com
  7. 保存配置文件。

  8. 要使更改生效:

在登录页面上,常规登录表单下方现在应该会出现一个 Google 图标。选择该图标以开始身份验证过程。Google 会要求用户登录并授权 GitLab 应用。如果一切顺利,用户将被重定向回 GitLab 并已登录。