Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Depois de recuperar as credenciais de um usuário
ou recuperar dicas de login,
verifique se um token de ID está disponível para a credencial. Um token de ID é uma
declaração assinada da identidade de um usuário que também contém informações básicas do perfil
de um usuário, possivelmente incluindo um endereço de e-mail verificado pelo
Google. Quando os tokens de ID estão disponíveis, é possível usá-los para autenticar com segurança
o back-end do app ou para pular a etapa de verificação de e-mail
ao criar uma conta.
Um token de ID fica disponível quando o ID de usuário de um objeto Credential corresponde ao ID de usuário de uma Conta do Google conectada no dispositivo.
Para fazer login com um token de ID, primeiro recupere o token com o método getIdTokens. Em seguida, envie o token de ID para o back-end do app. No back-end, verifique o token usando uma biblioteca de cliente das APIs do Google ou uma biblioteca JWT de uso geral.
É preciso chamar setAccountTypes(IdentityProviders.GOOGLE) ao criar os objetos
CredentialRequest e HintRequest.
Receber um token de ID do objeto Credentials
Depois de recuperar as credenciais de um usuário, verifique se o objeto Credentials
inclui um token de ID. Se for, chame getIdTokens para recuperá-lo e envie para seu back-end por HTTPS POST.
if(!credential.getIdTokens().isEmpty()){StringidToken=credential.getIdTokens().get(0).getIdToken();HttpClienthttpClient=newDefaultHttpClient();HttpPosthttpPost=newHttpPost("https://yourbackend.example.com/tokensignin"); try { List nameValuePairs = new ArrayList(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, "Signedinas:"+responseBody);}}
Verificar o token de ID no back-end
Depois de receber o token de ID por HTTPS POST, verifique a assinatura do token e as declarações aud, iss e exp.
A declaração aud de um token de ID do Smart Lock para senhas tem o seguinte
formato:
android://SHA512_HASH@ANDROID_PACKAGE_NAME
O valor SHA512HASH é o hash SHA-512 do seu certificado
de assinatura. É possível conseguir esse valor usando os utilitários keytool e openssl:
Ou você pode examinar um token de ID que sabe ser válido para conseguir o hash SHA-512.
As bibliotecas JWT podem processar algumas dessas tarefas de verificação para você. Por exemplo, usando a biblioteca do Google Auth para Java:
importcom.google.api.client.googleapis.auth.oauth2.GoogleIdToken;importcom.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;importcom.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;...//Verifierthatchecksthatthetokenhastheproperissuerandaudience,//andhasn't expiredprivatestaticGoogleIdTokenVerifierverifier=newGoogleIdTokenVerifier.Builder(transport,jsonFactory).setAudience(Arrays.asList(String.format("android://%s@%s",SHA512_HASH,PACKAGE_NAME))).build();//(ReceiveidTokenStringbyHTTPSPOST)GoogleIdTokenidToken=verifier.verify(idTokenString);if(idToken!=null){Payloadpayload=idToken.getPayload();System.out.println("User email: "+payload.getEmail());if(payload.getEmailVerified()){System.out.println("Email verified by Google.");}}else{System.out.println("Invalid ID token.");}
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-27 UTC."],[[["\u003cp\u003eSmart Lock for Passwords is deprecated; migrate to Credential Manager for enhanced security and user experience using passkeys, passwords, and federated identities.\u003c/p\u003e\n"],["\u003cp\u003eYou can retrieve ID tokens from retrieved credentials or sign-in hints to authenticate with your backend or streamline account creation.\u003c/p\u003e\n"],["\u003cp\u003eTo use ID tokens, ensure your app can retrieve credentials or hints, and specify \u003ccode\u003eIdentityProviders.GOOGLE\u003c/code\u003e when requesting credentials.\u003c/p\u003e\n"],["\u003cp\u003eAfter retrieving a credential, get the ID token using \u003ccode\u003egetIdTokens\u003c/code\u003e and send it to your backend for verification using a JWT library or a Google API client.\u003c/p\u003e\n"],["\u003cp\u003eOn the backend, verify the ID token's signature and claims (\u003ccode\u003eaud\u003c/code\u003e, \u003ccode\u003eiss\u003c/code\u003e, \u003ccode\u003eexp\u003c/code\u003e), with the \u003ccode\u003eaud\u003c/code\u003e claim containing your app's package name and signing certificate hash.\u003c/p\u003e\n"]]],[],null,["| **Deprecated:** Smart Lock for Passwords is deprecated. To ensure the continued security and usability of your app, [migrate to\n| Credential Manager](https://developer.android.com/training/sign-in/passkeys/) today. Credential Manager supports passkey, password, and federated identity authentication (such as Sign-in with Google), stronger security, and a more consistent user experience.\n\nAfter you have successfully [retrieved a user's credentials](/identity/smartlock-passwords/android/retrieve-credentials#handle_successful_credential_requests)\nor [retrieved sign-in hints](/identity/smartlock-passwords/android/retrieve-hints),\nyou can check if an ID token is available for the credential. An ID token is a\nsigned assertion of a user's identity that also contains a user's basic profile\ninformation, possibly including an email address that has been verified by\nGoogle. When ID tokens are available, you can use them to securely\nauthenticate with your app's backend, or to skip the email verification step\nwhen creating a new account.\n\nAn ID token is available when a `Credential` object's user ID matches the user\nID of a Google account that is signed in on the device.\n\nTo sign in with an ID token, first retrieve the ID token with the [`getIdTokens`](/android/reference/com/google/android/gms/auth/api/credentials/Credential#getIdTokens())\nmethod. Then, send the ID token to your app's backend. On the backend, verify\nthe token using either a Google API client library or a general-purpose JWT\nlibrary.\n\nBefore you begin\n\n- Your app must be able to successfully [retrieve a user's credentials](/identity/smartlock-passwords/android/retrieve-credentials#handle_successful_credential_requests) or [retrieve a sign-in hint](/identity/smartlock-passwords/android/retrieve-hints).\n- You must call `setAccountTypes(IdentityProviders.GOOGLE)` when you build the `CredentialRequest` and `HintRequest` objects.\n\nGet an ID token from the Credentials object\n\nAfter you retrieve a user's credentials, check if the `Credentials` object\nincludes an ID token. If it does, call `getIdTokens` to retrieve it, and send it\nto your backend by HTTPS POST. \n\n if (!credential.getIdTokens().isEmpty()) {\n String idToken = credential.getIdTokens().get(0).getIdToken();\n\n HttpClient httpClient = new DefaultHttpClient();\n HttpPost httpPost = new HttpPost(\"https://yourbackend.example.com/tokensignin\");\n\n try {\n List nameValuePairs = new ArrayList(1);\n nameValuePairs.add(new BasicNameValuePair(\"idToken\", idToken));\n httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));\n\n HttpResponse response = httpClient.execute(httpPost);\n int statusCode = response.getStatusLine().getStatusCode();\n final String responseBody = EntityUtils.toString(response.getEntity());\n Log.i(TAG, \"Signed in as: \" + responseBody);\n }\n }\n\nVerify the ID token on the backend\n\nAfter you receive the ID token by HTTPS POST, you must verify the token's\nsignature, and verify the token's `aud`, `iss`, and `exp` claims.\n\nThe `aud` claim of an ID token from Smart Lock for Passwords has the following\nformat: \n\n```\nandroid://SHA512_HASH@ANDROID_PACKAGE_NAME\n```\n\n\u003cbr /\u003e\n\nThe value \u003cvar translate=\"no\"\u003eSHA512\u003cem\u003eHASH\u003c/em\u003e\u003c/var\u003e*is the SHA-512 hash of your signing\ncertificate. You can get this value using the `keytool` and `openssl` utilities:* \n\n```\nkeytool -exportcert -keystore \u003cvar translate=\"no\"\u003epath-to-keystore\u003c/var\u003e -alias \u003cvar translate=\"no\"\u003ekey-name\u003c/var\u003e \n\n | openssl sha -sha512 -binary \n\n | base64 -w 0 \n\n | tr '+/' '-'\n```\n\n\u003cbr /\u003e\n\n| **Note:** On Mac OS X, omit the `-w 0` parameter from the `base64` command.\n\nOr, you can get the SHA-512 hash by examining an ID token you know to be valid.\n\nJWT libraries can handle some of these verification tasks for you. For example,\nusing the [Google Auth Library for Java](https://github.com/googleapis/google-auth-library-java): \n\n import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;\n import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;\n import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;\n\n ...\n\n // Verifier that checks that the token has the proper issuer and audience,\n // and hasn't expired\n private static GoogleIdTokenVerifier verifier =\n new GoogleIdTokenVerifier.Builder(transport, jsonFactory)\n .setAudience(Arrays.asList(String.format(\"android://%s@%s\", SHA512_HASH, PACKAGE_NAME)))\n .build();\n\n // (Receive idTokenString by HTTPS POST)\n\n GoogleIdToken idToken = verifier.verify(idTokenString);\n if (idToken != null) {\n Payload payload = idToken.getPayload();\n System.out.println(\"User email: \" + payload.getEmail());\n if (payload.getEmailVerified()) {\n System.out.println(\"Email verified by Google.\");\n }\n } else {\n System.out.println(\"Invalid ID token.\");\n }\n\nSee the [Google Sign-In documentation](/identity/sign-in/android/backend-auth#using-a-google-api-client-library)\nfor more details."]]