成功检索到用户的凭据或检索到登录提示后,您可以检查凭据是否有可用的 ID 令牌。ID 令牌是经过签名的用户身份断言,其中还包含用户的基本个人资料信息,可能包括经过 Google 验证的电子邮件地址。当 ID 令牌可用时,您可以使用它们安全地向应用的后端进行身份验证,或者在创建新账号时跳过电子邮件验证步骤。
当 Credential 对象的相应用户 ID 与设备上登录的 Google 账号的用户 ID 一致时,ID 令牌可用。
如需使用 ID 令牌登录,请先使用 getIdTokens 方法检索 ID 令牌。然后,将 ID 令牌发送到应用的后端。在后端,使用 Google API 客户端库或通用 JWT 库验证令牌。
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.");}
[null,null,["最后更新时间 (UTC):2025-08-27。"],[[["\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."]]