As contas são vinculadas usando o fluxo padrão do setor de código de autorização do OAuth 2.0.
OAuth 2.1 e PKCE para agentes
Para agentes de IA sem estado e pipelines multimodais, é recomendável usar a aplicação do OAuth 2.1.
- PKCE (chave de prova para troca de código): precisa ser usado para proteger o fluxo do código de autorização, evitando ataques de interceptação.
- Sem fluxo implícito: o fluxo implícito expõe tokens de acesso no URL, o que é um risco de segurança para ambientes de agentes.
Seu serviço precisa oferecer suporte a endpoints de autorização e troca de tokens compatíveis com OAuth 2.0/2.1.
Criar o projeto
Para criar seu projeto para usar a vinculação de contas:
- Vá para o Console de APIs do Google.
- Clique em Criar projeto.
- Insira um nome ou aceite a sugestão gerada.
- Confirme ou edite os campos restantes.
- Clique em Criar.
Para conferir o ID do projeto:
- Vá para o Console de APIs do Google.
- Encontre seu projeto na tabela da página de destino. O ID do projeto aparece na ID coluna.
Configurar a tela de permissão OAuth
O processo de conexão de contas do Google inclui uma tela de permissão que informa aos usuários o aplicativo que está solicitando acesso aos dados deles, o tipo de dados que estão pedindo e os termos aplicáveis. Você precisa configurar a tela de permissão OAuth antes de gerar um ID do cliente da API Google.
- Abra a página da tela de permissão OAuth do console de APIs do Google.
- Se solicitado, selecione o projeto que você acabou de criar.
Na página "Tela de permissão OAuth", preencha o formulário e clique no botão "Salvar".
Nome do aplicativo:o nome do aplicativo que precisa da permissão. O nome precisa refletir com precisão o aplicativo e ser consistente com o nome que os usuários veem em outros lugares. O nome do aplicativo será mostrado na tela de permissão de vinculação de contas.
Logotipo do aplicativo: uma imagem na tela de permissão que ajuda os usuários a reconhecer seu app. O logotipo é mostrado na tela de permissão de vinculação de contas e nas configurações da conta
E-mail de suporte:para que os usuários entrem em contato com você para esclarecer dúvidas sobre o consentimento deles.
Escopos para APIs Google:os escopos permitem que seu aplicativo acesse os dados do Google particulares do usuário. Para o caso de uso de vinculação de contas do Google, o escopo padrão (e-mail, perfil, openid) é suficiente. Não é necessário adicionar escopos sensíveis. Geralmente, é uma prática recomendada solicitar escopos de forma incremental, no momento em que o acesso é necessário, em vez de antecipadamente. Saiba mais.
Domínios autorizados:para proteger você e seus usuários, o Google permite apenas que aplicativos autenticados usando o OAuth usem domínios autorizados. Os links dos seus aplicativos precisam ser hospedados em domínios autorizados. Saiba mais.
Link da página inicial do aplicativo:página inicial do seu aplicativo. Precisa ser hospedado em um domínio autorizado.
Link da Política de Privacidade do aplicativo:mostrado na tela de permissão de vinculação de contas do Google. Precisa ser hospedado em um domínio autorizado.
Link dos Termos de Serviço do aplicativo (opcional) : precisa ser hospedado em um domínio autorizado.
Figura 1. Tela de permissão de vinculação de contas do Google para um aplicativo fictício, o Tunery
Verifique o "Status da verificação". Se o aplicativo precisar de verificação, clique no botão "Enviar para verificação" para enviar o aplicativo. Consulte os requisitos de verificação do OAuth para mais detalhes.
Implementar seu servidor OAuth
An OAuth 2.0 server implementation of the authorization code flow consists of two endpoints, which your service makes available by HTTPS. The first endpoint is the authorization endpoint, which is responsible for finding or 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. The second endpoint is the token exchange endpoint, which is used to obtain encrypted strings, called tokens, that authorize a user to access your service.
When a Google application needs to call one of your service's APIs, Google uses these endpoints together to get permission from your users to call these APIs on their behalf.
Google Account Linking: OAuth Authorization Code Flow
The following sequence diagram details interactions between the User, Google, and your service's endpoints.
Roles and responsibilities
The following table defines the roles and responsibilities of the actors in the Google Account Linking (GAL) OAuth flow. Note that in GAL, Google acts as the OAuth Client, while your service acts as the Identity/Service Provider.
| Actor / Component | GAL Role | Responsibilities |
|---|---|---|
| Google App / Server | OAuth Client | Initiates the flow, receives the authorization code, exchanges it for tokens, and securely stores them to access your service's APIs. |
| Your Authorization Endpoint | Authorization Server | Authenticates your users and obtains their consent to share access to their data with Google. |
| Your Token Exchange Endpoint | Authorization Server | Validates authorization codes and refresh tokens, and issues access tokens to the Google Server. |
| Google Redirect URI | Callback Endpoint | Receives the user redirect from your authorization service with the
code and state values. |
An OAuth 2.0 authorization code flow session initiated by Google has the following flow:
- Google opens your authorization endpoint in the user's browser. If the flow started on a voice-only device for an Action, Google transfers the execution to a phone.
- 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.
- Your service creates an authorization code and returns it to Google. To do so, redirect the user's browser back to Google with the authorization code attached to the request.
- Google sends the authorization code to your token exchange endpoint, which verifies the authenticity of the code and returns an access token and a refresh token. The access token is a short-lived token that your service accepts as credentials to access APIs. The refresh token is a long-lived token that Google can store and use to acquire new access tokens when they expire.
- After the user has completed the account linking flow, every subsequent request sent from Google contains an access token.
Implementation Recipe
Follow these steps to implement the Authorization Code flow.
Step 1: Handle authorization requests
When Google initiates account linking, it redirects the user to your authorization endpoint. For detailed protocol contracts and parameter requirements, see the Authorization Endpoint.
To handle the request, perform the following actions:
Validate the request:
- Confirm that the
client_idmatches the Client ID assigned to Google. - Confirm that the
redirect_urimatches the expected Google redirect URL:none https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID https://oauth-redirect-sandbox.googleusercontent.com/r/YOUR_PROJECT_ID - Verify that
response_typeiscode.
- Confirm that the
Authenticate the user:
- Check if the user is signed in to your service.
- If the user is not signed in, prompt them to complete your sign-in or sign-up flow.
Generate authorization code:
- Create a unique, non-guessable authorization code associated with the user and client.
- Set the code to expire in approximately 10 minutes.
Redirect back to Google:
- Redirect the browser to the URL provided in
redirect_uri. - Append the following query parameters:
code: The authorization code you generated.state: The unmodified state value received from Google.
- Redirect the browser to the URL provided in
Step 2: Handle token exchange requests
Your token exchange endpoint processes two types of requests: exchanging codes for tokens, and refreshing expired access tokens. For detailed protocol contracts and parameter requirements, see the Token Exchange Endpoint.
A. Exchange authorization codes for tokens
When Google receives the authorization code, it calls your token exchange endpoint (POST) to retrieve tokens.
Validate the request:
- Verify
client_idandclient_secret. - Verify the authorization code is valid and not expired.
- Confirm
redirect_urimatches the value used in Step 1. - If validation fails, return an HTTP
400 Bad Requestwith{"error": "invalid_grant"}.
- Verify
Issue tokens:
- Generate a long-lived
refresh_tokenand a short-livedaccess_token(typically 1 hour). - Return an HTTP
200 OKwith the standard JSON token response.
- Generate a long-lived
B. Refresh access tokens
When the access token expires, Google requests a new one using the refresh token.
Validate the request:
- Verify
client_id,client_secret, andrefresh_token. - If validation fails, return an HTTP
400 Bad Requestwith{"error": "invalid_grant"}.
- Verify
Issue new access token:
- Generate a new short-lived
access_token. - Return an HTTP
200 OKwith the JSON token response (optionally including a new refresh token).
- Generate a new short-lived
Handle userinfo requests
The userinfo endpoint is an OAuth 2.0 protected resource that return claims about the linked user. Implementing and hosting the userinfo endpoint is optional, except for the following use cases:
- Linked Account Sign-In with Google One Tap.
- Frictionless subscription on AndroidTV.
After the access token has been successfully retrieved from your token endpoint, Google sends a request to your userinfo endpoint to retrieve basic profile information about the linked user.
| userinfo endpoint request headers | |
|---|---|
Authorization header |
The access token of type Bearer. |
For example, if your userinfo endpoint is available at
https://myservice.example.com/userinfo, a request might look like the following:
GET /userinfo HTTP/1.1 Host: myservice.example.com Authorization: Bearer ACCESS_TOKEN
For your userinfo endpoint to handle requests, do the following steps:
- Extract access token from the Authorization header and return information for the user associated with the access token.
- If the access token is invalid, return an HTTP 401 Unauthorized error with using the
WWW-AuthenticateResponse Header. Below is an example of a userinfo error response: If a 401 Unauthorized, or any other unsuccessful error response is returned during the linking process, the error will be non-recoverable, the retrieved token will be discarded and the user will have to initiate the linking process again.HTTP/1.1 401 Unauthorized WWW-Authenticate: error="invalid_token", error_description="The Access Token expired"
If the access token is valid, return and HTTP 200 response with the following JSON object in the body of the HTTPS response:
If your userinfo endpoint returns an HTTP 200 success response, the retrieved token and claims are registered against the user's Google account.{ "sub": "USER_UUID", "email": "EMAIL_ADDRESS", "given_name": "FIRST_NAME", "family_name": "LAST_NAME", "name": "FULL_NAME", "picture": "PROFILE_PICTURE", }userinfo endpoint response subA unique ID that identifies the user in your system. emailEmail address of the user. given_nameOptional: First name of the user. family_nameOptional: Last name of the user. nameOptional: Full name of the user. pictureOptional: Profile picture of the user.
Como validar a implementação
Use a ferramenta OAuth 2.0 Playground para validar sua implementação.
Na ferramenta, siga estas etapas:
- Clique em Configuração para abrir a janela de configuração do OAuth 2.0.
- No campo Fluxo do OAuth, selecione Do lado do cliente.
- No campo Endpoints OAuth, selecione Personalizado.
- Especifique seu endpoint OAuth 2.0 e o ID do cliente atribuído ao Google nos campos correspondentes.
- Na seção Etapa 1, não selecione nenhum escopo do Google. Em vez disso, deixe esse campo em branco ou digite um escopo válido para seu servidor (ou uma string arbitrária se você não usar escopos do OAuth). Quando terminar, clique em Autorizar APIs.
- Nas seções Etapa 2 e Etapa 3, siga o fluxo do OAuth 2.0 e verifique se cada etapa funciona como esperado.
Você pode validar sua implementação usando a ferramenta Demonstração da Vinculação da Conta do Google.
Na ferramenta, siga estas etapas:
- Clique no botão Fazer login com o Google.
- Escolha a conta que você quer vincular.
- Insira o ID do serviço.
- Se quiser, insira um ou mais escopos para os quais você vai solicitar acesso.
- Clique em Iniciar demonstração.
- Quando solicitado, confirme que você pode consentir e negar o pedido de vinculação.
- Confirme se você foi redirecionado para sua plataforma.