Smart Lock for Passwords から認証情報マネージャーに移行する

2022 年にサポートが終了した Smart Lock for Passwords は、Google Play 開発者サービス Auth SDKcom.google.android.gms:play-services-auth)から削除されています。既存の統合に影響する可能性がある、互換性を破る変更を最小限に抑えるため、Google Play ストアのすべての既存アプリでの Smart Lock 機能は、引き続き正常に動作します。更新済みの SDK(com.google.android.gms:play-services-auth:21.0.0)でコンパイルされた新しいアプリ バージョンは、Smart Lock for Password API にアクセスできなくなり、正常にビルドされなくなります。すべてのデベロッパーは、できる限り速やかに認証情報マネージャーを使用するよう、Android プロジェクトを移行する必要があります。

Credential Manager API に移行するメリット

認証情報マネージャーはシンプルな Unified API ��、最新の機能とプラクティスをサポートすると同時に、ユーザーの認証エクスペリエンスを改善します。

  • 認証情報マネージャーは完全にパスワードの保存と認証をサポートしています。つまり、アプリを Smart Lock から認証情報マネージャーに移行しても、ユーザーは中断なくアプリを使用できます。
  • 認証情報マネージャーには、パスキーGoogle でログインのようなフェデレーション ログイン メソッドなど、複数のログイン メソッドのサポートが統合されています。今度どちらかをサポートする予定の場合には、セキュリティを強化でき、変換が可能です。
  • Android 14 以降、認証情報マネージャーはサードパーティのパスワードおよびパスキー プロバイダをサポートしています。
  • 認証情報マネージャーは、すべての認証方法で一貫性のある統合されたユーザー エクスペリエンスを実現します。

移行オプション

ユースケース 推奨事項
パスワードを保存し、保存したパスワードを使用してログインする 認証情報マネージャーを使用してユーザーのログインを行うのガイドのパスワード オプションを使用します。パスワードの保存と認証の詳細な手順については、後ほど説明します。
Google でログイン 認証情報マネージャーを「Google でログイン」と統合するのガイドに沿って操作します。
ユーザーに電話番号のヒントを表示する Google Identity Services の Phone Number Hint API を使用します。

認証情報マネージャーを使用してパスワードでログインする

Credential Manager API を使用するには、認証情報マネージャー ガイドの前提条件セクションに記載されている手順を実施し、次の操作を行ってください。

保存したパスワードでログインする

ユーザーのアカウントに関連付けられているパスワードのオプションを取得する手順は次のとおりです。

1. パスワードと認証オプションを初期化します。

Kotlin

// Retrieves the user's saved password for your app from their
// password provider.
val getPasswordOption = GetPasswordOption()

Java

// Retrieves the user's saved password for your app from their
// password provider.
GetPasswordOption getPasswordOption = new GetPasswordOption();

2. 前の手順で取得したオプションを使用してログイン リクエストを作成します。

Kotlin

val getCredRequest = GetCredentialRequest(
    listOf(getPasswordOption)
)

Java

GetCredentialRequest getCredRequest = new GetCredentialRequest.Builder()
    .addCredentialOption(getPasswordOption)
    .build();

3. ログインフローを開始します。

Kotlin

coroutineScope.launch {
    try {
        // Attempt to retrieve the credential from the Credential Manager.
        val result = credentialManager.getCredential(
            // Use an activity-based context to avoid undefined system UI
            // launching behavior.
            context = activityContext,
            request = getCredRequest
        )

        // Process the successfully retrieved credential.
        handleSignIn(result)
    } catch (e: GetCredentialException) {
        // Handle any errors that occur during the credential retrieval
        // process.
        handleFailure(e)
    }
}

fun handleSignIn(result: GetCredentialResponse) {
    // Extract the credential from the response.
    val credential = result.credential

    // Determine the type of credential and handle it accordingly.
    when (credential) {
        is PasswordCredential -> {
            val username = credential.id
            val password = credential.password

            // Use the extracted username and password to perform
            // authentication.
        }
        else -> {
            // Handle unrecognized credential types.
            Log.e(TAG, "Unexpected type of credential")
        }
    }
}

private fun handleFailure(e: GetCredentialException) {
    // Handle specific credential retrieval errors.
    when (e) {
        is GetCredentialCancellationException -> {
            /* This exception is thrown when the user intentionally cancels
            the credential retrieval operation. Update the application's state
            accordingly. */
        }

        is GetCredentialCustomException -> {
            /* This exception is thrown when a custom error occurs during the
            credential retrieval flow. Refer to the documentation of the
            third-party SDK used to create the GetCredentialRequest for
            handling this exception. */
        }

        is GetCredentialInterruptedException -> {
            /* This exception is thrown when an interruption occurs during the
            credential retrieval flow. Determine whether to retry the
            operation or proceed with an alternative authentication method. */
        }

        is GetCredentialProviderConfigurationException -> {
            /* This exception is thrown when there is a mismatch in
            configurations for the credential provider. Verify that the
            provider dependency is included in the manifest and that the
            required system services are enabled. */
        }

        is GetCredentialUnknownException -> {
            /* This exception is thrown when the credential retrieval
            operation fails without providing any additional details. Handle
            the error appropriately based on the application's context. */
        }

        is GetCredentialUnsupportedException -> {
            /* This exception is thrown when the device does not support the
            Credential Manager feature. Inform the user that credential-based
            authentication is unavailable and guide them to an alternative
            authentication method. */
        }

        is NoCredentialException -> {
            /* This exception is thrown when there are no viable credentials
            available for the user. Prompt the user to sign up for an account
            or provide an alternative authentication method. Upon successful
            authentication, store the login information using
            androidx.credentials.CredentialManager.createCredential to
            facilitate easier sign-in the next time. */
        }

        else -> {
            // Handle unexpected exceptions.
            Log.w(TAG, "Unexpected exception type: ${e::class.java.name}")
        }
    }
}

Java

credentialManager.getCredentialAsync(
    // Use activity based context to avoid undefined
    // system UI launching behavior
    activity,
    getCredRequest,
    cancellationSignal,
    <executor>,
    new CredentialManagerCallback<GetCredentialResponse, GetCredentialException>() {
        @Override
        public void onSuccess(GetCredentialResponse result) {
            handleSignIn(result);
        }

        @Override
        public void onFailure(GetCredentialException e) {
            handleFailure(e);
        }
    }
);

public void handleSignIn(GetCredentialResponse result) {
    // Handle the successfully returned credential.
    Credential credential = result.getCredential();
    if (credential instanceof PasswordCredential) {
        String username = ((PasswordCredential) credential).getId();
        String password = ((PasswordCredential) credential).getPassword();
        // Use ID and password to send to your server to validate and
        // authenticate
    } else {
        // Catch any unrecognized credential type here.
        Log.e(TAG, "Unexpected type of credential");
    }
}

public void handleFailure(GetCredentialException e) {
    if (e instanceof GetCredentialCancellationException) {
        /* During the get credential flow, this is thrown when a user
        intentionally cancels an operation. When this happens, the application
        should handle logic accordingly, typically under indication the user
        does not want to see Credential Manager anymore. */
    } else if (e instanceof GetCredentialCustomException) {
        /* Represents a custom error thrown during a get flow with
        CredentialManager. If you get this custom exception, you should match
        its type against exception constants defined in any third-party sdk
        with which you used to make the
        androidx.credentials.GetCredentialRequest, and then handle it
        according to the sdk recommendation. */
    } else if (e instanceof GetCredentialInterruptedException) {
        /* During the get credential flow, this is thrown when some
        interruption occurs that may warrant retrying or at least does not
        indicate a purposeful desire to close or tap away from Credential
        Manager. */
    } else if (e instanceof GetCredentialProviderConfigurationException) {
        /* During the get credential flow, this is thrown when configurations
        are mismatched for the provider, typically indicating the provider
        dependency is missing in the manifest or some system service is not
        enabled. */
    } else if (e instanceof GetCredentialUnknownException) {
        // This is thrown when the get credential operation failed with no
        // more details.
    } else if (e instanceof GetCredentialUnsupportedException) {
        /* During the get credential flow, this is thrown when credential
        manager is unsupported, typically because the device has disabled it
        or did not ship with this feature enabled. */
    } else if (e instanceof NoCredentialException) {
        /* During the get credential flow, this is returned when no viable
        credential is available for the user. This can be caused by various
        scenarios such as that the user doesn't have any credential or the
        user doesn't grant consent to using any available credential. Upon
        this exception, your app should navigate to use the regular app
        sign-up or sign-in screen. When that succeeds, you should invoke
        androidx.credentials.CredentialManager.createCredentialAsync to store
        the login info, so that your user can sign in more easily through
        Credential Manager the next time. */
    } else {
        Log.w(TAG, "Unexpected exception type " + e.getClass().getName());
    }
}

参考情報