リンクされたアカウントの Android へのログイン

コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。

[リンクされたアカウント ログイン] は、すでに Google アカウントをサービスにリンクしているユーザーに対し、[Google でワンタップでログイン] を有効にします。ユーザー名とパスワードを 1 回入力するだけでログインできるため、ユーザー エクスペリエンスが向上します。また、ユーザーがサービスで重複するアカウントを作成する可能性も低くなります。

リンクされたアカウントのログインは、Android のワンタップ ログインフローの一部として利用できます。つまり、アプリでワンタップ機能がすでに有効になっている場合、別のライブラリをインポートする必要はありません。

このドキュメントでは、リンクされたアカウントのログインをサポートするように Android アプリを変更する方法について説明します。

仕組み

  1. ワンタップ ログインフロー中にリンクされたアカウントの表示を有効にします。
  2. ユーザーが Google でログインし、サービス上で自身の Google アカウントを自身のアカウントにリンクしている場合は、そのリンクされたアカウントの ID トークンが送信されます。
  3. ワンタップのログイン プロンプトが表示され、リンクされたアカウントでサービスにログインするオプションが表示されます。
  4. ユーザーがリンクされたアカウントの使用を継続することにした場合、ユーザーの ID トークンがアプリに返されます。この ID と、ステップ 2 でサーバーに送信されたトークンを照合して、ログインしたユーザーを識別します。

セットアップ

開発環境をセットアップする

開発ホストで最新の Google Play 開発者サービスを入手する:

  1. Android SDK Manager を開きます。
  1. [SDK Tools] で、[Google Play 開発者サービス] を見つけます。

  2. これらのパッケージのステータスが「Installed」でない場合は、両方を選択して、[Install Packages] をクリックします。

アプリを構成する

  1. プロジェクト レベルの build.gradle ファイルの buildscript セクションと allprojects セクションの両方に Google の Maven リポジトリを含めます。

    buildscript {
        repositories {
            google()
        }
    }
    
    allprojects {
        repositories {
            google()
        }
    }
    
  2. 「Link with Google」API の依存関係をモジュールのアプリレベルの Gradle ファイル(通常は app/build.gradle)に追加します。

    dependencies {
      implementation 'com.google.android.gms:play-services-auth:20.4.1'
    }
    

リンク済みアカウントのログインをサポートするように Android アプリを変更する

リンクされたアカウントのログインフローの最後に、アプリに ID トークンが返されます。ユーザーがログインする前に、ID トークンの整合性を検証する必要があります。

次のコードサンプルは、ID トークンを確認して、後でユーザーにログインする手順を詳しく説明しています。

  1. ログイン インテントの結果を受け取るアクティビティを作成する

    Kotlin

      private val activityResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
          try {
            val signInCredentials = Identity.signInClient(this)
                                    .signInCredentialFromIntent(result.data)
            // Review the Verify the integrity of the ID token section for
            // details on how to verify the ID token
            verifyIdToken(signInCredential.googleIdToken)
          } catch (e: ApiException) {
            Log.e(TAG, “Sign-in failed with error code:”, e)
          }
        } else {
          Log.e(TAG, “Sign-in failed”)
        }
      }
    

    Java

      private final ActivityResultLauncher<IntentSenderResult>
        activityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartIntentSenderForResult(),
        result -> {
        If (result.getResultCode() == RESULT_OK) {
            try {
              SignInCredential signInCredential = Identity.getSignInClient(this)
                             .getSignInCredentialFromIntent(result.getData());
              verifyIdToken(signInCredential.getGoogleIdToken());
            } catch (e: ApiException ) {
              Log.e(TAG, “Sign-in failed with error:”, e)
            }
        } else {
            Log.e(TAG, “Sign-in failed”)
        }
    });
    
  2. ログイン リクエストを作成する

    Kotlin

    private val tokenRequestOptions =
    GoogleIdTokenRequestOptions.Builder()
      .supported(true)
      // Your server's client ID, not your Android client ID.
      .serverClientId(getString("your-server-client-id")
      .filterByAuthorizedAccounts(true)
      .associateLinkedAccounts("service-id-of-and-defined-by-developer",
                               scopes)
      .build()
    

    Java

     private final GoogleIdTokenRequestOptions tokenRequestOptions =
         GoogleIdTokenRequestOptions.Builder()
      .setSupported(true)
      .setServerClientId("your-service-client-id")
      .setFilterByAuthorizedAccounts(true)
      .associateLinkedAccounts("service-id-of-and-defined-by-developer",
                                scopes)
      .build()
    
  3. ログイン保留中のインテントを起動する

    Kotlin

     Identity.signInClient(this)
        .beginSignIn(
      BeginSignInRequest.Builder()
        .googleIdTokenRequestOptions(tokenRequestOptions)
      .build())
        .addOnSuccessListener{result ->
          activityResultLauncher.launch(result.pendingIntent.intentSender)
      }
      .addOnFailureListener {e ->
        Log.e(TAG, “Sign-in failed because:”, e)
      }
    

    Java

     Identity.getSignInClient(this)
      .beginSignIn(
        BeginSignInRequest.Builder()
          .setGoogleIdTokenRequestOptions(tokenRequestOptions)
          .build())
      .addOnSuccessListener(result -> {
        activityResultLauncher.launch(
            result.getPendingIntent().getIntentSender());
    })
    .addOnFailureListener(e -> {
      Log.e(TAG, “Sign-in failed because:”, e);
    });
    

ID トークンの整合性を確認する

To verify that the token is valid, ensure that the following criteria are satisfied:

  • The ID token is properly signed by Google. Use Google's public keys (available in JWK or PEM format) to verify the token's signature. These keys are regularly rotated; examine the Cache-Control header in the response to determine when you should retrieve them again.
  • The value of aud in the ID token is equal to one of your app's client IDs. This check is necessary to prevent ID tokens issued to a malicious app being used to access data about the same user on your app's backend server.
  • The value of iss in the ID token is equal to accounts.google.com or https://accounts.google.com.
  • The expiry time (exp) of the ID token has not passed.
  • If you want to restrict access to only members of your G Suite domain, verify that the ID token has an hd claim that matches your G Suite domain name.

Rather than writing your own code to perform these verification steps, we strongly recommend using a Google API client library for your platform, or a general-purpose JWT library. For development and debugging, you can call our tokeninfo validation endpoint.

Google API クライアント ライブラリの使用

本番環境で Google ID トークンを検証するには、Java Google API クライアント ライブラリを使用することをおすすめします。

Java

  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 CLIENT_ID of the app that accesses the backend:
      .setAudience(Collections.singletonList(CLIENT_ID))
      // Or, if multiple clients access the backend:
      //.setAudience(Arrays.asList(CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3))
      .build();

  // (Receive idTokenString by HTTPS POST)

  GoogleIdToken idToken = verifier.verify(idTokenString);
  if (idToken != null) {
    Payload payload = idToken.getPayload();

    // Print user identifier
    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.");
  }

GoogleIdTokenVerifier.verify() メソッドは、JWT 署名、aud クレーム、iss クレーム、exp クレームを検証します。

アクセスを G Suite ドメインのメンバーのみに制限する場合は、Payload.getHostedDomain() メソッドで返されたドメイン名をチェックして、hd クレームも確認します。

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 are a G Suite customer, you might also be interested in the hd claim, which indicates the hosted domain of the user. This can be used to restrict access to a resource to only members of certain domains. The absence of this claim indicates that the user does not belong to a G Suite hosted domain.