Vinculación de Cuentas de Google con OAuth

Las cuentas se vinculan con los flujos implícitos y de código de autorización de OAuth 2.0 estándar de la industria. Tu servicio debe admitir extremos de autorización y de intercambio de tokens que cumplan con OAuth 2.0.

En el flujo implícito, Google abre el extremo de autorización en el navegador del usuario. Después de acceder correctamente, devuelves un token de acceso de larga duración a Google. Este token de acceso ahora se incluye en cada solicitud que se envía desde Google.

En el flujo de código de autorización, necesitas dos extremos:

  • El extremo de autorización, que presenta la IU de acceso a los usuarios que aún no accedieron El extremo de autorización también crea un código de autorización de corta duración para registrar el consentimiento de los usuarios para el acceso solicitado.

  • El extremo de intercambio de tokens, que es responsable de dos tipos de intercambios:

    1. Intercambia un código de autorización por un token de actualización de larga duración y un token de acceso de corta duración. Este intercambio se produce cuando el usuario pasa por el flujo de vinculación de cuentas.
    2. Intercambia un token de actualización de larga duración por un token de acceso de corta duración. Este intercambio se produce cuando Google necesita un nuevo token de acceso porque venció.

Elige un flujo de OAuth 2.0

Si bien el flujo implícito es más fácil de implementar, Google recomienda que los tokens de acceso emitidos por el flujo implícito nunca venzan. Esto se debe a que el usuario se ve obligado a volver a vincular su cuenta después de que vence un token con el flujo implícito. Si necesitas que el token venza por motivos de seguridad, te recomendamos que uses el flujo de código de autorización en su lugar.

Lineamientos de diseño

En esta sección, se describen los requisitos y las recomendaciones de diseño para la pantalla del usuario que alojas para los flujos de vinculación de OAuth. Después de que la app de Google le hace una llamada, tu plataforma le muestra al usuario una página de acceso a Google y una pantalla de consentimiento para la vinculación de cuentas. Se redirecciona al usuario a la app de Google después de que da su consentimiento para vincular las cuentas.

En esta figura, se muestran los pasos para que un usuario vincule su Cuenta de Google a tu sistema de autenticación. En la primera captura de pantalla, se muestra la vinculación que inicia el usuario desde tu plataforma. La segunda imagen muestra el acceso del usuario a Google, mientras que la tercera muestra el consentimiento y la confirmación del usuario para vincular su Cuenta de Google con tu app. La captura de pantalla final muestra una cuenta de usuario vinculada correctamente en la app de Google.
Figura 1. Acceso del usuario a la vinculación de cuentas con Google y pantallas de consentimiento

Requisitos

  1. Debes comunicar que la cuenta del usuario se vinculará a Google, no a un producto específico de Google, como Google Home o Asistente de Google.

Recomendaciones

Te recomendamos que hagas lo siguiente:

  1. Mostrar la Política de Privacidad de Google Incluye un vínculo a la Política de Privacidad de Google en la pantalla de consentimiento.

  2. Datos que se compartirán. Usa un lenguaje claro y conciso para indicarle al usuario qué datos requiere Google y por qué.

  3. Llamado a la acción claro. Indica un llamado a la acción claro en la pantalla de consentimiento, como "Aceptar y vincular". Esto se debe a que los usuarios deben comprender qué datos deben compartir con Google para vincular sus cuentas.

  4. Capacidad de cancelar. Proporciona una forma para que los usuarios regresen o cancelen si deciden no realizar la vinculación.

  5. Proceso de acceso claro. Asegúrate de que los usuarios tengan un método claro para acceder a su Cuenta de Google, como campos para su nombre de usuario y contraseña, o Acceder con Google.

  6. Capacidad de desvincular. Ofrece un mecanismo para que los usuarios se desvinculen, como una URL que dirija a la configuración de su cuenta en tu plataforma. Como alternativa, puedes incluir un vínculo a la Cuenta de Google en el que los usuarios puedan administrar su cuenta vinculada.

  7. Capacidad de cambiar la cuenta de usuario. Sugiere un método para que los usuarios cambien de cuenta. Esto es especialmente beneficioso si los usuarios suelen tener varias cuentas.

    • Si un usuario debe cerrar la pantalla de consentimiento para cambiar de cuenta, envía un error recuperable a Google para que el usuario pueda acceder a la cuenta deseada con la vinculación de OAuth y el flujo implícito.
  8. Incluye tu logotipo. Mostrar el logotipo de tu empresa en la pantalla de consentimiento Usa tus lineamientos de estilo para colocar el logotipo. Si también deseas mostrar el logotipo de Google, consulta Logotipos y marcas comerciales.

Create the project

To create your project to use account linking:

  1. Go to the Google API Console.
  2. Click Create project.
  3. Enter a name or accept the generated suggestion.
  4. Confirm or edit any remaining fields.
  5. Click Create.

To view your project ID:

  1. Go to the Google API Console.
  2. Find your project in the table on the landing page. The project ID appears in the ID column.

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.

Implementa tu servidor de OAuth

To support the OAuth 2.0 implicit flow, your service makes an authorization endpoint available by HTTPS. This endpoint is responsible for authentication and obtaining consent from users for data access. The authorization endpoint presents a sign-in UI to your users that aren't already signed in and records consent to the requested access.

When a Google application needs to call one of your service's authorized APIs, Google uses this endpoint to get permission from your users to call these APIs on their behalf.

A typical OAuth 2.0 implicit flow session initiated by Google has the following flow:

  1. Google opens your authorization endpoint in the user's browser. The user signs in, if not signed in already, and grants Google permission to access their data with your API, if they haven't already granted permission.
  2. Your service creates an access token and returns it to Google. To do so, redirect the user's browser back to Google with the access token attached to the request.
  3. Google calls your service's APIs and attaches the access token with each request. Your service verifies that the access token grants Google authorization to access the API and then completes the API call.

Handle authorization requests

When a Google application needs to perform account linking via an OAuth 2.0 implicit flow, Google sends the user to your authorization endpoint with a request that includes the following parameters:

Authorization endpoint parameters
client_id The client ID you assigned to Google.
redirect_uri The URL to which you send the response to this request.
state A bookkeeping value that is passed back to Google unchanged in the redirect URI.
response_type The type of value to return in the response. For the OAuth 2.0 implicit flow, the response type is always token.
user_locale The Google Account language setting in RFC5646 format used to localize your content in the user's preferred language.

For example, if your authorization endpoint is available at https://myservice.example.com/auth, a request might look like the following:

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

For your authorization endpoint to handle sign-in requests, do the following steps:

  1. Verify the client_id and redirect_uri values to prevent granting access to unintended or misconfigured client apps:

    • Confirm that the client_id matches the client ID you assigned to Google.
    • Confirm that the URL specified by the redirect_uri parameter has the following form:
      https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID
      https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID
      
  2. Check if the user is signed in to your service. If the user isn't signed in, complete your service's sign-in or sign-up flow.

  3. Generate an access token for Google to use to access your API. The access token can be any string value, but it must uniquely represent the user and the client the token is for and must not be guessable.

  4. Send an HTTP response that redirects the user's browser to the URL specified by the redirect_uri parameter. Include all of the following parameters in the URL fragment:

    • access_token: The access token you just generated
    • token_type: The string bearer
    • state: The unmodified state value from the original request

    The following is an example of the resulting URL:

    https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID#access_token=ACCESS_TOKEN&token_type=bearer&state=STATE_STRING

Google's OAuth 2.0 redirect handler receives the access token and confirms that the state value hasn't changed. After Google has obtained an access token for your service, Google attaches the token to subsequent calls to your service APIs.

处理 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 可选:用户的个人资料照片。

Cómo validar la implementación

您可以使用 OAuth 2.0 Playground 工具验证您的实现。

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

  1. 点击配置 以打开 OAuth 2.0 配置窗口。
  2. OAuth flow 字段中,选择 Client-side(客户端)。
  3. OAuth 端点字段中,选择自定义
  4. 在相应字段中指定您的 OAuth 2.0 端点和您分配给 Google 的客户端 ID。
  5. 第 1 步部分,不要选择任何 Google 范围。请将此字段留空或输入对服务器有效的范围(如果您不使用 OAuth 范围,则可以输入任意字符串)。完成后,点击授权 API
  6. Step 2Step 3 部分中,完成 OAuth 2.0 流程,并验证每个步骤是否按预期运行。

您可以使用 Google 账号关联演示版工具验证您的实现。

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

  1. 点击使用 Google 账号登录按钮。
  2. 选择您要关联的账号。
  3. 输入服务 ID。
  4. (可选)输入您要请求访问权限的一个或多个范围。
  5. 点击开始演示
  6. 当系统提示时,请确认您同意或拒绝关联请求。
  7. 确认您已被重定向到您的平台。