CredentialManager


public interface CredentialManager


Manages user authentication flows.

An application can call the CredentialManager apis to launch framework UI flows for a user to register a new credential or to consent to a saved credential from supported credential providers, which can then be used to authenticate to the app.

This class contains its own exception types. They represent unique failures during the Credential Manager flow. As required, they can be extended for unique types containing new and unique versions of the exception - either with new 'exception types' (same credential class, different exceptions), or inner subclasses and their exception types (a subclass credential class and all their exception types).

For example, if there is an UNKNOWN exception type, assuming the base Exception is ClearCredentialException, we can add an 'exception type' class for it as follows:

class ClearCredentialUnknownException(
errorMessage: CharSequence? = null
) : ClearCredentialException(TYPE_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION, errorMessage) {
// ...Any required impl here...//
companion object {
private const val TYPE_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION: String =
"androidx.credentials.TYPE_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION"
}
}

Furthermore, the base class can be subclassed to a new more specific credential type, which then can further be subclassed into individual exception types. The first is an example of a 'inner credential type exception', and the next is a 'exception type' of this subclass exception.

class UniqueCredentialBasedOnClearCredentialException(
type: String,
errorMessage: CharSequence? = null
) : ClearCredentialException(type, errorMessage) {
// ... Any required impl here...//
}
// .... code and logic .... //
class UniqueCredentialBasedOnClearCredentialUnknownException(
errorMessage: CharSequence? = null
) : ClearCredentialException(TYPE_UNIQUE_CREDENTIAL_BASED_ON_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION,
errorMessage) {
// ... Any required impl here ... //
companion object {
private const val
TYPE_UNIQUE_CREDENTIAL_BASED_ON_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION: String =
"androidx.credentials.TYPE_CLEAR_CREDENTIAL_UNKNOWN_EXCEPTION"
}
}

Summary

Public methods

default void

Clears the current user credential state from all credential providers.

abstract void

Clears the current user credential state from all credential providers.

default static final @NonNull CredentialManager

Creates a CredentialManager based on the given context.

default @NonNull CreateCredentialResponse
createCredential(
    @NonNull Context context,
    @NonNull CreateCredentialRequest request
)

Registers a user credential that can be used to authenticate the user to the app in the future.

abstract void

Registers a user credential that can be used to authenticate the user to the app in the future.

abstract @NonNull PendingIntent

Returns a pending intent that shows a screen that lets a user enable a Credential Manager provider.

default @NonNull GetCredentialResponse
@RequiresApi(value = 34)
getCredential(
    @NonNull Context context,
    @NonNull PrepareGetCredentialResponse.PendingGetCredentialHandle pendingGetCredentialHandle
)

Requests a credential from the user.

default @NonNull GetCredentialResponse
getCredential(
    @NonNull Context context,
    @NonNull GetCredentialRequest request
)

Requests a credential from the user.

abstract void
@RequiresApi(value = 34)
getCredentialAsync(
    @NonNull Context context,
    @NonNull PrepareGetCredentialResponse.PendingGetCredentialHandle pendingGetCredentialHandle,
    CancellationSignal cancellationSignal,
    @NonNull Executor executor,
    @NonNull CredentialManagerCallback<@NonNull GetCredentialResponse, @NonNull GetCredentialException> callback
)

Requests a credential from the user.

abstract void
getCredentialAsync(
    @NonNull Context context,
    @NonNull GetCredentialRequest request,
    CancellationSignal cancellationSignal,
    @NonNull Executor executor,
    @NonNull CredentialManagerCallback<@NonNull GetCredentialResponse, @NonNull GetCredentialException> callback
)

Requests a credential from the user.

default @NonNull PrepareGetCredentialResponse

Prepares for a get-credential operation.

abstract void

Prepares for a get-credential operation.

Public methods

clearCredentialState

Added in 1.2.0
default void clearCredentialState(@NonNull ClearCredentialStateRequest request)

Clears the current user credential state from all credential providers.

You should invoked this api after your user signs out of your app to notify all credential providers that any stored credential session for the given app should be cleared.

A credential provider may have stored an active credential session and use it to limit sign-in options for future get-credential calls. For example, it may prioritize the active credential over any other available credential. When your user explicitly signs out of your app and in order to get the holistic sign-in options the next time, you should call this API to let the provider clear any stored credential session.

If the API is called with ClearCredentialStateRequest.TYPE_CLEAR_RESTORE_CREDENTIAL then any restore credential stored on device will be cleared.

Parameters
@NonNull ClearCredentialStateRequest request

the request for clearing the app user's credential state

clearCredentialStateAsync

Added in 1.2.0
abstract void clearCredentialStateAsync(
    @NonNull ClearCredentialStateRequest request,
    CancellationSignal cancellationSignal,
    @NonNull Executor executor,
    @NonNull CredentialManagerCallback<Void, @NonNull ClearCredentialException> callback
)

Clears the current user credential state from all credential providers.

This API uses callbacks instead of Kotlin coroutines.

You should invoked this api after your user signs out of your app to notify all credential providers that any stored credential session for the given app should be cleared.

A credential provider may have stored an active credential session and use it to limit sign-in options for future get-credential calls. For example, it may prioritize the active credential over any other available credential. When your user explicitly signs out of your app and in order to get the holistic sign-in options the next time, you should call this API to let the provider clear any stored credential session.

Parameters
@NonNull ClearCredentialStateRequest request

the request for clearing the app user's credential state

CancellationSignal cancellationSignal

an optional signal that allows for cancelling this call

@NonNull Executor executor

the callback will take place on this executor

@NonNull CredentialManagerCallback<Void, @NonNull ClearCredentialException> callback

the callback invoked when the request succeeds or fails

create

Added in 1.2.0
default static final @NonNull CredentialManager create(@NonNull Context context)

Creates a CredentialManager based on the given context.

Parameters
@NonNull Context context

the context with which the CredentialManager should be associated

createCredential

default @NonNull CreateCredentialResponse createCredential(
    @NonNull Context context,
    @NonNull CreateCredentialRequest request
)

Registers a user credential that can be used to authenticate the user to the app in the future.

The execution potentially launches framework UI flows for a user to view their registration options, grant consent, etc.

Parameters
@NonNull Context context

the context used to launch any UI needed; use an activity context to make sure the UI will be launched within the same task stack

@NonNull CreateCredentialRequest request

the request for creating the credential

createCredentialAsync

Added in 1.2.0
abstract void createCredentialAsync(
    @NonNull Context context,
    @NonNull CreateCredentialRequest request,
    CancellationSignal cancellationSignal,
    @NonNull Executor executor,
    @NonNull CredentialManagerCallback<@NonNull CreateCredentialResponse, @NonNull CreateCredentialException> callback
)

Registers a user credential that can be used to authenticate the user to the app in the future.

This API uses callbacks instead of Kotlin coroutines.

The execution potentially launches framework UI flows for a user to view their registration options, grant consent, etc.

Parameters
@NonNull Context context

the context used to launch any UI needed; use an activity context to make sure the UI will be launched within the same task stack

@NonNull CreateCredentialRequest request

the request for creating the credential

CancellationSignal cancellationSignal

an optional signal that allows for cancelling this call

@NonNull Executor executor

the callback will take place on this executor

@NonNull CredentialManagerCallback<@NonNull CreateCredentialResponse, @NonNull CreateCredentialException> callback

the callback invoked when the request succeeds or fails

createSettingsPendingIntent

Added in 1.2.0
@RequiresApi(value = 34)
abstract @NonNull PendingIntent createSettingsPendingIntent()

Returns a pending intent that shows a screen that lets a user enable a Credential Manager provider.

Returns
@NonNull PendingIntent

the pending intent that can be launched

getCredential

@RequiresApi(value = 34)
default @NonNull GetCredentialResponse getCredential(
    @NonNull Context context,
    @NonNull PrepareGetCredentialResponse.PendingGetCredentialHandle pendingGetCredentialHandle
)

Requests a credential from the user.

Different from the other getCredential(GetCredentialRequest, Activity) API, this API launches the remaining flows to retrieve an app credential from the user, after the completed prefetch work corresponding to the given pendingGetCredentialHandle. Use this API to complete the full credential retrieval operation after you initiated a request through the prepareGetCredential API.

The execution can potentially launch UI flows to collect user consent to using a credential, display a picker when multiple credentials exist, etc.

Parameters
@NonNull Context context

the context used to launch any UI needed; use an activity context to make sure the UI will be launched within the same task stack

@NonNull PrepareGetCredentialResponse.PendingGetCredentialHandle pendingGetCredentialHandle

the handle representing the pending operation to resume

getCredential

default @NonNull GetCredentialResponse getCredential(
    @NonNull Context context,
    @NonNull GetCredentialRequest request
)

Requests a credential from the user.

The execution potentially launches framework UI flows for a user to view available credentials, consent to using one of them, etc.

import androidx.credentials.Credential
import androidx.credentials.CredentialManager
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetPasswordOption
import androidx.credentials.GetPublicKeyCredentialOption
import androidx.credentials.PublicKeyCredential
import androidx.credentials.exceptions.GetCredentialException

val credentialManager = CredentialManager.create(context)

val getPasswordOption = GetPasswordOption()

val getPublicKeyCredentialOption =
    GetPublicKeyCredentialOption(
        requestJson = generateGetPasskeyRequestJsonFromServer(),
        // No need to fill this unless you are a browser and are making an origin-based request
        clientDataHash = null,
    )

val request =
    GetCredentialRequest(
        credentialOptions = listOf(getPasswordOption, getPublicKeyCredentialOption)
    )

// The API call will launch a credential selector UI for the user to pick a login credential.
// It will be canceled if this coroutine scope is canceled. If you want the operation to persist
// through your UI lifecycle (e.g. configuration changes), choose a coroutine scope that is
// broader than your UI lifecycle (e.g. ViewModelScope)
yourCoroutineScope.launch {
    try {
        val response =
            credentialManager.getCredential(
                // Important: use an Activity context to ensure that the system credential
                // selector
                // ui is launched within the same activity stack to avoid undefined UI
                // transition
                // behavior.
                context = activity,
                request = request,
            )
        signInWithCredential(response.credential)
    } catch (e: GetCredentialException) {
        handleGetCredentialFailure(e)
    }
}
Parameters
@NonNull Context context

the context used to launch any UI needed; use an activity context to make sure the UI will be launched within the same task stack

@NonNull GetCredentialRequest request

the request for getting the credential

getCredentialAsync

Added in 1.2.0
@RequiresApi(value = 34)
abstract void getCredentialAsync(
    @NonNull Context context,
    @NonNull PrepareGetCredentialResponse.PendingGetCredentialHandle pendingGetCredentialHandle,
    CancellationSignal cancellationSignal,
    @NonNull Executor executor,
    @NonNull CredentialManagerCallback<@NonNull GetCredentialResponse, @NonNull GetCredentialException> callback
)

Requests a credential from the user.

This API uses callbacks instead of Kotlin coroutines.

Different from the other getCredentialAsync(GetCredentialRequest, Activity) API, this API launches the remaining flows to retrieve an app credential from the user, after the completed prefetch work corresponding to the given pendingGetCredentialHandle. Use this API to complete the full credential retrieval operation after you initiated a request through the prepareGetCredentialAsync API.

The execution can potentially launch UI flows to collect user consent to using a credential, display a picker when multiple credentials exist, etc.

Parameters
@NonNull Context context

the context used to launch any UI needed; use an activity context to make sure the UI will be launched within the same task stack

@NonNull PrepareGetCredentialResponse.PendingGetCredentialHandle pendingGetCredentialHandle

the handle representing the pending operation to resume

CancellationSignal cancellationSignal

an optional signal that allows for cancelling this call

@NonNull Executor executor

the callback will take place on this executor

@NonNull CredentialManagerCallback<@NonNull GetCredentialResponse, @NonNull GetCredentialException> callback

the callback invoked when the request succeeds or fails

getCredentialAsync

Added in 1.2.0
abstract void getCredentialAsync(
    @NonNull Context context,
    @NonNull GetCredentialRequest request,
    CancellationSignal cancellationSignal,
    @NonNull Executor executor,
    @NonNull CredentialManagerCallback<@NonNull GetCredentialResponse, @NonNull GetCredentialException> callback
)

Requests a credential from the user.

This API uses callbacks instead of Kotlin coroutines.

The execution potentially launches framework UI flows for a user to view available credentials, consent to using one of them, etc.

Parameters
@NonNull Context context

the context used to launch any UI needed; use an activity context to make sure the UI will be launched within the same task stack

@NonNull GetCredentialRequest request

the request for getting the credential

CancellationSignal cancellationSignal

an optional signal that allows for cancelling this call

@NonNull Executor executor

the callback will take place on this executor

@NonNull CredentialManagerCallback<@NonNull GetCredentialResponse, @NonNull GetCredentialException> callback

the callback invoked when the request succeeds or fails

prepareGetCredential

@RequiresApi(value = 34)
default @NonNull PrepareGetCredentialResponse prepareGetCredential(@NonNull GetCredentialRequest request)

Prepares for a get-credential operation. Returns a PrepareGetCredentialResponse that can later be used to launch the credential retrieval UI flow to finalize a user credential for your app.

This API doesn't invoke any UI. It only performs the preparation work so that you can later launch the remaining get-credential operation (involves UIs) through the getCredential API which incurs less latency than executing the whole operation in one call.

Parameters
@NonNull GetCredentialRequest request

the request for getting the credential

prepareGetCredentialAsync

Added in 1.2.0
@RequiresApi(value = 34)
abstract void prepareGetCredentialAsync(
    @NonNull GetCredentialRequest request,
    CancellationSignal cancellationSignal,
    @NonNull Executor executor,
    @NonNull CredentialManagerCallback<@NonNull PrepareGetCredentialResponse, @NonNull GetCredentialException> callback
)

Prepares for a get-credential operation. Returns a PrepareGetCredentialResponse that can later be used to launch the credential retrieval UI flow to finalize a user credential for your app.

This API uses callbacks instead of Kotlin coroutines.

This API doesn't invoke any UI. It only performs the preparation work so that you can later launch the remaining get-credential operation (involves UIs) through the getCredentialAsync API which incurs less latency than executing the whole operation in one call.

Parameters
@NonNull GetCredentialRequest request

the request for getting the credential

CancellationSignal cancellationSignal

an optional signal that allows for cancelling this call

@NonNull Executor executor

the callback will take place on this executor

@NonNull CredentialManagerCallback<@NonNull PrepareGetCredentialResponse, @NonNull GetCredentialException> callback

the callback invoked when the request succeeds or fails