Переход с Smart Lock для паролей на Диспетчер учетных данных

Smart Lock for Passwords , который был устарел в 2022 году, теперь удален из Google Play Services Auth SDK ( com.google.android.gms:play-services-auth ). Чтобы свести к минимуму критические изменения, которые могут повлиять на существующие интеграции, возможности Smart Lock для всех существующих приложений в Play Store продолжат работать правильно. Новые версии приложений, скомпилированные с обновленным SDK ( com.google.android.gms:play-services-auth:21.0.0 ), больше не смогут получить доступ к Smart Lock for Password API и не будут успешно собраны. Всем разработчикам следует как можно скорее перенести свои проекты Android на использование Credential Manager .

Преимущества перехода на API Credential Manager

Credential Manager предлагает простой, унифицированный API, который обеспечивает поддержку современных функций и методов, одновременно улучшая процесс аутентификации для ваших пользователей:

  • Credential Manager полностью поддерживает сохранение паролей и аутентификацию . Это означает отсутствие помех для ваших пользователей при миграции вашего приложения с Smart Lock на Credential Manager.
  • Credential Manager интегрирует поддержку нескольких методов входа, включая пароли и интегрированные методы входа, такие как «Войти через Google» , для повышения безопасности и включения преобразования, если вы планируете поддерживать любой из них в будущем.
  • Начиная с Android 14, Credential Manager поддерживает сторонних поставщиков паролей и ключей доступа.
  • Credential Manager обеспечивает единообразный и унифицированный пользовательский интерфейс для всех методов аутентификации.

Варианты миграции :

Вариант использования Рекомендация
Сохранить пароль и войти с сохраненным паролем Используйте опцию пароля из руководства Sign in your user with Credential Manager . Подробные шаги по сохранению пароля и аутентификации описаны ниже.
Войти через Google Следуйте руководству по интеграции диспетчера учетных данных с функцией входа через Google .
Показывать пользователям подсказку по номеру телефона Используйте API подсказок по номеру телефона от Google Identity Services.

Вход с паролями с помощью Credential Manager

Чтобы использовать API Credential Manager, выполните действия, описанные в разделе предварительных условий руководства Credential Manager, и убедитесь, что вы выполнили следующее:

Войти с сохраненными паролями

Чтобы получить параметры пароля, связанные с учетной записью пользователя, выполните следующие действия:

1. Инициализируйте пароль и опцию аутентификации.

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

2. Используйте параметры, полученные на предыдущем шаге, для создания запроса на вход.

val getCredRequest = GetCredentialRequest(
    listOf(getPasswordOption)
)

3. Запустите процесс входа в систему.

fun launchSignInFlow() {
    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)
        }
    }
}

private 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}")
        }
    }
}

Дополнительные ресурсы