CredentialManager


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 companion functions

CredentialManager
create(context: Context)

Creates a CredentialManager based on the given context.

Public functions

open suspend Unit

Clears the current user credential state from all credential providers.

Unit
clearCredentialStateAsync(
    request: ClearCredentialStateRequest,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<Void?, ClearCredentialException>
)

Clears the current user credential state from all credential providers.

open suspend CreateCredentialResponse

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

Unit
createCredentialAsync(
    context: Context,
    request: CreateCredentialRequest,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<CreateCredentialResponseCreateCredentialException>
)

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

PendingIntent

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

open suspend GetCredentialResponse
@RequiresApi(value = 34)
getCredential(
    context: Context,
    pendingGetCredentialHandle: PrepareGetCredentialResponse.PendingGetCredentialHandle
)

Requests a credential from the user.

open suspend GetCredentialResponse

Requests a credential from the user.

Unit
@RequiresApi(value = 34)
getCredentialAsync(
    context: Context,
    pendingGetCredentialHandle: PrepareGetCredentialResponse.PendingGetCredentialHandle,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<GetCredentialResponseGetCredentialException>
)

Requests a credential from the user.

Unit
getCredentialAsync(
    context: Context,
    request: GetCredentialRequest,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<GetCredentialResponseGetCredentialException>
)

Requests a credential from the user.

open suspend PrepareGetCredentialResponse

Prepares for a get-credential operation.

Unit
@RequiresApi(value = 34)
prepareGetCredentialAsync(
    request: GetCredentialRequest,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<PrepareGetCredentialResponseGetCredentialException>
)

Prepares for a get-credential operation.

Public companion functions

create

Added in 1.2.0
fun create(context: Context): CredentialManager

Creates a CredentialManager based on the given context.

Parameters
context: Context

the context with which the CredentialManager should be associated

Public functions

clearCredentialState

Added in 1.2.0
open suspend fun clearCredentialState(request: ClearCredentialStateRequest): Unit

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
request: ClearCredentialStateRequest

the request for clearing the app user's credential state

clearCredentialStateAsync

Added in 1.2.0
fun clearCredentialStateAsync(
    request: ClearCredentialStateRequest,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<Void?, ClearCredentialException>
): Unit

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
request: ClearCredentialStateRequest

the request for clearing the app user's credential state

cancellationSignal: CancellationSignal?

an optional signal that allows for cancelling this call

executor: Executor

the callback will take place on this executor

callback: CredentialManagerCallback<Void?, ClearCredentialException>

the callback invoked when the request succeeds or fails

createCredential

open suspend fun createCredential(context: Context, request: CreateCredentialRequest): CreateCredentialResponse

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
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

request: CreateCredentialRequest

the request for creating the credential

createCredentialAsync

Added in 1.2.0
fun createCredentialAsync(
    context: Context,
    request: CreateCredentialRequest,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<CreateCredentialResponseCreateCredentialException>
): Unit

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
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

request: CreateCredentialRequest

the request for creating the credential

cancellationSignal: CancellationSignal?

an optional signal that allows for cancelling this call

executor: Executor

the callback will take place on this executor

callback: CredentialManagerCallback<CreateCredentialResponseCreateCredentialException>

the callback invoked when the request succeeds or fails

createSettingsPendingIntent

Added in 1.2.0
@RequiresApi(value = 34)
fun createSettingsPendingIntent(): PendingIntent

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

Returns
PendingIntent

the pending intent that can be launched

getCredential

@RequiresApi(value = 34)
open suspend fun getCredential(
    context: Context,
    pendingGetCredentialHandle: PrepareGetCredentialResponse.PendingGetCredentialHandle
): GetCredentialResponse

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
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

pendingGetCredentialHandle: PrepareGetCredentialResponse.PendingGetCredentialHandle

the handle representing the pending operation to resume

getCredential

open suspend fun getCredential(context: Context, request: GetCredentialRequest): GetCredentialResponse

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
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

request: GetCredentialRequest

the request for getting the credential

getCredentialAsync

Added in 1.2.0
@RequiresApi(value = 34)
fun getCredentialAsync(
    context: Context,
    pendingGetCredentialHandle: PrepareGetCredentialResponse.PendingGetCredentialHandle,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<GetCredentialResponseGetCredentialException>
): Unit

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
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

pendingGetCredentialHandle: PrepareGetCredentialResponse.PendingGetCredentialHandle

the handle representing the pending operation to resume

cancellationSignal: CancellationSignal?

an optional signal that allows for cancelling this call

executor: Executor

the callback will take place on this executor

callback: CredentialManagerCallback<GetCredentialResponseGetCredentialException>

the callback invoked when the request succeeds or fails

getCredentialAsync

Added in 1.2.0
fun getCredentialAsync(
    context: Context,
    request: GetCredentialRequest,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<GetCredentialResponseGetCredentialException>
): Unit

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
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

request: GetCredentialRequest

the request for getting the credential

cancellationSignal: CancellationSignal?

an optional signal that allows for cancelling this call

executor: Executor

the callback will take place on this executor

callback: CredentialManagerCallback<GetCredentialResponseGetCredentialException>

the callback invoked when the request succeeds or fails

prepareGetCredential

@RequiresApi(value = 34)
open suspend fun prepareGetCredential(request: GetCredentialRequest): PrepareGetCredentialResponse

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
request: GetCredentialRequest

the request for getting the credential

prepareGetCredentialAsync

Added in 1.2.0
@RequiresApi(value = 34)
fun prepareGetCredentialAsync(
    request: GetCredentialRequest,
    cancellationSignal: CancellationSignal?,
    executor: Executor,
    callback: CredentialManagerCallback<PrepareGetCredentialResponseGetCredentialException>
): Unit

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
request: GetCredentialRequest

the request for getting the credential

cancellationSignal: CancellationSignal?

an optional signal that allows for cancelling this call

executor: Executor

the callback will take place on this executor

callback: CredentialManagerCallback<PrepareGetCredentialResponseGetCredentialException>

the callback invoked when the request succeeds or fails