使用 OAuth 进行 Google 帐号关联

帐号使用行业标准的 OAuth 2.0 隐式授权代码流程来关联。您的服务必须支持符合 OAuth 2.0 规范的授权令牌交换端点。

In the implicit flow, Google opens your authorization endpoint in the user's browser. After successful sign in, you return a long-lived access token to Google. This access token is now included in every request sent from Google.

In the authorization code flow, you need two endpoints:

  • The authorization endpoint, which presents the sign-in UI to your users that aren't already signed in. The authorization endpoint also creates a short-lived authorization code to record users' consent to the requested access.

  • The token exchange endpoint, which is responsible for two types of exchanges:

    1. Exchanges an authorization code for a long-lived refresh token and a short-lived access token. This exchange happens when the user goes through the account linking flow.
    2. Exchanges a long-lived refresh token for a short-lived access token. This exchange happens when Google needs a new access token because the one it had expired.

Choose an OAuth 2.0 flow

Although the implicit flow is simpler to implement, Google recommends that access tokens issued by the implicit flow never expire. This is because the user is forced to link their account again after a token expires with the implicit flow. If you need token expiration for security reasons, we strongly recommend that you use the authorization code flow instead.

Design guidelines

This section describes the design requirements and recommendations for the user screen that you host for OAuth linking flows. After it's called by Google's app, your platform displays a sign in to Google page and account linking consent screen to the user. The user is directed back to Google's app after giving their consent to link accounts.

This figure shows the steps for a user to link their Google account
            to your authentication system. The first screenshot shows
            user-initiated linking from your platform. The second image shows
            user sign-in to Google, while the third shows the user consent and
            confirmation for linking their Google account with your app. The
            final screenshot shows a successfully linked user account in the
            Google app.
Figure 1. Account linking user sign in to Google and consent screens.

Requirements

  1. You must communicate that the user’s account will be linked to Google, not a specific Google product like Google Home or Google Assistant.

Recommendations

We recommend that you do the following:

  1. Display Google's Privacy Policy. Include a link to Google’s Privacy Policy on the consent screen.

  2. Data to be shared. Use clear and concise language to tell the user what data of theirs Google requires and why.

  3. Clear call-to-action. State a clear call-to-action on your consent screen, such as “Agree and link.” This is because users need to understand what data they're required to share with Google to link their accounts.

  4. Ability to cancel. Provide a way for users to go back or cancel, if they choose not to link.

  5. Clear sign-in process. Ensure that users have clear method for signing in to their Google account, such as fields for their username and password or Sign in with Google.

  6. Ability to unlink. Offer a mechanism for users to unlink, such as a URL to their account settings on your platform. Alternatively, you can include a link to Google Account where users can manage their linked account.

  7. Ability to change user account. Suggest a method for users to switch their account(s). This is especially beneficial if users tend to have multiple accounts.

    • If a user must close the consent screen to switch accounts, send a recoverable error to Google so the user can sign in to the desired account with OAuth linking and the implicit flow.
  8. Include your logo. Display your company logo on the consent screen. Use your style guidelines to place your logo. If you wish to also display Google's logo, see Logos and trademarks.

Create the project

To create your project to use account linking:

  1. Go to the Google API Console.
  2. Кликнете върху Създаване на проект .
  3. Въведете име или приемете генерираното предложение.
  4. Потвърдете или редактирайте всички останали полета.
  5. Кликнете върху Създаване .

За да видите идентификационния си номер на проекта:

  1. Go to the Google API Console.
  2. Намерете проекта си в таблицата на целевата страница. Идентификационният номер на проекта се появява в колоната с идентификатор .

The Google Account Linking process includes a consent screen which tells users the application requesting access to their data, what kind of data they are asking for and the terms that apply. You will need to configure your OAuth consent screen before generating a Google API client ID.

  1. Open the OAuth consent screen page of the Google APIs console.
  2. If prompted, select the project you just created.
  3. On the "OAuth consent screen" page, fill out the form and click the “Save” button.

    Application name: The name of the application asking for consent. The name should accurately reflect your application and be consistent with the application name users see elsewhere. The application name will be shown on the Account Linking consent screen.

    Application logo: An image on the consent screen that will help users recognize your app. The logo is shown on Account linking consent screen and on account settings

    Support email: For users to contact you with questions about their consent.

    Scopes for Google APIs: Scopes allow your application to access your user's private Google data. For the Google Account Linking use case, default scope (email, profile, openid) is sufficient, you don’t need to add any sensitive scopes. It is generally a best practice to request scopes incrementally, at the time access is required, rather than up front. Learn more.

    Authorized domains: To protect you and your users, Google only allows applications that authenticate using OAuth to use Authorized Domains. Your applications' links must be hosted on Authorized Domains. Learn more.

    Application Homepage link: Home page for your application. Must be hosted on an Authorized Domain.

    Application Privacy Policy link: Shown on Google Account Linking consent screen. Must be hosted on an Authorized Domain.

    Application Terms of Service link (Optional): Must be hosted on an Authorized Domain.

    Figure 1. Google Account Linking Consent Screen for a fictitious Application, Tunery

  4. Check "Verification Status", if your application needs verification then click the "Submit For Verification" button to submit your application for verification. Refer to OAuth verification requirements for details.

实现 OAuth 服务器

授权代码流程的 OAuth 2.0 服务器实现包括 两个端点,您的服务会通过 HTTPS 提供这两个端点。第一个端点 是授权端点,负责查找或获取 就数据访问征求用户意见。授权端点会提供一个 尚未登录的用户的登录界面,并记录同意情况 请求的访问权限。第二个端点是令牌交换端点, 用于获取加密字符串(称为令牌),以授权用户 访问您的服务。

当 Google 应用需要调用您的某个服务的 API 时,Google 会使用 将这些端点组合在一起,以获取用户调用这些 API 的权限 。

由 Google 发起的 OAuth 2.0 授权代码流程会话包含 以下流程:

  1. Google 会在用户的浏览器中打开您的授权端点。如果流 在用户通过纯语音设备上针对某个 Action 启动,Google 会将 将代码执行到手机上
  2. 用户登录(如果尚未登录),并授予 Google 以下权限: 访问您的 API 访问其数据(如果尚未授权)。
  3. 您的服务会创建授权代码并将其返回给 Google。待办事项 因此,请使用授权代码将用户的浏览器重定向回 Google。 附件。
  4. Google 会将授权代码发送到您的令牌交换端点, 验证代码的真实性并返回访问令牌刷新令牌。访问令牌是一个短期有效的令牌 作为访问 API 的凭据。刷新令牌长期有效 Google 可以存储该令牌,以便在用户首次访问该令牌时, 过期。
  5. 在用户完成账号关联流程后, 从 Google 发送的请求中包含访问令牌。

处理授权请求

需要使用 OAuth 2.0 授权代码执行账号关联的情况 流程中,Google 会通过请求将用户发送到您的授权端点 包含以下参数:

授权端点参数
client_id 您分配给 Google 的客户 ID。
redirect_uri 此请求的响应发送到的网址。
state 将一个在 重定向 URI。
scope 可选:一组以空格分隔的范围字符串,用于指定 Google 请求授权的数据
response_type 要在响应中返回的值的类型。对于 OAuth 2.0 授权代码流程中,响应类型始终为 code
user_locale “Google 账号语言设置” RFC5646 格式,用于将您的内容本地化为用户首选语言。

例如,如果您的授权端点位于 https://myservice.example.com/auth 时,请求可能如下所示:

GET https://myservice.example.com/auth?client_id=GOOGLE_CLIENT_ID&redirect_uri=REDIRECT_URI&state=STATE_STRING&scope=REQUESTED_SCOPES&response_type=code&user_locale=LOCALE

为了让授权端点能够处理登录请求,请执行以下操作 步骤:

  1. 验证 client_id 是否与您分配给 Google 的 Client ID 匹配,以及 redirect_uri 与 Google 为您的服务提供的重定向网址是否匹配。这些检查对于防止 访问意外或配置错误的客户端应用。如果你支持多种 OAuth 2.0 流程,还应确认 response_type 是否为 code
  2. 检查用户是否已登录您的服务。如果用户没有登录, 完成服务的登录或注册流程。
  3. 生成授权代码,以供 Google 用于访问您的 API。 授权代码可以是任何字符串值,但它必须是唯一的 代表用户、令牌对应的客户端以及代码的有效期 而且不可猜测出来。您通常需要进行授权 会在大约 10 分钟后过期。
  4. 确认 redirect_uri 参数指定的网址包含 以下表单:
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
      https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID
      
  5. 将用户的浏览器重定向到 redirect_uri 参数。添加您在 以及您在重定向时返回未经修改的原始状态值 方法是附加 codestate 参数。以下是 生成的网址示例:
    https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID?code=AUTHORIZATION_CODE&state=STATE_STRING

处理令牌交换请求

您的服务的令牌交换端点负责处理两种令牌 广告交易平台:

  • 交换访问令牌和刷新令牌的授权代码
  • 用刷新令牌换取访问令牌

令牌交换请求包含以下参数:

令牌交换端点参数
client_id 用于将请求来源标识为 Google 的字符串。此字符串必须 在您的系统中注册为 Google 的唯一标识符。
client_secret 您在 Google 中为您的服务注册的密钥字符串。
grant_type 所交换的令牌的类型。是 authorization_coderefresh_token
code 如果值为 grant_type=authorization_code,则此参数为 Google 通过您的登录或令牌交换收到的代码 端点。
redirect_uri 如果值为 grant_type=authorization_code,则此参数为 初始授权请求中使用的网址。
refresh_token 如果值为 grant_type=refresh_token,则此参数为 刷新令牌 Google 从您的令牌交换端点收到的令牌。
交换访问令牌和刷新令牌的授权代码

用户登录且您的授权端点返回一个短期有效的 授权代码发送给 Google,Google 会向您的令牌交换发送请求 端点使用授权代码交换访问令牌和刷新 令牌。

对于这些请求,grant_type 的值为 authorization_code, 的 code 值是您先前授予的授权代码的值 。以下是发送 访问令牌和刷新令牌的授权代码:

POST /token HTTP/1.1
Host: oauth2.example.com
Content-Type: application/x-www-form-urlencoded

client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=REDIRECT_URI

要将授权代码交换为访问令牌和刷新令牌,您的 令牌交换端点通过执行以下命令来响应 POST 请求: 步骤:

  1. 验证 client_id 是否将请求来源标识为已获授权的请求来源 来源,并且 client_secret 与预期值匹配。
  2. 请确认授权代码有效且未过期, 请求中指定的客户端 ID 与 授权代码。
  3. 确认 redirect_uri 参数指定的网址完全相同 初始授权请求中使用的值。
  4. 如果您无法验证上述所有条件,则返回 HTTP 正文为 {"error": "invalid_grant"} 的 400 Bad Request 错误。
  5. 否则,使用授权代码中的用户 ID 来生成刷新 令牌和访问令牌。这些标记可以是任何字符串值, 必须唯一地代表用户和令牌对应的客户端, 不得被猜到对于访问令牌,请记录 令牌,通常是在您发出令牌一个小时后。 刷新令牌不会过期。
  6. 在 HTTPS 响应的正文中返回以下 JSON 对象:
    {
    "token_type": "Bearer",
    "access_token": "ACCESS_TOKEN",
    "refresh_token": "REFRESH_TOKEN",
    "expires_in": SECONDS_TO_EXPIRATION
    }

Google 会存储用户的访问令牌和刷新令牌,并存储相关记录 访问令牌的有效期。访问令牌过期后,Google 会使用 刷新令牌,以从令牌交换端点获取新的访问令牌。

用刷新令牌换取访问令牌

访问令牌过期后,Google 会向您的令牌交换发送请求 端点将刷新令牌交换为新的访问令牌。

对于这些请求,grant_type 的值为 refresh_token,值 “refresh_token”是您之前授予的刷新令牌的值 Google。以下是交换刷新令牌的请求示例 获取访问令牌:

POST /token HTTP/1.1
Host: oauth2.example.com
Content-Type: application/x-www-form-urlencoded

client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

如需将刷新令牌交换为访问令牌,令牌交换端点 来响应 POST 请求:

  1. 验证 client_id 是否将请求来源标识为 Google,并 client_secret 与预期值一致。
  2. 请确认刷新令牌有效,以及在 请求与刷新令牌所关联的客户端 ID 相匹配。
  3. 如果您无法验证上述所有条件,则返回 HTTP 400 正文为 {"error": "invalid_grant"} 的 Bad Request 错误。
  4. 否则,请使用刷新令牌中的用户 ID 来生成访问权限 令牌。这些标记可以是任何字符串值,但它们必须是唯一的 代表用户和客户端,而不得 猜测。对于访问令牌,请记录令牌的到期时间, 通常在您发出令牌一小时后发送
  5. 在 HTTPS 的正文中返回以下 JSON 对象 回答:
    {
    "token_type": "不记名",
    "access_token": "ACCESS_TOKEN",
    “expires_in”:SECONDS_TO_EXPIRATION
    }
处理 userinfo 请求

userinfo 端点是受 OAuth 2.0 保护的资源,会返回关联用户的声明。实现和托管 userinfo 端点是可选的,但以下用例除外:

从您的令牌端点成功检索到访问令牌后,Google 会向您的 userinfo 端点发送请求,以检索关联用户的基本个人资料信息。

userinfo 端点请求标头
Authorization header Bearer 类型的访问令牌。

例如,如果您的 userinfo 端点可通过 https://myservice.example.com/userinfo 时,请求可能如下所示:

GET /userinfo HTTP/1.1
Host: myservice.example.com
Authorization: Bearer ACCESS_TOKEN

为了让 userinfo 端点能够处理请求,请执行以下步骤:

  1. 从 Authorization 标头中提取访问令牌,并返回与访问令牌相关联的用户的信息。
  2. 如果访问令牌无效,则使用 WWW-Authenticate 响应标头返回 HTTP 401 Unauthorized 错误。下面是一个 userinfo 错误响应示例:
    HTTP/1.1 401 Unauthorized
    WWW-Authenticate: error="invalid_token",
    error_description="The Access Token expired"
    
    如果在关联过程中返回 401 未经授权错误或任何其他失败的错误响应,该错误将无法恢复,检索到的令牌将被舍弃,并且用户必须重新开始关联流程。
  3. 如果访问令牌有效,则返回 HTTPS 正文中包含以下 JSON 对象的 HTTP 200 响应 回复:

    {
    "sub": "USER_UUID",
    "email": "EMAIL_ADDRESS",
    "given_name": "FIRST_NAME",
    "family_name": "LAST_NAME",
    "name": "FULL_NAME",
    "picture": "PROFILE_PICTURE",
    }
    
    如果您的 userinfo 端点返回 HTTP 200 成功响应,则系统会针对用户的 Google 账号注册检索到的令牌和声明。

    userinfo 端点响应
    sub 系统中用于识别用户的唯一 ID。
    email 用户的电子邮件地址。
    given_name 可选:用户的名字。
    family_name 可选:用户的姓氏。
    name 可选:用户的全名。
    picture 可选:用户的个人资料照片。

验证您的实现

您可以通过使用验证实现的OAuth 2.0游乐场工具。

在工具中,执行以下步骤:

  1. 单击配置打开的OAuth 2.0配置窗口。
  2. OAuth流场中,选择客户端
  3. OAuth端点字段中,选择自定义
  4. 在相应字段中指定您的 OAuth 2.0 端点和您分配给 Google 的客户端 ID。
  5. 步骤1部分,不要选择任何谷歌范围。相反,将此字段留空或键入对您的服务器有效的范围(如果不使用 OAuth 范围,则输入任意字符串)。当您完成后,单击授权的API。
  6. 步骤2步骤3段,完成OAuth 2.0流程和验证每个步骤按预期工作。

您可以通过验证您的实现谷歌帐户链接演示工具。

在工具中,执行以下步骤:

  1. 点击登录在与谷歌按钮。
  2. 选择您要关联的帐户。
  3. 输入服务标识。
  4. (可选)输入您将请求访问的一个或多个范围。
  5. 单击开始演示
  6. 出现提示时,确认您可以同意并拒绝链接请求。
  7. 确认您被重定向到您的平台。