Skip to content
Back to skills

Restore Credentials

ASecurity

Provides knowledge and workflows to implement Android's Restore Credentials

  • 3 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 6, 2026
testinggokotlinshelltestinggitapidatabasebackendsecuritydocumentation

Works with

  • cli
  • api

Security analysis

A100/100

Pro scans all 6 files and shows the line behind each finding

Scanned December 6, 2026

npx -y skills add network-user/dotcore-skills --skill restore-credentials --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Restore Credentials?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Restore Credentials
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/network-user-restore-credentials/badge)](https://www.skillsdirectory.com/skills/network-user-restore-credentials)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: restore-credentials
description: Provides knowledge and workflows to implement Android's Restore Credentials
  feature using the androidx.credentials library. Use this skill to create, sign in
  with, and delete restore keys, enabling silent user sign-in on new devices after
  a restore. It covers version compatibility, dependencies, server-side prerequisites,
  and the complete client-side implementation for creating, retrieving, and clearing
  restore keys.
license: Complete terms in LICENSE.txt
metadata:
  author: Google LLC
  last-updated: '2026-12-02'
  keywords:
  - Credential Manager
  - Restore Credentials
  - backup & restore
  - backup
  - restore
  - implementation
---

## Fundamentals

The objective is to implement the **Restore Credentials** feature through the
Android Credential Manager API (`androidx.credentials`). This allows apps that
use or are integrating Credential Manager to silently log users back in when
they restore their app on a new device. Restore Credentials operates
independently of the app's primary authentication method (passwords, passkeys,
federated sign-in) and requires no UI changes to existing sign-in flows.

### Scope

**Crucial:** This skill focuses exclusively on the Android client-side
integration. It does **not** implement the server-side cryptographic
validation logic. The developer must be reminded of this and the
[Points to inform the developer about](#backend-guidelines) after implementation is done.

## Implementation Guidelines

When instructed to implement Restore Credentials on a developer's application,
remember the following:

1. Before the implementation, you **MUST** read and understand the [Two-Tier
   Restoration Architecture](#two-tier-restoration-architecture) and review the [DOs and DON'Ts](#dos-and-donts).
2. After the implementation, you **MUST** present the developer with the [Backend Guidelines](#backend-guidelines) as a reminder for their backend setup. It is important that you remind the developer that they still have to implement the backend.

## Two-Tier Restoration Architecture

To enable a resilient sign-in experience, retrieve credentials through a
**two-tier architecture**:

1. **Tier 1 (Primary - Background):** Executes automatically during device setup using the app's `BackupAgent.onRestoreFinished()` callback. This provides an invisible restoration before the user opens the app for the first time, allowing background sync and notification delivery.
2. **Tier 2 (Secondary - Foreground):** Runs in the Launcher `Activity.onCreate()` to catch failovers if background restoration didn't complete (example: dropped network, delayed restoration) or if `allowBackup` is disabled.

If `allowBackup` in the manifest is set to true, implement both. Otherwise, only
implement tier 2 (Foreground Restoration). Do **NOT** change the value of
`allowBackup` in the manifest.

If you added a `BackupAgent` to the app, you **MUST** also set
`android:fullBackupOnly="true"` in the manifest. Do **NOT** do this if there
already existed a `BackupAgent` in the app before your implementation.

## DOs and DON'Ts

**DO:**

- Do check `AndroidManifest.xml` for the value of allowBackup to determine what you have to implement.
- Do implement a fallback for createCredential: always try calling it first with `isCloudBackupEnabled` set to true. If an `E2eeUnavailableException` is thrown, catch it and retry the call with `isCloudBackupEnabled` set to `false`.
- Do implement a `BackupAgent` (subclass of `android.app.backup.BackupAgent`) if `allowBackup` is true in the manifest.
- Do set `android:fullBackupOnly="true"` in the manifest if you added a `BackupAgent` to the app.
- Call `clearCredentialState()` when the user signs out. This is a mandatory security measure to log the user out fully.
- Do attempt to get the restore key on the first launch of the app on a new device and also within the `BackupAgent.onRestoreFinished()` callback if your app uses it.
- Do ensure that a restore credential is created even if the user is already logged in.
- Do ensure that the credential retrieval and login in `onRestoreFinished()` is performed synchronously (for example using `runBlocking`).
- Do restore notifications in the `BackupAgent` if your app uses them. (For example capture and send FCM token to backend)
- Do ensure that if you implement mock network requests or stubs, you replace all placeholders with valid, properly formatted JSON payloads for the credential requests.
- Do encapsulate credential creation and retrieval into their own dedicated functions. Because credential creation must be called in multiple places (sign-up, sign-in) and retrieval across multiple tiers (`BackupAgent` and Launcher `Activity`), this prevents code duplication.
- Do remind the developer of the [critical guidelines](#implementation-guide) for implementing the backend once you're done with the implementation.
- Do generate a separate restore key for each application if the organization has multiple apps with different package names, as a restore key is tied to a unique application package name.

**DON'T:**

- DON'T change the value of `allowBackup` in `AndroidManifest.xml`. Restore Credentials functionality is not affected by the allowBackup setting, meaning the user will still be automatically logged in when a Restore Credential exists, even if `allowBackup` is false.
- DON'T implement a `BackupAgent` if `allowBackup` is `false` in `AndroidManifest.xml`.
- DON'T assume the credential stored in the `GetCredentialResponse` to be of type `PublicKeyCredential`. It has type `RestoreCredential`.
- DON'T chain `GetRestoreCredentialOption` with any other `CredentialOption` in the construction of a `GetCredentialRequest`.
- DON'T assume `CredentialManager` or the Android system will automatically delete a restore key when a user signs out of the app. You must explicitly call `clearCredentialState` with a `ClearCredentialStateRequest` of `TYPE_CLEAR_RESTORE_CREDENTIAL`.
- DON'T remove any existing calls to `clearCredentialState()`. A `ClearCredentialStateRequest` without a type specified only clears all NON-restore credentials.

## Implementation Guide

Implement the Android client-side code by using the following guide. Follow it
**step-by-step** and don't implement any backend functionality, only remind
the user of the [Backend Guidelines](#backend-guidelines) once you're done.

## Version compatibility

Credential Manager's Restore Credentials works on devices running Android 9
(API level 28) and higher, Google Play services (GMS) core version `242200000`
(v24.22) or higher, and version `1.5.0` or higher of the `androidx.credentials`
library. On devices without Google Play services or with a lower GMS version,
catch
[`CreateCredentialProviderConfigurationException`](https://developer.android.com/reference/androidx/credentials/exceptions/CreateCredentialProviderConfigurationException) and
[`GetCredentialProviderConfigurationException`](https://developer.android.com/reference/androidx/credentials/exceptions/GetCredentialProviderConfigurationException) so your app falls back
gracefully to standard sign-in.

## Prerequisites

Set up a WebAuthn [relying party server](#backend-guidelines) similar to a [passkeys](#dos-and-donts) relying
party server. If you already operate a WebAuthn [server](#two-tier-restoration-architecture) for
passkeys, you can reuse the same cryptographic verification library and
endpoints for restore keys while applying the [server-side architecture and key
lifecycle guidelines](#server-side-guidelines).

> [!NOTE]
> **Note:** While server-side verification uses WebAuthn, your client app can support restore keys without supporting user-facing passkeys. Store restore keys with a distinct credential flag in your backend database so they don't appear in user-facing passkey management screens. Because restore keys work independently of your primary authentication method (such as passwords, OTP, or Sign in with Google), you don't need to change your app's existing sign-in UI.

## Dependencies

Add the following dependencies to your app module's `build.gradle` file:

### Kotlin

```kotlin
dependencies {
    implementation("androidx.credentials:credentials:1.7.0-alpha03")
    implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha03")
}
```

### Groovy

```groovy
dependencies {
    implementation "androidx.credentials:credentials:1.7.0-alpha03"
    implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha03"
}
```

Restore Credentials is available in version `1.5.0` and higher of the
`androidx.credentials` library. We recommend using the latest stable version of
the dependencies where possible.

## Background restoration and foreground fallback

To deliver a zero-tap sign-in experience across both cloud backups and cable or
Wi-Fi Direct device-to-device (D2D) transfers, we recommend restoring
credentials silently in the background with a foreground fallback:

- **Tier 1: Background restoration (`BackupAgent.onRestoreFinished()`,
  recommended)**: Executes automatically in the background during device setup immediately after app data is restored. Restoring the user's session here signs the user in before they open your app for the first time, enabling immediate background sync and push notification delivery.
- **Tier 2: Foreground fallback (Launcher `Activity.onCreate()`)** : Executes when the user launches your app for the first time on the new device if no active session exists yet. Include this as a fallback in case background restoration fails to complete (for example, if the device was offline during setup or transferred without an app data backup), or if your app keeps `android:allowBackup="false"`.

Check your `AndroidManifest.xml` for [`android:allowBackup`](references/android/guide/topics/manifest/application-element.md) before choosing which tiers to implement:

| `android:allowBackup` in `AndroidManifest.xml` | Required restoration tiers | Manifest configuration rules |
|---|---|---|
| `android:allowBackup="true"` (default) | Implement both Tier 1 (`BackupAgent`) and Tier 2 (`Activity.onCreate()`) | If you add a new `BackupAgent` subclass to an app that didn't previously define one, also set `android:fullBackupOnly="true"` in `<application>` to preserve Auto Backup behavior. |
| `android:allowBackup="false"` | Implement Tier 2 (`Activity.onCreate()`) only | Don't change `android:allowBackup` to `"true"` and don't register a `BackupAgent` if your app intentionally disables app data backup. |

> [!IMPORTANT]
> **Important:** Don't flip an intentional `android:allowBackup="false"` to `"true"` in `AndroidManifest.xml`, and don't add `android:fullBackupOnly="true"` if your app already defines an existing custom key-value `BackupAgent`, because doing so disables your existing `onBackup()` and `onRestore()` callbacks.

### How android:allowBackup affects key transfer and testing

The [`android:allowBackup`](references/android/guide/topics/manifest/application-element.md) manifest attribute controls app data backup,
which interacts with Restore Credentials in the following ways:

- **Restore key transfer (`allowBackup` independent)** : Google Play services transfers the `RestoreCredential` key pair using end-to-end encrypted cloud backup or local D2D transfer regardless of whether `android:allowBackup` is `true` or `false`. For D2D transfers, the restore key always transfers; for cloud backups, the only condition under which it doesn't transfer is when the user has opted out of cloud backup in Android Settings or lacks encrypted backup enrollment.
- **Android Studio Backup and Restore testing** : Testing the **Cloud** backup type in Android Studio's Backup and Restore tool requires `android:allowBackup="true"`, whereas **Device to Device** testing works regardless of `allowBackup`.

## Overview

The following steps summarize the high-level workflow for implementing Restore
Credentials across your client app and backend server:

1. [**Create a restore key**](#create-restore-key):
   1. [**Instantiate Credential Manager**](#implementation-guide): Create a `CredentialManager` object.
   2. [**Get credential creation options from your app server**](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API): Fetch WebAuthn `PublicKeyCredentialCreationOptions` JSON from your server.
   3. [**Create the restore key**](https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson): Call `createCredential()` (encapsulated in a dedicated helper across sign-in and `Activity.onCreate()`) with `isCloudBackupEnabled = true` and fall back to `isCloudBackupEnabled = false` if `E2eeUnavailableException` is thrown.
   4. [**Handle the credential creation response**](https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson): Send `CreateRestoreCredentialResponse.responseJson` to your app server and record your local sync marker in [`Context.getNoBackupFilesDir()`](https://developer.android.com/reference/android/content/Context#getNoBackupFilesDir()).
2. [**Sign in with a restore key**](#sign-restore):
   1. [**Get credential retrieval options from your app server**](#get-credential-retrieval): Fetch unauthenticated WebAuthn `PublicKeyCredentialRequestOptions` JSON from your server.
   2. [**Get the restore key**](#get-restore): Call `getCredential()` through a shared retrieval helper synchronously in `BackupAgent.onRestoreFinished()` (Tier 1, recommended) and as a fallback on first launch in `Activity.onCreate()` (Tier 2).
   3. [**Handle the sign-in response**](#handle-sign-in): Cast the returned credential to `RestoreCredential`, verify `authenticationResponseJson` on your server, and refresh push notification tokens.
3. [**Delete a restore key**](#delete-restore): Perform a dual clear with `clearCredentialState()` (`ClearCredentialStateRequest()` and `ClearCredentialStateRequest.TYPE_CLEAR_RESTORE_CREDENTIAL`) and delete your local sync marker from `Context.getNoBackupFilesDir()` whenever the user signs out or when a session is invalidated remotely, paired with server-side credential ID deactivation.
4. [**Server-side architecture and key lifecycle guidelines**](#server-side-guidelines): Configure your relying party server to differentiate restore keys from passkeys, support `1:N` multidevice mapping with preserved `credId` rewrapping, and enforce authoritative server-side `credId` revocation.

## Create a restore key

Cover all signed-in user journeys so that both newly authenticating users and
existing signed-in users upgrading to your updated app version have a restore
key created:

- **During sign-in or sign-up**: Create the restore key immediately after the user completes authentication or registration.
- **On app launch for already signed-in users** : In your main `Activity.onCreate()`, if the user is already signed in and a restore key hasn't been created yet on this device, create one silently in the background.

Because restore key creation runs both after sign-in and in
`Activity.onCreate()`, encapsulate key creation in a dedicated helper function
so you don't duplicate request and fallback logic.

To avoid calling `createCredential()` on every app launch, store a local sync
flag such as `has_synced_restore_credential` inside
[`Context.getNoBackupFilesDir()`](https://developer.android.com/reference/android/content/Context#getNoBackupFilesDir())---for example, using a marker `File` or a
Jetpack `DataStore` file in `context.noBackupFilesDir`. Android automatically
excludes `getNoBackupFilesDir()` from Auto Backup without requiring custom
`data_extraction_rules.xml` rules. Don't store this flag in default
`SharedPreferences` or a backed-up `DataStore` directory; otherwise, Auto
Backup copies `has_synced_restore_credential = true` onto the new device and
prevents the new device from generating or rotating its own restore key.

> [!NOTE]
> **Note:** A restore key is tied to an application's unique package name. If your organization's main app and sub-apps have different package names, create a separate restore key for each app.

### Instantiate Credential Manager

Use your app's activity context to instantiate a `CredentialManager` object.

```kotlin
// Use your app or activity context to instantiate a client instance of
// CredentialManager.
private val credentialManager = CredentialManager.create(context)
```

### Get credential creation options from your app server

Use a FIDO2 or WebAuthn-compliant library on your app server to generate
`PublicKeyCredentialCreationOptions` JSON required to create the restore
credential. For more information about the server-side implementation, see
[Server-side guidance](https://developers.google.com/identity/passkeys/developer-guides/server-registration).

The creation options JSON follows the same structure as passkey registration:

```json
{
  "challenge": "<base64url-encoded challenge>",
  "rp": {
    "name": "<relying party name>",
    "id": "<relying party host name>"
  },
  "user": {
    "id": "<base64url-encoded user ID>",
    "name": "<user name>",
    "displayName": "<user display name>"
  },
  "pubKeyCredParams": [
    {
      "type": "public-key",
      "alg": -7
    }
  ],
  "attestation": "none",
  "excludeCredentials": [
    {
        "id": "<base64url-encoded credential ID to exclude>", 
        "type": "public-key"
    }
  ],
  "authenticatorSelection": {
    "requireResidentKey": true,
    "residentKey": "required",
    "userVerification": "required"
  }
}
```

Make sure your creation options JSON meets these requirements:

- `challenge` and `user.id`: Encode both values as unpadded Base64URL strings (replacing `+` with `-`, `/` with `_`, and stripping trailing `=`), where `user.id` decodes to `1` to `64` bytes. Standard Base64 characters, raw integer IDs, or a `user.id` outside the 1-64 byte range cause [`CreateRestoreCredentialDomException`](https://developer.android.com/reference/androidx/credentials/exceptions/restorecredential/CreateRestoreCredentialDomException) or `IllegalArgumentException`.
- `rp.id`: Set to your relying party's domain (for example, `example.com`).
- `pubKeyCredParams`: Include `{"type": "public-key", "alg": -7}` (`ES256`), because Google Play services generates ECDSA P-256 (`ES256`) restore keys (you can also include `{"type": "public-key", "alg": -257}` for `RS256` server compatibility).

### Create the restore key

Wrap the server's `requestJson` in a [`CreateRestoreCredentialRequest`](https://developer.android.com/reference/androidx/credentials/CreateRestoreCredentialRequest)
object and call [`credentialManager.createCredential()`](https://developer.android.com/reference/androidx/credentials/CredentialManager#createCredential(android.content.Context,androidx.credentials.CreateCredentialRequest)). Attempt creation
with `isCloudBackupEnabled = true` first, and catch
[`E2eeUnavailableException`](https://developer.android.com/reference/androidx/credentials/exceptions/restorecredential/E2eeUnavailableException) to retry with `isCloudBackupEnabled = false`
so local D2D transfers remain supported even on devices without cloud backup or
a knowledge-factor screen lock:

```kotlin
// requestJson contains the credential creation options sent by the server
val createRestoreRequest = CreateRestoreCredentialRequest(requestJson)
val response = try {
    credentialManager.createCredential(context, createRestoreRequest)
} catch (e: E2eeUnavailableException) {
    // Fall back to local device-to-device (D2D) restore if cloud E2EE is unavailable
    credentialManager.createCredential(
        context,
        CreateRestoreCredentialRequest(requestJson, isCloudBackupEnabled = false),
    )
}
```

#### Key points about the code

- The `CreateRestoreCredentialRequest` object contains the following fields:

  - `requestJson`: The credential creation options sent by the app server in the [Web Authentication API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API) format for [`PublicKeyCredentialCreationOptionsJSON`](https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson).
  - `isCloudBackupEnabled`: `Boolean` field to determine if the restore key
    should be backed up to the cloud. By default, this flag is `true`. This
    field has these values:

    - `true`: (**Recommended**) Enables backing up the restore key to the cloud with end-to-end encryption when the user has Android data backup and a knowledge-factor screen lock (PIN, pattern, or password) enabled.
    - `false`: Saves the restore key locally on the device without backing it up to the cloud. The key can transfer over a direct device-to-device (D2D) setup connection, but isn't available if the user restores from a cloud backup only.

  > [!CAUTION]
  > **Caution:** Try `isCloudBackupEnabled = true` first and fall back to `false` only when `E2eeUnavailableException` is thrown. If cloud backup is disabled unconditionally and the user restores from a cloud backup, the call to retrieve the restore key fails and the user isn't automatically signed in.

### Handle the credential creation response

`createCredential()` returns a [`CreateRestoreCredentialResponse`](https://developer.android.com/reference/androidx/credentials/CreateRestoreCredentialResponse)
containing `responseJson` in the standard WebAuthn
[`AuthenticatorAttestationResponse` JSON format](https://w3c.github.io/webauthn/#authenticatorattestationresponse). Send
`response.responseJson` to your relying party server to verify and store the
public key and credential ID (`credId`) associated with the user's account, and
then record your local sync marker in `context.noBackupFilesDir`. For more
information about server-side verification, see [the guidance for passkeys](references/android/identity/passkeys/create-passkeys.md).

During the restore key creation process, handle these exceptions:

- [`CreateRestoreCredentialDomException`](https://developer.android.com/reference/androidx/credentials/exceptions/restorecredential/CreateRestoreCredentialDomException): Thrown if `requestJson` is invalid and doesn't follow the WebAuthn format for [`PublicKeyCredentialCreationOptionsJSON`](https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson).
- [`E2eeUnavailableException`](https://developer.android.com/reference/androidx/credentials/exceptions/restorecredential/E2eeUnavailableException): Thrown if `isCloudBackupEnabled` is `true`, but the user's device doesn't have Android cloud backup or a knowledge-factor screen lock (PIN, pattern, or password) enabled. Catch this exception and call `createCredential()` again with `isCloudBackupEnabled` set to `false`.
- `IllegalArgumentException`: Thrown if `requestJson` is empty, isn't valid JSON, or doesn't have a valid Base64URL-encoded `user.id` that conforms to the WebAuthn [specifications](https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson).

## Sign in with a restore key

When the user sets up a new device, retrieve the restore key to silently
authenticate the user without showing a sign-in prompt.

### Get credential retrieval options from your app server

Before calling `getCredential()` on the new device, request a WebAuthn
`PublicKeyCredentialRequestOptions` JSON challenge (`authenticationJson`) from
your app server. Because the app on the new device doesn't yet know which user
is signing in, this endpoint must be **unauthenticated** (userless discovery).
For related passkey guidance, see [Sign in with a passkey](references/android/identity/passkeys/sign-in-with-passkeys.md) and the
[server-side authentication guide](https://developers.google.com/identity/passkeys/developer-guides/server-authentication#create_credential_request_options).

The retrieval options JSON has the following structure:

```json
{
  "challenge": "<your app challenge>",
  "allowCredentials": [],
  "rpId": "<your app server domain>"
}
```

Configure the retrieval options JSON on your server as follows:

- `allowCredentials`: Omit this field or pass an empty array (`[]`) because the user's account isn't known before restoration. After `getCredential()` returns, your server identifies the user from the `response.userHandle` field (which matches the `user.id` registered during creation) and looks up the public key by `id` (`credId`).
- `userVerification`: Set to `"discouraged"` (or `"preferred"`). Because Restore Credentials runs silently without biometric or screen-lock UI, Android overrides `"required"` to `"discouraged"`, and the authenticator data returned to your server has the User Verified (`uv`) flag set to `false`. Configure your WebAuthn server verifier to accept `uv = false` for restore key assertions.

### Get the restore key

Wrap the server's `authenticationJson` in a `GetRestoreCredentialOption` inside
a `GetCredentialRequest` and call `getCredential()` on the `CredentialManager`
object.

> [!CAUTION]
> **Caution:** Don't combine `GetRestoreCredentialOption` with any other `CredentialOption` (such as `GetPublicKeyCredentialOption` or `GetPasswordOption`) in the same `GetCredentialRequest`. Passing multiple options with `GetRestoreCredentialOption` throws an `IllegalArgumentException`.

Encapsulate credential retrieval in a shared `suspend` function (such as
`getRestoreKey()`) so you can invoke it from both
[`BackupAgent.onRestoreFinished()`](https://developer.android.com/reference/android/app/backup/BackupAgent#onRestoreFinished()) (Tier 1) and your launcher
`Activity.onCreate()` (Tier 2):

```kotlin
    suspend fun getRestoreKey(
        fetchAuthenticationJson: () -> String,
    ) {
        // Fetch the options required to get the restore key
        val authenticationJson = fetchAuthenticationJson()

        // Create the GetRestoreCredentialOption object
        val options = GetRestoreCredentialOption(authenticationJson)
        val getRequest = GetCredentialRequest(listOf(options))

        try {
            val response = credentialManager.getCredential(context, getRequest)

            // Type-check and extract the restore credential
            val credential = response.credential
            if (credential is RestoreCredential) {
                val responseJson = credential.authenticationResponseJson
            }
        } catch (e: NoCredentialException) {
            // No restore key is present on this device
        }
    }

class MyBackupAgent : BackupAgent() {

    override fun onRestoreFinished() {
        super.onRestoreFinished()
        val credentialManager = CredentialManager.create(this)
        val restoreFunctions = RestoreCredentialsFunctions(this, credentialManager)

        runBlocking(Dispatchers.IO) {
            restoreFunctions.getRestoreKey(
                fetchAuthenticationJson = {
                    /* Fetch challenge JSON from server */ ""
                }
            )
        }
    }
}
```

`getCredential()` returns a [`GetCredentialResponse`](https://developer.android.com/reference/androidx/credentials/GetCredentialResponse) whose `credential`
property is a [`RestoreCredential`](https://developer.android.com/reference/androidx/credentials/RestoreCredential) containing `authenticationResponseJson`.
Because `RestoreCredential` subclasses `Credential` directly rather than
`PublicKeyCredential`, checking `credential is PublicKeyCredential` evaluates to
`false` for a restore key. If your authentication repository handles both
passkeys and restore keys in a shared helper, branch with `when (credential)`
and check `is RestoreCredential` separately from `is PublicKeyCredential`:

```kotlin
// RestoreCredential and PublicKeyCredential are distinct subclasses of Credential.
val responseJson: String? = when (val credential = response.credential) {
    is RestoreCredential -> credential.authenticationResponseJson
    is PublicKeyCredential -> credential.authenticationResponseJson
    else -> null
}
```

#### Tier 1: Background restoration in BackupAgent.onRestoreFinished

If `android:allowBackup="true"` (recommended), implement [`BackupAgent`](https://developer.android.com/reference/android/app/backup/BackupAgent)
(such as `MyBackupAgent` in the preceding snippet) and invoke `getRestoreKey()`
inside [`onRestoreFinished()`](https://developer.android.com/reference/android/app/backup/BackupAgent#onRestoreFinished()). Don't put Restore Credentials retrieval
inside `onRestore()`, which runs only for legacy key-value backups, whereas
`onRestoreFinished()` runs reliably after any backup restore.

> [!IMPORTANT]
> **Important:** `BackupAgent.onRestoreFinished()` is a synchronous lifecycle callback. Because `credentialManager.getCredential()` is a `suspend` function, you must block synchronously (for example, using `runBlocking(Dispatchers.IO)` with a timeout) until credential retrieval, backend verification, and push token registration complete. Don't launch an asynchronous fire-and-forget coroutine, because Android can destroy the `BackupAgent` process as soon as `onRestoreFinished()` returns.

If you add a new `BackupAgent` to an app that previously relied on default Auto Backup (`android:allowBackup="true"`), add `android:fullBackupOnly="true"` to the `<application>` element in `AndroidManifest.xml` so Android continues performing full file backups. Don't add `android:fullBackupOnly="true"` if your app already had an existing custom `BackupAgent`.

> [!IMPORTANT]
> **Important:** Push notifications aren't automatically restored when a restore key is retrieved. Inside `BackupAgent.onRestoreFinished()` (or immediately after Tier 2 sign-in), fetch a fresh Firebase Cloud Messaging (FCM) registration token (for example, `FirebaseMessaging.getInstance().token.await()`) and register it with your backend so background notifications resume before the user opens the app.

#### Tier 2: Foreground fallback in launcher Activity.onCreate

In your launcher `Activity.onCreate()`, check whether the user already has an
active local session (from Tier 1 or a prior sign-in). If not, call
`getRestoreKey()` from `lifecycleScope` before rendering your sign-in screen.

### Handle the sign-in response

Send `restoreCredential.authenticationResponseJson` to your relying party
server to verify the `SHA256withECDSA` signature against the stored public key
and issue fresh app session tokens. For more information about server-side
WebAuthn verification, see [Sign in with a passkey](references/android/identity/passkeys/sign-in-with-passkeys.md).

> [!NOTE]
> **Note:** Because `getCredential()` runs silently without an interactive biometric or PIN prompt (`userVerification = false`, `userPresence = true`) to enable background restoration in `BackupAgent.onRestoreFinished()`, a restored key can still be retrieved on a new device if the user skipped setting a destination screen lock during setup or later removed it. If your app's security policy requires an active device lock screen before granting access to sensitive data, check `KeyguardManager.isDeviceSecure()` after restoring the session and prompt for step-up authentication when needed.

#### Restore WebView and Custom Tabs sessions

Restore Credentials generates an app-scoped WebAuthn key pair and doesn't
transfer system browser or Custom Tabs cookies. Don't rely on copying raw
authentication cookies from the previous device to restore web sessions---copied
cookies can expire before device setup or fail to transfer depending on user
backup settings.

- **Custom Tabs and OpenID Connect (OIDC)**: Restore your native app OAuth or session tokens silently first using Restore Credentials, and decouple routine API calls from browser cookies. When the user opens an authenticated Custom Tabs flow, make a back-channel request from your restored native session to your identity provider to mint a short-lived, single-use session-transfer ticket, and launch Custom Tabs with that ticket. Never pass raw access or refresh tokens in front-channel URLs.
- **[`WebView`](https://developer.android.com/reference/android/webkit/WebView) sessions** : Call `getCredential()` from your Android app code and verify `restoreCredential.authenticationResponseJson` on your backend to mint fresh session cookies (or exchange for a fresh session with your identity provider). Inject those fresh cookies through [`CookieManager`](https://developer.android.com/reference/android/webkit/CookieManager) (call `CookieManager.getInstance().setCookie()`, followed by `flush()`) before calling `webView.loadUrl()`. If the identity provider rejects restoration due to a genuine session expiry or remote revocation, fall back to interactive sign-in while preserving the user's recognized identity context where possible.

## Delete the restore key

Credential Manager is stateless and doesn't automatically delete restore keys
when a user signs out of your app. Restore keys are deleted on the device when
the user uninstalls your app, clears your app's storage in system settings, or
triggers your app's programmatic sign-out flow.

Delete the restore key and your local sync marker whenever:

- The user signs out of your app.
- Your app detects a **server-side session invalidation** (for example, when the user resets their password on the web or your server returns an HTTP `401 Unauthorized` error).

Because a default `ClearCredentialStateRequest()` clears only non-restore
credential session state and leaves the restore key intact, perform a **dual
clear** on sign-out:

1. Call `credentialManager.clearCredentialState(ClearCredentialStateRequest())` to clear active credential provider session state.
2. Call [`credentialManager.clearCredentialState()`](https://developer.android.com/reference/androidx/credentials/CredentialManager#clearCredentialState(androidx.credentials.ClearCredentialStateRequest)) with `ClearCredentialStateRequest(ClearCredentialStateRequest.TYPE_CLEAR_RESTORE_CREDENTIAL)` to delete the stored `RestoreCredential`.
3. Delete your local `has_synced_restore_credential` marker from `context.noBackupFilesDir`.

```kotlin
// Clear active credential provider session state
credentialManager.clearCredentialState(ClearCredentialStateRequest())

// When the user logs out, delete the restore key
val clearRequest = ClearCredentialStateRequest(TYPE_CLEAR_RESTORE_CREDENTIAL)
val response = credentialManager.clearCredentialState(clearRequest)
```

Removing a Google Account from Android system settings doesn't clear your app's
local restore key on that device and doesn't immediately erase existing cloud
backups; it only stops future cloud backup syncs from that device. Cloud backup
copies are deleted only when an online device syncs a
`clearCredentialState(ClearCredentialStateRequest(ClearCredentialStateRequest.TYPE_CLEAR_RESTORE_CREDENTIAL))`
call, when the user turns off or deletes backup data in Android settings or
Google One, or automatically after 57 days of device backup inactivity. Always
pair client-side deletion with server-side deactivation of the credential ID
(`credId`).

## Server-side architecture and key lifecycle guidelines

When configuring your relying party backend to support Restore Credentials,
follow these five architectural guidelines:

1. **Differentiate restore keys from user-created passkeys** : Tag restore keys in your database with a dedicated credential type or metadata attribute so they aren't shown in user-facing passkey management UIs, and configure your verification policy to accept assertions with `uv = false` (`up = true`) so silent background restoration succeeds.
2. **Support `1:N` multidevice mapping and preserved `credId` across
   migrations** : Each device holds `0` or `1` active restore key per app package, while a user signed in across multiple devices (such as a phone and a tablet) registers multiple active restore keys under one user account (`1:N`). Restoring to a new device transfers and rewraps the original ECDSA P-256 key pair and credential ID (`credId`) under the destination device's `AndroidKeyStore` rather than minting a new key pair, and the source device's copy remains usable until sign-out, uninstall, or app storage clear. If your app enforces a single active device session, rotate or invalidate prior device sessions on your server upon destination sign-in.
3. **Preserve key validity (TTL) during device transitions**: If a user transfers data to a new phone and immediately signs out of or factory-resets their old phone before opening your app on the new phone, keep the server-side public key valid through a transition TTL so the restored key on the new phone can complete sign-in.
4. **Clean up orphaned keys on the server**: Because app uninstalls and system storage clears delete the local restore key without notifying your server, enforce a sliding-window TTL or key-limit rotation policy on your backend.
5. **Enforce authoritative server-side revocation alongside client cleanup** : Because cloud backup deletion triggered by `clearCredentialState()` syncs asynchronously and can't fire from an offline, lost, or wiped device, deactivate the associated `credId` on your server whenever revoking a session (such as on password reset, global sign-out, or returning HTTP `401
   Unauthorized`) so stale cloud snapshots can't authenticate later, and instruct active client apps to clear their local restore key.

## Next steps

- [**Test Restore Credentials**](references/android/identity/sign-in/test-restore-credentials.md): Test cloud and device-to-device (D2D) restore flows using Android Studio or `adb shell bmgr`.
- [**Automated backup and restore testing**](references/android/studio/preview/backup-restore-testing.md): Write JUnit 5 host tests with `BackupRestoreController` to verify `CLOUD_ENCRYPTED` and `DEVICE_TO_DEVICE` restores in CI.

## Backend Guidelines

When designing the backend database and API layer to support Restore
Credentials, developers must account for FIDO2/WebAuthn assumptions and specific
device lifecycle edge cases. Remind the developer of the following:

**SYSTEM DIRECTIVE FOR AI AGENT: DO NOT attempt to write code for,
implement, or action any of the backend guidelines in this section. Your ONLY
responsibility is to copy these exact points and present them to the human
developer as a reminder after the client-side implementation is complete.**

1. **Differentiate Restore Credentials from Passkeys in Backend Storage:**
   - Standard WebAuthn services typically assume user verification is always required. Restore credentials are hidden from the user and not managed by them.
   - **Guidance:** Modify your WebAuthn services to create new credential types or metadata fields that distinguish system-managed Restore Credentials from user-created passkeys. Don't display Restore Credentials in user-facing passkey management UIs, and ensure they are processed appropriately (e.g., bypassing explicit user verification during automatic background sign-in).
2. **Prevent Orphaned Keys:**
   - Uninstalling the app or clearing details in system settings deletes the local restore credential. Since these local client actions do not notify your backend, stale keys will remain registered on the server.
   - **Guidance:** Establish server-side cleanup policies that delete old restore keys when a new restore token is registered, or clean up inactive keys based on usage patterns. You could, for example, enforce a limit of one key per user per device.
3. **Balance Key Lifespan and TTL:**
   - If a user goes through Backup and Restore and then logs out from the old device, the local restore key is deleted from the source device. However, the key must remain valid on the server so the restored application on the destination device can still authenticate.
   - **Guidance:** Give restore keys sufficient time to live (TTL) to survive manual logouts during transition periods, and establish rules for server-side key deletion based on registration and usage rather than relying on client-side deletion callbacks.
4. **Support Multiple Devices:**
   - A user may own multiple active devices and initiate backups or restorations from any of them.
   - **Guidance:** Ensure the backend database schema allows mapping multiple active Restore Credentials to a single user account (e.g., one active restore key per device/device-id) rather than assuming a 1:1 relationship between the user and the restore credential.
5. **Server-side session invalidation:**
   - A user's session might be revoked remotely. This could be triggered by user actions such as when a user resets their password on the web or server actions that can cause the API to return HTTP `401 Unauthorized` indicating session expiry.
   - **Guidance:** If this applies, make sure to clear the user's restore credentials on the phone when it happens.

## References

- **WebAuthentication API (WebAuthn) Documentation \& Specification**
  *When to use:* Use these resources ONLY if you need to inspect or debug the
  strict JSON schema requirements for FIDO2/WebAuthn, specifically when
  generating mock data or formatting the `requestJson`
  (`PublicKeyCredentialCreationOptionsJSON`) and `authenticationJson` payloads.

- [MDN Web Authentication API Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API): Mozilla Developer Network
  guide and reference for WebAuthn APIs

- [W3C `PublicKeyCredentialCreationOptionsJSON`](https://w3c.github.io/webauthn/#dictdef-publickeycredentialcreationoptionsjson): Data structure definition
  for WebAuthn credential creation requests in JSON format.

- [W3C `PublicKeyCredentialRequestOptionsJSON`](https://w3c.github.io/webauthn/#dictdef-publickeycredentialrequestoptionsjson): Data structure definition
  for WebAuthn authentication or assertion requests in JSON format.

Files in this skill

  • SKILL.md40.8 KB
  • references/android/guide/topics/manifest/application-element.md39.2 KB
  • references/android/identity/passkeys/create-passkeys.md18.8 KB
  • references/android/identity/passkeys/sign-in-with-passkeys.md11 KB
  • references/android/identity/sign-in/test-restore-credentials.md5.9 KB
  • references/android/studio/preview/backup-restore-testing.md31.9 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in testing →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.