Skip to content

Commit 7598fbe

Browse files
author
Neelansh Sahai
committed
Add restore credential snippets
1 parent 7eb5acd commit 7598fbe

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.example.identity.credentialmanager
2+
3+
import android.content.Context
4+
import androidx.credentials.ClearCredentialStateRequest
5+
import androidx.credentials.ClearCredentialStateRequest.Companion.TYPE_CLEAR_RESTORE_CREDENTIAL
6+
import androidx.credentials.CreateRestoreCredentialRequest
7+
import androidx.credentials.CredentialManager
8+
import androidx.credentials.GetCredentialRequest
9+
import androidx.credentials.GetRestoreCredentialOption
10+
11+
class RestoreCredentialsFunctions(
12+
private val context: Context,
13+
private val credentialManager: CredentialManager,
14+
) {
15+
suspend fun createRestoreKey(
16+
createRestoreRequest: CreateRestoreCredentialRequest
17+
) {
18+
// [START android_identity_restore_cred_create]
19+
val credentialManager = CredentialManager.create(context)
20+
21+
// On a successful authentication create a Restore Key
22+
// Pass in the context and CreateRestoreCredentialRequest object
23+
val response = credentialManager.createCredential(context, createRestoreRequest)
24+
// [END android_identity_restore_cred_create]
25+
}
26+
27+
suspend fun getRestoreKey(
28+
fetchAuthenticationJson: () -> String,
29+
) {
30+
// [START android_identity_restore_cred_get]
31+
// Fetch the Authentication JSON from server
32+
val authenticationJson = fetchAuthenticationJson()
33+
34+
// Create the GetRestoreCredentialRequest object
35+
val options = GetRestoreCredentialOption(authenticationJson)
36+
val getRequest = GetCredentialRequest(listOf(options))
37+
38+
// The restore key can be fetched in two scenarios to
39+
// 1. On the first launch of app on the device, fetch the Restore Key
40+
// 2. In the onRestore callback (if the app implements the Backup Agent)
41+
val response = credentialManager.getCredential(context, getRequest)
42+
// [END android_identity_restore_cred_get]
43+
}
44+
45+
suspend fun deleteRestoreKey() {
46+
// [START android_identity_restore_cred_delete]
47+
// Create a ClearCredentialStateRequest object
48+
val clearRequest = ClearCredentialStateRequest(TYPE_CLEAR_RESTORE_CREDENTIAL)
49+
50+
// On user log-out, clear the restore key
51+
val response = credentialManager.clearCredentialState(clearRequest)
52+
// [END android_identity_restore_cred_delete]
53+
}
54+
}

0 commit comments

Comments
 (0)