비밀번호 대용 Smart Lock에서 인증 관리자로 이전하기

2022년에 지원 중단된 비밀번호 대용 Smart Lock이 이제 Google Play 서비스 인증 SDK(com.google.android.gms:play-services-auth)에서 삭제됩니다. 기존 통합에 영향을 줄 수 있는 브레이킹 체인지를 최소화하기 위해 Play 스토어에 있는 기존의 모든 앱의 Smart Lock 기능은 계속 올바르게 작동합니다. 업데이트된 SDK(com.google.android.gms:play-services-auth:21.0.0)로 컴파일된 새 앱 버전은 더 이상 비밀번호 대용 Smart Lock API에 액세스할 수 없으며 빌드에 실패합니다. 인증 관리자를 사용하려는 모든 개발자는 최대한 빨리 Android 프로젝트를 이전해야 합니다.

Credential Manager API로 이전할 때의 이점

인증 관리자는 최신 기능과 관행을 지원하는 동시에 사용자의 인증 환경을 개선하는 간단한 통합 API를 제공합니다.

  • 인증 관리자는 비밀번호 저장 및 인증을 완벽하게 지원합니다. 즉, 앱을 Smart Lock에서 인증 관리자로 이전할 때 사용자에게 중단이 발생하지 않습니다.
  • 인증 관리자는 패스키 및 제휴 로그인 방법(예: Google 계정으로 로그인)과 같은 멀티 로그인 방법에 관한 지원을 통합하여 향후 둘 중 하나를 지원할 계획이 있는 경우 보안을 강화하고 전환을 사용 설정합니다.
  • Android 14부터 인증 관리자는 서드 파티 비밀번호 및 패스키 제공업체를 지원합니다.
  • 인증 관리자는 모든 인증 방법에서 일관되고 통합된 사용자 환경을 제공합니다.

이전 옵션은 다음과 같습니다.

사용 사례 권장사항
비밀번호 저장 및 저장된 비밀번호로 로그인 인증 관리자로 사용자 로그인 가이드의 비밀번호 옵션을 사용합니다. 비밀번호 저장 및 인증에 대한 세부 단계는 뒷부분에서 설명합니다.
Google 계정으로 로그인 Google 계정으로 로그인과 인증 관리자 통합 가이드를 따르세요.
사용자에게 전화번호 힌트 표시 Google ID 서비스의 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());
    }
}

추가 리소스