Se você usa o Login do Google com um app ou site que se comunica com um back-end servidor, talvez seja necessário identificar o usuário atualmente conectado nele. Para fazer isso de forma segura, depois que um usuário fizer login, envie o token de ID para seu servidor usando HTTPS. Em seguida, no servidor, verifique a integridade do token de ID e use as informações do usuário contidas no token para estabelecer uma sessão ou criar uma nova conta.
Enviar o token de ID para seu servidor
Primeiro, quando o usuário fizer login, receba o token de ID:
-
Quando você configurar o Login do Google, chame o método
requestIdTokene transmiti-lo ao ID do cliente da Web do servidor.// Request only the user's ID token, which can be used to identify the // user securely to your backend. This will contain the user's basic // profile (name, profile picture URL, etc) so you should not need to // make an additional call to personalize your application. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.server_client_id)) .requestEmail() .build();
-
Quando seu app for iniciado, verifique se o usuário já fez login nele usando o Google: neste dispositivo ou em outro, chamando
silentSignIn:GoogleSignIn.silentSignIn() .addOnCompleteListener( this, new OnCompleteListener<GoogleSignInAccount>() { @Override public void onComplete(@NonNull Task<GoogleSignInAccount> task) { handleSignInResult(task); } });
-
Se o usuário não conseguir fazer login silenciosamente, apresente o normalmente do usuário, oferecendo ao usuário a opção de fazer login. Quando o usuário faz sinalizar in, acesse o
GoogleSignInAccountdo usuário na atividade da intent de login:// This task is always completed immediately, there is no need to attach an // asynchronous listener. Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignInResult(task);
-
Depois que o usuário faz login de maneira silenciosa ou explícita, receba o token de ID do objeto
GoogleSignInAccount:private void handleSignInResult(@NonNull Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); String idToken = account.getIdToken(); // TODO(developer): send ID Token to server and validate updateUI(account); } catch (ApiException e) { Log.w(TAG, "handleSignInResult:error", e); updateUI(null); } }
Em seguida, envie o token de ID para o seu servidor com uma solicitação POST HTTPS:
HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("https://yourbackend.example.com/tokensignin"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("idToken", idToken)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); final String responseBody = EntityUtils.toString(response.getEntity()); Log.i(TAG, "Signed in as: " + responseBody); } catch (ClientProtocolException e) { Log.e(TAG, "Error sending ID token to backend.", e); } catch (IOException e) { Log.e(TAG, "Error sending ID token to backend.", e); }
Verificar a integridade do token de ID
Depois de receber o token de ID por HTTPS POST, verifique a integridade do token.
Para verificar se o token é válido, confira se os seguintes critérios são atendidos:
- O token de ID é assinado corretamente pelo Google. Use as chaves públicas do Google
(disponíveis nos formatos
JWK ou
PEM)
para verificar a assinatura do token. Essas chaves são trocadas regularmente. Examine o cabeçalho
Cache-Controlna resposta para determinar quando você deve recuperá-las novamente. - O valor de
audno token de ID é igual a um dos IDs de cliente do seu app. Essa verificação é necessária para evitar que tokens de ID emitidos para um app malicioso sejam usados para acessar dados sobre o mesmo usuário no servidor de back-end do seu app. - O valor de
issno token de ID é igual aaccounts.google.comouhttps://accounts.google.com. - O prazo de validade (
exp) do token de ID ainda não expirou. - Se você precisar validar se o token de ID representa uma conta de organização do Google Workspace ou do Cloud, verifique a declaração
hd, que indica o domínio hospedado do usuário. Isso precisa ser usado ao restringir o acesso a um recurso apenas a membros de determinados domínios. A ausência dessa declaração indica que a conta não pertence a um domínio hospedado pelo Google.
Usando os campos email, email_verified e hd, você pode determinar se o Google hospeda e é autoridade para um endereço de e-mail. Nos casos em que o Google é autoritário, o usuário é conhecido como o proprietário legítimo da conta, e você pode pular a senha ou outros métodos de desafio.
Casos em que o Google é autoridade:
- Se o nome de usuário de
emailtiver o sufixo@gmail.com, ele será uma conta do Gmail. email_verifiedé verdadeiro ehdestá definido, essa é uma conta do Google Workspace.
Os usuários podem se registrar para ter Contas do Google sem usar o Gmail ou o Google Workspace. Quando email não contém um sufixo @gmail.com e hd está ausente, o Google não é autoritário, e é recomendável usar senha ou outros métodos de desafio para verificar o usuário. email_verified também pode ser verdadeiro, já que o Google verificou inicialmente o usuário quando a Conta do Google foi criada. No entanto, a propriedade da conta de e-mail de terceiros pode ter mudado desde então.
Em vez de escrever seu próprio código para realizar essas etapas de verificação, recomendamos usar uma biblioteca de cliente das APIs do Google para sua plataforma ou uma biblioteca JWT de uso geral. Para desenvolvimento e depuração, chame nosso endpoint de validação tokeninfo.
Using a Google API Client Library
Using one of the Google API Client Libraries (e.g. Java, Node.js, PHP, Python) is the recommended way to validate Google ID tokens in a production environment.
To validate an ID token in Java, use the GoogleIdTokenVerifier object. For example:
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken; import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload; import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier; ... GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory) // Specify the WEB_CLIENT_ID of the app that accesses the backend: .setAudience(Collections.singletonList(WEB_CLIENT_ID)) // Or, if multiple clients access the backend: //.setAudience(Arrays.asList(WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3)) .build(); // (Receive idTokenString by HTTPS POST) GoogleIdToken idToken = verifier.verify(idTokenString); if (idToken != null) { Payload payload = idToken.getPayload(); // Print user identifier. This ID is unique to each Google Account, making it suitable for // use as a primary key during account lookup. Email is not a good choice because it can be // changed by the user. String userId = payload.getSubject(); System.out.println("User ID: " + userId); // Get profile information from payload String email = payload.getEmail(); boolean emailVerified = Boolean.valueOf(payload.getEmailVerified()); String name = (String) payload.get("name"); String pictureUrl = (String) payload.get("picture"); String locale = (String) payload.get("locale"); String familyName = (String) payload.get("family_name"); String givenName = (String) payload.get("given_name"); // Use or store profile information // ... } else { System.out.println("Invalid ID token."); }
The GoogleIdTokenVerifier.verify() method verifies the JWT
signature, the aud claim, the iss claim, and the
exp claim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can verify the hd claim by checking the domain name
returned by the Payload.getHostedDomain() method. The domain of the
email claim is insufficient to ensure that the account is managed by a domain
or organization.
To validate an ID token in Node.js, use the Google Auth Library for Node.js. Install the library:
npm install google-auth-library --save
verifyIdToken() function. For example:
const {OAuth2Client} = require('google-auth-library'); const client = new OAuth2Client(); async function verify() { const ticket = await client.verifyIdToken({ idToken: token, audience: WEB_CLIENT_ID, // Specify the WEB_CLIENT_ID of the app that accesses the backend // Or, if multiple clients access the backend: //[WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3] }); const payload = ticket.getPayload(); // This ID is unique to each Google Account, making it suitable for use as a primary key // during account lookup. Email is not a good choice because it can be changed by the user. const userid = payload['sub']; // If the request specified a Google Workspace domain: // const domain = payload['hd']; } verify().catch(console.error);
The verifyIdToken function verifies
the JWT signature, the aud claim, the exp claim,
and the iss claim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can check the hd claim, which indicates the hosted
domain of the user. This must be used when restricting access to a resource to only members
of certain domains. The absence of this claim indicates that the account does not belong to
a Google hosted domain.
To validate an ID token in PHP, use the Google API Client Library for PHP. Install the library (for example, using Composer):
composer require google/apiclient
verifyIdToken() function. For example:
require_once 'vendor/autoload.php'; // Get $id_token via HTTPS POST. $client = new Google_Client(['client_id' => $WEB_CLIENT_ID]); // Specify the WEB_CLIENT_ID of the app that accesses the backend $payload = $client->verifyIdToken($id_token); if ($payload) { // This ID is unique to each Google Account, making it suitable for use as a primary key // during account lookup. Email is not a good choice because it can be changed by the user. $userid = $payload['sub']; // If the request specified a Google Workspace domain //$domain = $payload['hd']; } else { // Invalid ID token }
The verifyIdToken function verifies
the JWT signature, the aud claim, the exp claim,
and the iss claim.
If you need to validate that the ID token represents a Google Workspace or Cloud
organization account, you can check the hd claim, which indicates the hosted
domain of the user. This must be used when restricting access to a resource to only members
of certain domains. The absence of this claim indicates that the account does not belong to
a Google hosted domain.
To validate an ID token in Python, use the verify_oauth2_token function. For example:
from google.oauth2 import id_token from google.auth.transport import requests # (Receive token by HTTPS POST) # ... try: # Specify the WEB_CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token(token, requests.Request(), WEB_CLIENT_ID) # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [WEB_CLIENT_ID_1, WEB_CLIENT_ID_2, WEB_CLIENT_ID_3]: # raise ValueError('Could not verify audience.') # If the request specified a Google Workspace domain # if idinfo['hd'] != DOMAIN_NAME: # raise ValueError('Wrong domain name.') # ID token is valid. Get the user's Google Account ID from the decoded token. # This ID is unique to each Google Account, making it suitable for use as a primary key # during account lookup. Email is not a good choice because it can be changed by the user. userid = idinfo['sub'] except ValueError: # Invalid token pass
The verify_oauth2_token function verifies the JWT
signature, the aud claim, and the exp claim.
You must also verify the hd
claim (if applicable) by examining the object that
verify_oauth2_token returns. If multiple clients access the
backend server, also manually verify the aud claim.
Calling the tokeninfo endpoint
An easy way to validate an ID token signature for debugging is to
use the tokeninfo endpoint. Calling this endpoint involves an
additional network request that does most of the validation for you while you test proper
validation and payload extraction in your own code. It is not suitable for use in production
code as requests may be throttled or otherwise subject to intermittent errors.
To validate an ID token using the tokeninfo endpoint, make an HTTPS
POST or GET request to the endpoint, and pass your ID token in the
id_token parameter.
For example, to validate the token "XYZ123", make the following GET request:
https://oauth2.googleapis.com/tokeninfo?id_token=XYZ123
If the token is properly signed and the iss and exp
claims have the expected values, you will get a HTTP 200 response, where the body
contains the JSON-formatted ID token claims.
Here's an example response:
{
// These six fields are included in all Google ID Tokens.
"iss": "https://accounts.google.com",
"sub": "110169484474386276334",
"azp": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"aud": "1008719970978-hb24n2dstb40o45d4feuo2ukqmcc6381.apps.googleusercontent.com",
"iat": "1433978353",
"exp": "1433981953",
// These seven fields are only included when the user has granted the "profile" and
// "email" OAuth scopes to the application.
"email": "testuser@gmail.com",
"email_verified": "true",
"name" : "Test User",
"picture": "https://lh4.googleusercontent.com/-kYgzyAWpZzJ/ABCDEFGHI/AAAJKLMNOP/tIXL9Ir44LE/s99-c/photo.jpg",
"given_name": "Test",
"family_name": "User",
"locale": "en"
}If you need to validate that the ID token represents a Google Workspace account, you can check
the hd claim, which indicates the hosted domain of the user. This must be used when
restricting access to a resource to only members of certain domains. The absence of this claim
indicates that the account does not belong to a Google Workspace hosted domain.
Criar uma conta ou sessão
Depois de verificar o token, confira se o usuário já está no seu usuário no seu banco de dados. Se sim, estabeleça uma sessão autenticada para o usuário. Se o usuário ainda não estiver no seu banco de dados, crie um novo registro de usuário com base nas informações no payload do token de ID e estabeleça uma sessão para o usuário. Você pode solicitar ao usuário outras informações de perfil quando detectar um usuário recém-criado no app.
Como proteger as contas dos seus usuários com a Proteção entre contas
Quando conta com o Google para fazer login de um usuário, você se beneficia automaticamente de todos os infraestrutura e recursos de segurança que o Google criou para proteger os dados dos usuários. No entanto, no caso improvável de a Conta do Google do usuário ser comprometida ou no caso de haver um evento de segurança significativo, o app também poderá ficar vulnerável a ataques. Para proteger melhor suas contas contra eventos de segurança importantes, use a Proteção entre contas para receber alertas de segurança do Google. Quando receber esses eventos, ganhar visibilidade de alterações importantes na segurança da Conta do Google do usuário e você poderá tomar providências no serviço para proteger suas contas.