封鎖儲存庫

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

在設定新的 Android 裝置時,許多使用者仍會管理自己的憑證。這項手動程序可能會變得困難,且通常會導致使用者體驗不佳。Block Store API 是由 Google Play 服務提供技術,其程式庫為應用程式提供了一種儲存使用者憑證的方法,而不會儲存使用者密碼的複雜性或安全性風險。

Block Store API 可讓應用程式儲存資料,以供日後在新的裝置上重新驗證使用者。這有助於為使用者提供更流暢的體驗,因為使用者首次在新裝置上啟動應用程式時,不會看到登入畫面。

使用「封鎖商店」的好處如下:

  • 開發人員適用的加密憑證儲存解決方案。憑證會盡可能進行端對端加密。
  • 儲存憑證,而非使用者名稱和密碼。
  • 消除登入流程的阻礙。
  • 省去管理複雜密碼的麻煩。
  • Google 會驗證使用者身分。

事前準備

如要讓應用程式做好準備,請完成下列各節的步驟。

設定應用程式

在專案層級的 build.gradle 檔案中,將 buildscriptallprojects 區段納入 Google Maven 存放區

buildscript {
  repositories {
    google()
    mavenCentral()
  }
}

allprojects {
  repositories {
    google()
    mavenCentral()
  }
}

將 Block Store API 的 Google Play 服務依附元件新增至模組的 Gradle 建構檔案,通常為 app/build.gradle

dependencies {
  implementation 'com.google.android.gms:play-services-auth-blockstore:16.2.0'
}

運作方式

Block Store 可讓開發人員儲存及還原最多 16 個位元組的陣列。 如此一來,您就能儲存目前使用者工作階段的相關重要資訊,並視需要靈活儲存這些資訊。這項資料可以進行端對端加密,而且支援「封鎖」功能的基礎架構是以「備份與還原」基礎架構為基礎。

本指南將說明將使用者的權杖儲存至 Block Store 的功能。以下簡單說明採用「封鎖商店」功能的應用程式運作方式:

  1. 在應用程式的驗證流程期間或之後,您可以將使用者的驗證權杖儲存至 Block Store,以便日後擷取。
  2. 權杖會儲存在本機中,並且可以盡可能備份到雲端,並且盡可能進行端對端加密。
  3. 當使用者在新裝置上啟動還原流程時,系統會轉移資料。
  4. 如果使用者在還原流程中還原您的應用程式,您的應用程式就可以從新裝置上的 Block Store 擷取已儲存的權杖。

儲存憑證

使用者登入應用程式時,您可以將您為該使用者產生的驗證權杖儲存至「封鎖存放區」。您可以使用不重複的金鑰組值來儲存這個憑證,每個鍵的最大值上限為 4kb。如要儲存憑證,請在 StoreBytesData.Builder 執行個體上呼叫 setBytes()'setKey(/android/reference/com/google/android/gms/auth/blockstore/StoreBytesData.Builder.html#setKey(java.lang.String)',以將使用者憑證儲存至來源裝置。使用 Block Store 儲存憑證後,該權杖就會加密並儲存在裝置本機。

下列範例說明如何將驗證憑證儲存至本機裝置:

Java

  BlockstoreClient client = Blockstore.getClient(this);
  byte[] bytes1 = new byte[] { 1, 2, 3, 4 };  // Store one data block.
  String key1 = "com.example.app.key1";
  StoreBytesData storeRequest1 = StoreBytesData.Builder()
          .setBytes(bytes1)
          // Call this method to set the key value pair the data should be associated with.
          .setKeys(Arrays.asList(key1))
          .build();
  client.storeBytes(storeRequest1)
    .addOnSuccessListener(result -> Log.d(TAG, "stored " + result + " bytes"))
    .addOnFailureListener(e -> Log.e(TAG, "Failed to store bytes", e));

Kotlin

  val client = Blockstore.getClient(this)

  val bytes1 = byteArrayOf(1, 2, 3, 4) // Store one data block.
  val key1 = "com.example.app.key1"
  val storeRequest1 = StoreBytesData.Builder()
    .setBytes(bytes1) // Call this method to set the key value with which the data should be associated with.
    .setKeys(Arrays.asList(key1))
    .build()
  client.storeBytes(storeRequest1)
    .addOnSuccessListener { result: Int ->
      Log.d(TAG,
            "Stored $result bytes")
    }
    .addOnFailureListener { e ->
      Log.e(TAG, "Failed to store bytes", e)
    }

使用預設權杖

使用不含位元組的 StoreBytes 儲存的資料會使用預設金鑰 BlockstoreClient.DEFAULT_BYTES_DATA_KEY。

Java

  BlockstoreClient client = Blockstore.getClient(this);
  // The default key BlockstoreClient.DEFAULT_BYTES_DATA_KEY.
  byte[] bytes = new byte[] { 9, 10 };
  StoreBytesData storeRequest = StoreBytesData.Builder()
          .setBytes(bytes)
          .build();
  client.storeBytes(storeRequest)
    .addOnSuccessListener(result -> Log.d(TAG, "stored " + result + " bytes"))
    .addOnFailureListener(e -> Log.e(TAG, "Failed to store bytes", e));

Kotlin

  val client = Blockstore.getClient(this);
  // the default key BlockstoreClient.DEFAULT_BYTES_DATA_KEY.
  val bytes = byteArrayOf(1, 2, 3, 4)
  val storeRequest = StoreBytesData.Builder()
    .setBytes(bytes)
    .build();
  client.storeBytes(storeRequest)
    .addOnSuccessListener { result: Int ->
      Log.d(TAG,
            "stored $result bytes")
    }
    .addOnFailureListener { e ->
      Log.e(TAG, "Failed to store bytes", e)
    }

擷取憑證

之後,當使用者在新裝置上完成還原流程時,Google Play 服務會先驗證使用者,然後擷取您的 Block Store 資料。使用者已同意在還原流程中還原您的應用程式資料,因此不需要額外同意聲明。使用者開啟應用程式時,您可以呼叫 retrieveBytes(),透過 Block Store 要求權杖。系統隨後可使用擷取到的憑證,讓使用者在新裝置上保持登入狀態。

下列範例說明如何根據特定金鑰擷取多個符記。

Java

BlockstoreClient client = Blockstore.getClient(this);

// Retrieve data associated with certain keys.
String key1 = "com.example.app.key1";
String key2 = "com.example.app.key2";
String key3 = BlockstoreClient.DEFAULT_BYTES_DATA_KEY; // Used to retrieve data stored without a key

List requestedKeys = Arrays.asList(key1, key2, key3); // Add keys to array
RetrieveBytesRequest retrieveRequest = new RetrieveBytesRequest.Builder()
    .setKeys(requestedKeys)
    .build();

client.retrieveBytes(retrieveRequest)
    .addOnSuccessListener(
        result -> {
          Map blockstoreDataMap = result.getBlockstoreDataMap();
          for (Map.Entry entry : blockstoreDataMap.entrySet()) {
            Log.d(TAG, String.format(
                "Retrieved bytes %s associated with key %s.",
                new String(entry.getValue().getBytes()), entry.getKey()));
          }
        })
    .addOnFailureListener(e -> Log.e(TAG, "Failed to store bytes", e));

Kotlin

val client = Blockstore.getClient(this)

// Retrieve data associated with certain keys.
val key1 = "com.example.app.key1"
val key2 = "com.example.app.key2"
val key3 = BlockstoreClient.DEFAULT_BYTES_DATA_KEY // Used to retrieve data stored without a key

val requestedKeys = Arrays.asList(key1, key2, key3) // Add keys to array

val retrieveRequest = RetrieveBytesRequest.Builder()
  .setKeys(requestedKeys)
  .build()

client.retrieveBytes(retrieveRequest)
  .addOnSuccessListener { result: RetrieveBytesResponse ->
    val blockstoreDataMap =
      result.blockstoreDataMap
    for ((key, value) in blockstoreDataMap) {
      Log.d(ContentValues.TAG, String.format(
        "Retrieved bytes %s associated with key %s.",
        String(value.bytes), key))
    }
  }
  .addOnFailureListener { e: Exception? ->
    Log.e(ContentValues.TAG,
          "Failed to store bytes",
          e)
  }

擷取所有權杖。

以下舉例說明如何擷取儲存在 BlockStore 的所有權杖。

Java

BlockstoreClient client = Blockstore.getClient(this)

// Retrieve all data.
RetrieveBytesRequest retrieveRequest = new RetrieveBytesRequest.Builder()
    .setRetrieveAll(true)
    .build();

client.retrieveBytes(retrieveRequest)
    .addOnSuccessListener(
        result -> {
          Map blockstoreDataMap = result.getBlockstoreDataMap();
          for (Map.Entry entry : blockstoreDataMap.entrySet()) {
            Log.d(TAG, String.format(
                "Retrieved bytes %s associated with key %s.",
                new String(entry.getValue().getBytes()), entry.getKey()));
          }
        })
    .addOnFailureListener(e -> Log.e(TAG, "Failed to store bytes", e));

Kotlin

val client = Blockstore.getClient(this)

val retrieveRequest = RetrieveBytesRequest.Builder()
  .setRetrieveAll(true)
  .build()

client.retrieveBytes(retrieveRequest)
  .addOnSuccessListener { result: RetrieveBytesResponse ->
    val blockstoreDataMap =
      result.blockstoreDataMap
    for ((key, value) in blockstoreDataMap) {
      Log.d(ContentValues.TAG, String.format(
        "Retrieved bytes %s associated with key %s.",
        String(value.bytes), key))
    }
  }
  .addOnFailureListener { e: Exception? ->
    Log.e(ContentValues.TAG,
          "Failed to store bytes",
          e)
  }

以下舉例說明如何擷取預設金鑰。

Java

BlockStoreClient client = Blockstore.getClient(this);
RetrieveBytesRequest retrieveRequest = new RetrieveBytesRequest.Builder()
    .setKeys(Arrays.asList(BlockstoreClient.DEFAULT_BYTES_DATA_KEY))
    .build();
client.retrieveBytes(retrieveRequest);

Kotlin

val client = Blockstore.getClient(this)

val retrieveRequest = RetrieveBytesRequest.Builder()
  .setKeys(Arrays.asList(BlockstoreClient.DEFAULT_BYTES_DATA_KEY))
  .build()
client.retrieveBytes(retrieveRequest)

刪除憑證

您可能會需要從 BlockStore 刪除憑證,原因如下:

  • 使用者完成登出流程。
  • 憑證已遭撤銷或無效。

與擷取憑證類似,您可以設定需要刪除的金鑰陣列,以指定需要刪除的符記。

以下是刪除特定金鑰的範例。

Java

BlockstoreClient client = Blockstore.getClient(this);

// Delete data associated with certain keys.
String key1 = "com.example.app.key1";
String key2 = "com.example.app.key2";
String key3 = BlockstoreClient.DEFAULT_BYTES_DATA_KEY; // Used to delete data stored without key

List requestedKeys = Arrays.asList(key1, key2, key3) // Add keys to array
DeleteBytesRequest deleteRequest = new DeleteBytesRequest.Builder()
      .setKeys(requestedKeys)
      .build();
client.deleteBytes(deleteRequest)

Kotlin

val client = Blockstore.getClient(this)

// Retrieve data associated with certain keys.
val key1 = "com.example.app.key1"
val key2 = "com.example.app.key2"
val key3 = BlockstoreClient.DEFAULT_BYTES_DATA_KEY // Used to retrieve data stored without a key

val requestedKeys = Arrays.asList(key1, key2, key3) // Add keys to array

val retrieveRequest = DeleteBytesRequest.Builder()
      .setKeys(requestedKeys)
      .build()

client.deleteBytes(retrieveRequest)

刪除所有權杖

下列範例會刪除目前儲存在 BlockStore 的所有權杖:

Java

// Delete all data.
DeleteBytesRequest deleteAllRequest = new DeleteBytesRequest.Builder()
      .setDeleteAll(true)
      .build();
client.deleteBytes(deleteAllRequest)
.addOnSuccessListener(result -> Log.d(TAG, "Any data found and deleted? " + result));

Kotlin

  val deleteAllRequest = DeleteBytesRequest.Builder()
  .setDeleteAll(true)
  .build()
client.deleteBytes(deleteAllRequest)
  .addOnSuccessListener { result: Boolean ->
    Log.d(TAG,
          "Any data found and deleted? $result")
  }

端對端加密

裝置必須搭載 Android 9 以上版本,且使用者必須為裝置設定螢幕鎖定 (PIN 碼、解鎖圖案或密碼),才能使用端對端加密功能。您可以呼叫 isEndToEndEncryptionAvailable() 來確認裝置是否可使用加密功能。

以下範例說明如何驗證在雲端備份期間是否可以使用加密功能:

client.isEndToEndEncryptionAvailable()
        .addOnSuccessListener { result ->
          Log.d(TAG, "Will Block Store cloud backup be end-to-end encrypted? $result")
        }

啟用雲端備份功能

如要啟用雲端備份功能,請在 StoreBytesData 物件中加入 setShouldBackupToCloud() 方法。將 setShouldBackupToCloud() 設為 true 時,Block Store 會定期將儲存的備份備份到雲端。

以下範例僅在雲端備份的端對端加密作業時才啟用雲端備份:

val client = Blockstore.getClient(this)
val storeBytesDataBuilder = StoreBytesData.Builder()
        .setBytes(/* BYTE_ARRAY */)

client.isEndToEndEncryptionAvailable()
        .addOnSuccessListener { isE2EEAvailable ->
          if (isE2EEAvailable) {
            storeBytesDataBuilder.setShouldBackupToCloud(true)
            Log.d(TAG, "E2EE is available, enable backing up bytes to the cloud.")

            client.storeBytes(storeBytesDataBuilder.build())
                .addOnSuccessListener { result ->
                  Log.d(TAG, "stored: ${result.getBytesStored()}")
                }.addOnFailureListener { e ->
                  Log.e(TAG, “Failed to store bytes”, e)
                }
          } else {
            Log.d(TAG, "E2EE is not available, only store bytes for D2D restore.")
          }
        }

測試方法

在開發期間,請使用以下方法來測試還原流程。

解除安裝/重新安裝相同的裝置

如果使用者啟用備份服務 (可依序前往 [設定] > [Google] > [備份]),在應用程式解除安裝/重新安裝的過程中,系統會保持「封鎖」資料。

您可以按照以下步驟進行測試:

  1. 將 BlockStore API 整合至測試應用程式。
  2. 使用測試應用程式叫用 BlockStore API,以儲存資料。
  3. 解除安裝測試應用程式,然後在同一部裝置上重新安裝應用程式。
  4. 使用測試應用程式叫用 BlockStore API 來擷取資料。
  5. 確認擷取的位元組與解除安裝前儲存的資料相同。

裝置對裝置

在大多數情況下,您需要將目標裝置恢復原廠設定。接著,您可以進入 Android 無線還原流程Google 傳輸線還原功能 (適用於支援的裝置)。

雲端還原

  1. 將 Blockstore API 整合至您的測試應用程式。測試應用程式必須提交至 Play 商店。
  2. 在來源裝置上,使用測試應用程式叫用 Blockstore API 來儲存資料,應將 BackBackToCloud 設為 true。
  3. 對於 O 及以上的裝置,您可以手動觸發 Block Store 雲端備份:依序前往「設定」>「Google」>「備份」,然後按一下 [立即備份] 按鈕。
    1. 如要驗證 Block Store 雲端備份是否成功,您可以採取下列做法:
      1. 備份完成後,請搜尋標有「CloudSyncBpTkSvc」標記的記錄行。
      2. 您應該會看到類似以下的行:「“......, CloudSyncBpTkSvc: sync result: SUCCESS, ..., 上載 size: XXX bytes ...」
    2. 「Block Store」雲端備份服務經過 5 分鐘的「等待期」,5 分鐘內,按一下「立即備份」按鈕不會觸發其他 Block Store 雲端備份。
  4. 將目標裝置恢復原廠設定,並完成雲端還原流程。選擇在還原流程中還原測試應用程式。如要進一步瞭解雲端還原流程,請參閱支援的雲端還原流程
  5. 在目標裝置上,使用測試應用程式叫用 Blockstore API 來擷取資料。
  6. 確認擷取的位元組與來源裝置中儲存的位元組相同。

裝置需求

端對端加密

  • 搭載 Android 9 (API 29) 以上版本的裝置支援端對端加密。
  • 您的裝置必須設定螢幕鎖定方式、PIN 碼、解鎖圖案或密碼,才能啟用端對端加密功能,並妥善加密使用者的資料。

裝置對裝置還原流程

如要使用裝置進行裝置還原,您必須設定來源裝置和目標裝置。這兩部裝置正在傳輸資料。

Source 裝置必須搭載 Android 6 (API 23) 以上版本才能備份。

指定搭載 Android 9 (API 29) 以上版本的裝置,以便進行還原。

如要進一步瞭解裝置對裝置還原流程的詳細資訊,請參閱這篇文章

雲端備份與還原流程

備份與還原作業需要來源裝置和目標裝置。

Source 裝置必須搭載 Android 6 (API 23) 以上版本才能備份。

指定裝置 (依其廠商而定)。Pixel 裝置可以從 Android 9 (API 29) 使用這項功能,所有其他裝置都必須搭載 Android 12 (API 31) 以上版本。