Descripción general
La vinculación optimizada de Acceso con Google basada en OAuth agrega Acceso con Google además de la vinculación de OAuth. Esto proporciona una experiencia de vinculación fluida para los usuarios de Google y también habilita la creación de cuentas, lo que permite que el usuario cree una cuenta nueva en tu servicio con su Cuenta de Google.
Para realizar la vinculación de cuentas con OAuth y Acceder con Google, sigue estos pasos generales:
- Primero, pídele al usuario que otorgue su consentimiento para acceder a su perfil de Google.
- Usa la información de su perfil para verificar si existe la cuenta de usuario.
- En el caso de los usuarios existentes, vincula las cuentas.
- Si no encuentras una coincidencia para el usuario de Google en tu sistema de autenticación, valida el token de ID que recibiste de Google. Luego, puedes crear un usuario en función de la información del perfil contenida en el token de ID.
Figura 1. Vinculación de cuentas en el teléfono de un usuario con la vinculación optimizada
Requisitos para la vinculación optimizada
- Implementa el flujo de vinculación web básica de OAuth. Tu servicio debe admitir extremos de autorización y intercambio de tokens que cumplan con OAuth 2.0.
- Tu extremo de intercambio de tokens debe admitir aserciones de token web JSON (JWT) y, además, implementar los intents
check,createyget.
Implementa tu servidor de OAuth
Tu extremo de intercambio de tokens debe admitir los intents check, create y get. A continuación, se muestran los pasos completados a través del flujo de vinculación de cuentas y se indica cuándo se llama a los diferentes intents:
- ¿El usuario tiene una cuenta en tu sistema de autenticación? (El usuario decide si selecciona SÍ o NO)
- SÍ: ¿El usuario usa el correo electrónico asociado a su Cuenta de Google para acceder a tu plataforma? (El usuario decide seleccionando SÍ o NO)
- SÍ: ¿El usuario tiene una cuenta coincidente en tu sistema de autenticación? (se llama a
check intentpara confirmar)- SÍ : Se llama a
get intenty la cuenta se vincula si get intent se muestra correctamente. - NO: ¿Crear una cuenta nueva? (El usuario decide seleccionando SÍ o NO)
- SÍ : Se llama a
create intenty la cuenta se vincula si el intent de creación se muestra correctamente. - NO : Se activa el flujo de OAuth web, se dirige al usuario a su navegador y se le da la opción de vincular con un correo electrónico diferente.
- SÍ : Se llama a
- SÍ : Se llama a
- NO : Se activa el flujo de OAuth web, se dirige al usuario a su navegador y se le brinda la opción de vincular con un correo electrónico diferente.
- SÍ: ¿El usuario tiene una cuenta coincidente en tu sistema de autenticación? (se llama a
- NO: ¿El usuario tiene una cuenta coincidente en tu sistema de autenticación? (se llama a
check intentpara confirmar)- SÍ : Se llama a
get intenty la cuenta se vincula si get intent se muestra correctamente. - NO : Se llama a
create intenty la cuenta se vincula si el intent de creación se muestra correctamente.
- SÍ : Se llama a
- SÍ: ¿El usuario usa el correo electrónico asociado a su Cuenta de Google para acceder a tu plataforma? (El usuario decide seleccionando SÍ o NO)
Check for an existing user account (check intent)
After the user gives consent to access their Google profile, Google sends a request that contains a signed assertion of the Google user's identity. The assertion contains information that includes the user's Google Account ID, name, and email address. The token exchange endpoint configured for your project handles that request.
If the corresponding Google account is already present in your authentication
system, your token exchange endpoint responds with account_found=true. If the
Google account doesn't match an existing user, your token exchange endpoint
returns an HTTP 404 Not Found error with account_found=false.
The request has the following form:
POST /token HTTP/1.1 Host: oauth2.example.com Content-Type: application/x-www-form-urlencoded grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&intent=check&assertion=JWT&scope=SCOPES&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET
Your token exchange endpoint must be able to handle the following parameters:
| Token endpoint parameters | |
|---|---|
intent |
For these requests, the value of this parameter is
check. |
grant_type |
The type of token being exchanged. For these requests, this
parameter has the value urn:ietf:params:oauth:grant-type:jwt-bearer. |
assertion |
A JSON Web Token (JWT) that provides a signed assertion of the Google user's identity. The JWT contains information that includes the user's Google Account ID, name, and email address. |
client_id |
The client ID you assigned to Google. |
client_secret |
The client secret you assigned to Google. |
To respond to the check intent requests, your token exchange endpoint must perform the following steps:
- Validate and decode the JWT assertion.
- Check if the Google account is already present in your authentication system.
Valida y decodifica la aserción de JWT
Puedes validar y decodificar la aserción de JWT con un Biblioteca de decodificación JWT para tu lenguaje. Usa las claves públicas de Google, disponibles en JWK o PEM para verificar la firma del token.
Cuando se decodifica, la aserción de JWT luce como el siguiente ejemplo:
{ "sub": "1234567890", // The unique ID of the user's Google Account "iss": "https://accounts.google.com", // The assertion's issuer "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID "iat": 233366400, // Unix timestamp of the assertion's creation time "exp": 233370000, // Unix timestamp of the assertion's expiration time "name": "Jan Jansen", "given_name": "Jan", "family_name": "Jansen", "email": "jan@gmail.com", // If present, the user's email address "email_verified": true, // true, if Google has verified the email address "hd": "example.com", // If present, the host domain of the user's GSuite email address // If present, a URL to user's profile picture "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ", "locale": "en_US" // User's locale, from browser or phone settings }
Además de verificar la firma del token, comprueba que el token de la aserción
entidad emisora (campo iss) es https://accounts.google.com, que el público
(campo aud) es tu ID de cliente asignado y que el token no haya vencido.
(Campo exp).
Usa los campos email, email_verified y hd para determinar si
Google aloja una dirección de correo electrónico y tiene la autoridad para hacerlo. En los casos en que Google sea
autorizado, se sabe que el usuario actualmente es el propietario legítimo de la cuenta
y puedes omitir la contraseña y otros métodos de verificación de identidad. De lo contrario, estos métodos
se puede usar para verificar la cuenta antes de realizar la vinculación.
Casos en los que Google es confiable:
emailtiene el sufijo@gmail.com; esta es una cuenta de Gmail.email_verifiedes verdadero yhdestá configurado. Esta es una cuenta de G Suite.
Los usuarios pueden registrarse en Cuentas de Google sin usar Gmail ni G Suite. Cuándo
email no contiene un sufijo @gmail.com ni hd, ni tampoco
se recomienda verificar con métodos de verificación, tanto confiables como con contraseñas
del usuario. email_verified también puede ser verdadero, ya que Google verificó inicialmente el
usuario cuando se creó la cuenta de Google, sin embargo, la propiedad del tercero
de correo electrónico puede haber cambiado desde entonces.
Check if the Google account is already present in your authentication system
Check whether either of the following conditions are true:
- The Google Account ID, found in the assertion's
subfield, is in your user database. - The email address in the assertion matches a user in your user database.
If either condition is true, the user has already signed up. In that case, return a response like the following:
HTTP/1.1 200 Success
Content-Type: application/json;charset=UTF-8
{
"account_found":"true",
}
If neither the Google Account ID nor the email address specified in the
assertion matches a user in your database, the user hasn't signed up yet. In
this case, your token exchange endpoint needs to reply with a HTTP 404 error
that specifies "account_found": "false", as in the following example:
HTTP/1.1 404 Not found
Content-Type: application/json;charset=UTF-8
{
"account_found":"false",
}
Handle automatic linking (get intent)
After the user gives consent to access their Google profile, Google sends a request that contains a signed assertion of the Google user's identity. The assertion contains information that includes the user's Google Account ID, name, and email address. The token exchange endpoint configured for your project handles that request.
If the corresponding Google Account is already present in your authentication
system, your token exchange endpoint returns a token for the user. If the
Google Account doesn't match an existing user, your token exchange endpoint
returns a linking_error error and optional login_hint.
The request has the following form:
POST /token HTTP/1.1 Host: oauth2.example.com Content-Type: application/x-www-form-urlencoded grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&intent=get&assertion=JWT&scope=SCOPES&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET
Your token exchange endpoint must be able to handle the following parameters:
| Token endpoint parameters | |
|---|---|
intent |
For these requests, the value of this parameter is get. |
grant_type |
The type of token being exchanged. For these requests, this
parameter has the value urn:ietf:params:oauth:grant-type:jwt-bearer. |
assertion |
A JSON Web Token (JWT) that provides a signed assertion of the Google user's identity. The JWT contains information that includes the user's Google Account ID, name, and email address. |
scope |
Optional: Any scopes that you've configured Google to request from users. |
client_id |
The client ID you assigned to Google. |
client_secret |
The client secret you assigned to Google. |
To respond to the get intent requests, your token exchange endpoint must perform the following steps:
- Validate and decode the JWT assertion.
- Check if the Google account is already present in your authentication system.
Valida y decodifica la aserción de JWT
Puedes validar y decodificar la aserción de JWT con un Biblioteca de decodificación JWT para tu lenguaje. Usa las claves públicas de Google, disponibles en JWK o PEM para verificar la firma del token.
Cuando se decodifica, la aserción de JWT luce como el siguiente ejemplo:
{ "sub": "1234567890", // The unique ID of the user's Google Account "iss": "https://accounts.google.com", // The assertion's issuer "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID "iat": 233366400, // Unix timestamp of the assertion's creation time "exp": 233370000, // Unix timestamp of the assertion's expiration time "name": "Jan Jansen", "given_name": "Jan", "family_name": "Jansen", "email": "jan@gmail.com", // If present, the user's email address "email_verified": true, // true, if Google has verified the email address "hd": "example.com", // If present, the host domain of the user's GSuite email address // If present, a URL to user's profile picture "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ", "locale": "en_US" // User's locale, from browser or phone settings }
Además de verificar la firma del token, comprueba que el token de la aserción
entidad emisora (campo iss) es https://accounts.google.com, que el público
(campo aud) es tu ID de cliente asignado y que el token no haya vencido.
(Campo exp).
Usa los campos email, email_verified y hd para determinar si
Google aloja una dirección de correo electrónico y tiene la autoridad para hacerlo. En los casos en que Google sea
autorizado, se sabe que el usuario actualmente es el propietario legítimo de la cuenta
y puedes omitir la contraseña y otros métodos de verificación de identidad. De lo contrario, estos métodos
se puede usar para verificar la cuenta antes de realizar la vinculación.
Casos en los que Google es confiable:
emailtiene el sufijo@gmail.com; esta es una cuenta de Gmail.email_verifiedes verdadero yhdestá configurado. Esta es una cuenta de G Suite.
Los usuarios pueden registrarse en Cuentas de Google sin usar Gmail ni G Suite. Cuándo
email no contiene un sufijo @gmail.com ni hd, ni tampoco
se recomienda verificar con métodos de verificación, tanto confiables como con contraseñas
del usuario. email_verified también puede ser verdadero, ya que Google verificó inicialmente el
usuario cuando se creó la cuenta de Google, sin embargo, la propiedad del tercero
de correo electrónico puede haber cambiado desde entonces.
Check if the Google account is already present in your authentication system
Check whether either of the following conditions are true:
- The Google Account ID, found in the assertion's
subfield, is in your user database. - The email address in the assertion matches a user in your user database.
If an account is found for the user, issue an access token and return the values in a JSON object in the body of your HTTPS response, like in the following example:
{ "token_type": "Bearer", "access_token": "ACCESS_TOKEN", "refresh_token": "REFRESH_TOKEN", "expires_in": SECONDS_TO_EXPIRATION }
In some cases, account linking based on ID token might fail for the user. If it
does so for any reason, your token exchange endpoint needs to reply with a HTTP
401 error that specifies error=linking_error, as the following example shows:
HTTP/1.1 401 Unauthorized
Content-Type: application/json;charset=UTF-8
{
"error":"linking_error",
"login_hint":"foo@bar.com"
}
When Google receives a 401 error response with linking_error, Google sends
the user to your authorization endpoint with login_hint as a parameter. The
user completes account linking using the OAuth linking flow in their browser.
Handle account creation via Google Sign-In (create intent)
When a user needs to create an account on your service, Google makes a request
to your token exchange endpoint that specifies intent=create.
The request has the following form:
POST /token HTTP/1.1 Host: oauth2.example.com Content-Type: application/x-www-form-urlencoded response_type=token&grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&scope=SCOPES&intent=create&assertion=JWT&client_id=GOOGLE_CLIENT_ID&client_secret=GOOGLE_CLIENT_SECRET
Your token exchange endpoint must able to handle the following parameters:
| Token endpoint parameters | |
|---|---|
intent |
For these requests, the value of this parameter is create. |
grant_type |
The type of token being exchanged. For these requests, this
parameter has the value urn:ietf:params:oauth:grant-type:jwt-bearer. |
assertion |
A JSON Web Token (JWT) that provides a signed assertion of the Google user's identity. The JWT contains information that includes the user's Google Account ID, name, and email address. |
client_id |
The client ID you assigned to Google. |
client_secret |
The client secret you assigned to Google. |
The JWT within the assertion parameter contains the user's Google Account ID,
name, and email address, which you can use to create a new account on your
service.
To respond to the create intent requests, your token exchange endpoint must perform the following steps:
- Validate and decode the JWT assertion.
- Validate user information and create new account.
Valida y decodifica la aserción de JWT
Puedes validar y decodificar la aserción de JWT con un Biblioteca de decodificación JWT para tu lenguaje. Usa las claves públicas de Google, disponibles en JWK o PEM para verificar la firma del token.
Cuando se decodifica, la aserción de JWT luce como el siguiente ejemplo:
{ "sub": "1234567890", // The unique ID of the user's Google Account "iss": "https://accounts.google.com", // The assertion's issuer "aud": "123-abc.apps.googleusercontent.com", // Your server's client ID "iat": 233366400, // Unix timestamp of the assertion's creation time "exp": 233370000, // Unix timestamp of the assertion's expiration time "name": "Jan Jansen", "given_name": "Jan", "family_name": "Jansen", "email": "jan@gmail.com", // If present, the user's email address "email_verified": true, // true, if Google has verified the email address "hd": "example.com", // If present, the host domain of the user's GSuite email address // If present, a URL to user's profile picture "picture": "https://lh3.googleusercontent.com/a-/AOh14GjlTnZKHAeb94A-FmEbwZv7uJD986VOF1mJGb2YYQ", "locale": "en_US" // User's locale, from browser or phone settings }
Además de verificar la firma del token, comprueba que el token de la aserción
entidad emisora (campo iss) es https://accounts.google.com, que el público
(campo aud) es tu ID de cliente asignado y que el token no haya vencido.
(Campo exp).
Usa los campos email, email_verified y hd para determinar si
Google aloja una dirección de correo electrónico y tiene la autoridad para hacerlo. En los casos en que Google sea
autorizado, se sabe que el usuario actualmente es el propietario legítimo de la cuenta
y puedes omitir la contraseña y otros métodos de verificación de identidad. De lo contrario, estos métodos
se puede usar para verificar la cuenta antes de realizar la vinculación.
Casos en los que Google es confiable:
emailtiene el sufijo@gmail.com; esta es una cuenta de Gmail.email_verifiedes verdadero yhdestá configurado. Esta es una cuenta de G Suite.
Los usuarios pueden registrarse en Cuentas de Google sin usar Gmail ni G Suite. Cuándo
email no contiene un sufijo @gmail.com ni hd, ni tampoco
se recomienda verificar con métodos de verificación, tanto confiables como con contraseñas
del usuario. email_verified también puede ser verdadero, ya que Google verificó inicialmente el
usuario cuando se creó la cuenta de Google, sin embargo, la propiedad del tercero
de correo electrónico puede haber cambiado desde entonces.
Validate user information and create new account
Check whether either of the following conditions are true:
- The Google Account ID, found in the assertion's
subfield, is in your user database. - The email address in the assertion matches a user in your user database.
If either condition is true, prompt the user to link their existing account
with their Google Account. To do so, respond to the request with an HTTP 401 error
that specifies error=linking_error and gives the user's email address as the
login_hint. The following is a sample response:
HTTP/1.1 401 Unauthorized
Content-Type: application/json;charset=UTF-8
{
"error":"linking_error",
"login_hint":"foo@bar.com"
}
When Google receives a 401 error response with linking_error, Google sends
the user to your authorization endpoint with login_hint as a parameter. The
user completes account linking using the OAuth linking flow in their browser.
If neither condition is true, create a new user account with the information provided in the JWT. New accounts don't typically have a password set. It's recommended that you add Google Sign-In to other platforms to enable users to log in with Google across the surfaces of your application. Alternatively, you can email the user a link that starts your password recovery flow to allow the user to set a password to sign in on other platforms.
When the creation is completed, issue an access token and refresh token and return the values in a JSON object in the body of your HTTPS response, like in the following example:
{ "token_type": "Bearer", "access_token": "ACCESS_TOKEN", "refresh_token": "REFRESH_TOKEN", "expires_in": SECONDS_TO_EXPIRATION }
Obtén tu ID de cliente de la API de Google
Se te solicitará que proporciones tu ID de cliente de la API de Google durante el proceso de registro de la vinculación de cuentas.
Para obtener tu ID de cliente de la API con el proyecto que creaste mientras completabas los pasos de Vinculación de OAuth. Para ello, completa los siguientes pasos:
Crea o selecciona un proyecto de APIs de Google.
Si tu proyecto no tiene un ID de cliente para el tipo de aplicación web, haz clic en Crear cliente para crear uno. Asegúrate de incluir el dominio de tu sitio en el cuadro Orígenes autorizados de JavaScript. Cuando realices pruebas o desarrollo locales, debes agregar
http://localhostyhttp://localhost:<port_number>al campo Orígenes autorizados de JavaScript.
Cómo validar la implementación
您可以使用 OAuth 2.0 Playground 工具验证您的实现。
在该工具中,执行以下步骤:
- 点击配置 以打开 OAuth 2.0 配置窗口。
- 在 OAuth flow 字段中,选择 Client-side(客户端)。
- 在 OAuth 端点字段中,选择自定义。
- 在相应字段中指定您的 OAuth 2.0 端点和您分配给 Google 的客户端 ID。
- 在第 1 步部分,不要选择任何 Google 范围。请将此字段留空或输入对服务器有效的范围(如果您不使用 OAuth 范围,则可以输入任意字符串)。完成后,点击授权 API。
- 在 Step 2 和 Step 3 部分中,完成 OAuth 2.0 流程,并验证每个步骤是否按预期运行。
您可以使用 Google 账号关联演示版工具验证您的实现。
在该工具中,执行以下步骤:
- 点击使用 Google 账号登录按钮。
- 选择您要关联的账号。
- 输入服务 ID。
- (可选)输入您要请求访问权限的一个或多个范围。
- 点击开始演示。
- 当系统提示时,请确认您同意或拒绝关联请求。
- 确认您已被重定向到您的平台。