保護 Firebase 機器學習 Android 應用程式及雲端憑證

如果 Android 應用程式使用 Firebase 機器學習的其中一個 Cloud API,則在正式環境中啟動應用程式之前,您應採取一些額外步驟,防止未經授權的 API 存取。

對於實際工作環境的應用程式,您必須確保只有通過驗證的用戶端可以存取雲端服務。(請注意,只有未取得 Root 權限的裝置可以使用上述方法進行驗證)。

接著,您將建立一個僅供偵錯的 API 金鑰,用於在測試和開發期間方便使用。

1. 透過 Firebase 註冊正式版應用程式

首先,請透過 Firebase 註冊正式版應用程式。

  1. 確認您已取得應用程式的 SHA-1 簽名。詳情請參閱驗證用戶端一文。

  2. 前往 Firebase 控制台的 「專案設定」,然後選取「設定」分頁標籤。

  3. 向下捲動至「你的應用程式」資訊卡,然後選取您的 Android 應用程式。

  4. 在應用程式資訊中加入 SHA-1 簽名。

2. 限制 API 金鑰的範圍

接下來,設定現有的 API 金鑰以禁止存取 Cloud Vision API:

  1. 開啟 Google Cloud 控制台的「Credentials」(憑證) 頁面。系統出現提示訊息時,請選取專案。

  2. 針對清單中的每個現有 API 金鑰,開啟編輯檢視畫面。

  3. 在「API 限制」區段中,選取「限制金鑰」,然後加入清單中,讓 API 金鑰能夠存取的所有 API。請務必「不」包含 Cloud Vision API。

    設定 API 金鑰的 API 限制時,您會明確宣告該金鑰有權存取的 API。根據預設,當「API 限制」區段選取「不要限制金鑰」時,該 API 金鑰可用於存取已啟用專案的任何 API。

現在,現有的 API 金鑰不會授予 Cloud ML 服務的存取權,但您加入「API 限制」清單內的任何 API 都能繼續使用每個金鑰。

請注意,如果日後啟用了任何其他 API,請務必將其新增至適用 API 金鑰的 API 限制清單。

3. 建立及使用僅限偵錯的 API 金鑰

最後,請新建一個僅供開發使用的 API 金鑰。Firebase ML 可利用此 API 金鑰,在無法進行應用程式驗證的環境中 (例如在模擬器上執行時) 存取 Google Cloud 服務。

  1. 建立用於開發的新 API 金鑰:

    1. 開啟 Google Cloud 控制台的「Credentials」(憑證) 頁面。系統出現提示訊息時,請選取專案。

    2. 按一下「Create credentials」(建立憑證) >「API key」(API 金鑰),然後記下新的 API 金鑰。這組金鑰允許未經驗證的應用程式存取 API,因此請將這組金鑰保密

  2. 為確保新的偵錯 API 金鑰不會外洩,請在僅適用於偵錯版本的 Android 資訊清單檔案中指定偵錯 API 金鑰:

    1. 如果您尚未建立偵錯資訊清單,請依序點選「File」>「New」>「Other」>「Android Manifest File」,然後從目標來源集中選取 debug

    2. 在偵錯資訊清單中,新增下列宣告:

      <application>
      <meta-data
          android:name="com.firebase.ml.cloud.ApiKeyForDebug"
          android:value="your-debug-api-key" />
      </application>
      
  3. 在應用程式中,將 Firebase ML 設定為使用憑證指紋比對功能,以在實際工作環境中驗證用戶端,以及僅在偵錯版本中使用 API 金鑰 (偵錯金鑰):

    Kotlin+KTX

    val optionsBuilder = FirebaseVisionCloudImageLabelerOptions.Builder()
    if (!BuildConfig.DEBUG) {
        // Requires physical, non-rooted device:
        optionsBuilder.enforceCertFingerprintMatch()
    }
    
    // Set other options. For example:
    optionsBuilder.setConfidenceThreshold(0.8f)
    // ...
    
    // And lastly:
    val options = optionsBuilder.build()
    FirebaseVision.getInstance().getCloudImageLabeler(options).processImage(myImage)

    Java

    FirebaseVisionCloudImageLabelerOptions.Builder optionsBuilder =
            new FirebaseVisionCloudImageLabelerOptions.Builder();
    if (!BuildConfig.DEBUG) {
        // Requires physical, non-rooted device:
        optionsBuilder.enforceCertFingerprintMatch();
    }
    
    // Set other options. For example:
    optionsBuilder.setConfidenceThreshold(0.8f);
    // ...
    
    // And lastly:
    FirebaseVisionCloudImageLabelerOptions options = optionsBuilder.build();
    FirebaseVision.getInstance().getCloudImageLabeler(options).processImage(myImage);

後續步驟

請參閱「發布檢查清單」,瞭解在應用程式使用其他 Firebase 功能時,如何做好準備。