設定新裝置時還原應用程式憑證

使用者設定新裝置時,可以透過 Credential Manager 的「還原憑證」功能還原應用程式帳戶。這項 API 目前為開發人員預覽版,適用於搭載 Android 9 以上版本,以及 Google Play 服務 (GMS) Core 242200000 以上版本的所有裝置。「還原憑證」功能的優點包括:

  • 提供流暢的使用者體驗:使用者不必手動登入個別應用程式,即可還原應用程式帳戶。
  • 提高使用者參與度:如果使用者在新裝置上設定時可以還原帳戶,就更有可能繼續使用您的應用程式。
  • 減少開發工作:憑證還原功能已整合至 Credential Manager,因此已支援密碼金鑰的開發人員可以新增憑證還原功能。

運作方式

您可以使用「還原憑證」建立、取得及清除相關憑證。

  1. 建立還原憑證:使用者登入應用程式時,請建立與其帳戶相關聯的還原憑證。這項憑證會儲存在本機,並在使用者啟用 Google 備份且提供端對端加密時,同步到雲端 (應用程式可以選擇不將憑證同步到雲端)
  2. 取得還原憑證:使用者設定新裝置時,應用程式可以向認證管理工具要求還原憑證。這樣一來,您就能自動登入使用者,不必輸入任何額外資訊。
  3. 清除還原憑證:使用者登出應用程式時,您應刪除相關聯的還原憑證。

「還原憑證」功能可與已實作密碼金鑰的後端系統順暢整合。這是因為密碼金鑰和還原金鑰 (「還原憑證」功能使用的憑證類型) 都遵循相同的基礎技術規格。這項調整可確保「還原憑證」程序能有效擷取並還原儲存在啟用密碼金鑰系統中的使用者憑證,在不同平台和驗證方法中提供一致且易於使用的體驗。

Credential Manager 底部功能表
圖 1. 圖表:說明如何使用還原憑證將應用程式資料還原至新裝置,包括建立憑證、啟動還原流程,以及自動登入使用者帳戶

實作

您可以使用 Credential Manager Jetpack 程式庫存取 Restore Credentials API。首先,請按照下列步驟操作:

  1. 在專案中新增憑證管理工具依附元件。

    // build.gradle.kts
    implementation("androidx.credentials:credentials:1.5.0-alpha03")
    
  2. 建立 CreateRestoreCredentialRequest 物件。

  3. 呼叫 CredentialManager 物件的 createCredential() 方法。

    val credentialManager = CredentialManager.create(context)
    
    // On a successful authentication create a Restore Key
    // Pass in the context and CreateRestoreCredentialRequest object
    val response = credentialManager.createCredential(context, createRestoreRequest)
    

    這個產生的還原憑證是 WebAuthn 憑證類型,又稱為還原金鑰

  4. 使用者設定新裝置時,請呼叫 CredentialManager 物件的 getCredential() 方法。

    // Fetch the Authentication JSON from server
    val authenticationJson = fetchAuthenticationJson()
    
    // Create the GetRestoreCredentialRequest object
    val options = GetRestoreCredentialOption(authenticationJson)
    val getRequest = GetCredentialRequest(listOf(options))
    
    // The restore key can be fetched in two scenarios to
    // 1. On the first launch of app on the device, fetch the Restore Key
    // 2. In the onRestore callback (if the app implements the Backup Agent)
    val response = credentialManager.getCredential(context, getRequest)
    
  5. 當使用者登出應用程式時,請呼叫 CredentialManager 物件的 clearCredentialState() 方法。

    // Create a ClearCredentialStateRequest object
    val clearRequest = ClearCredentialStateRequest(TYPE_CLEAR_RESTORE_CREDENTIAL)
    
    // On user log-out, clear the restore key
    val response = credentialManager.clearCredentialState(clearRequest)
    

如果您使用備份代理程式,請在 onRestore 回呼中執行 getCredential 部分。這樣可確保應用程式憑證會在應用程式資料還原後立即還原。