保護 Firebase ML Android 應用程式和#39 的雲端憑證

如果您的 Android 應用程式使用 Firebase ML 的 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. 開啟 Cloud Shell 的「Credentials」(憑證) 頁面, 存取 Google Cloud 控制台系統出現提示時,請選取您的專案。

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

  3. 在「API 限制」部分,選取「限制金鑰」,然後將 列出您想讓 API 金鑰存取的所有 API。請確認 「不」包含 Cloud Vision API。

    設定 API 金鑰的 API 限制時,您將明確 宣告金鑰可存取的 API。根據預設,當 「限制」專區已選取「不限制金鑰」,您可以 ,用來存取已為專案啟用的任何 API。

現有的 API 金鑰將不會授予雲端機器學習服務的存取權, 您新增至其 API 限制的所有 API 仍可使用金鑰。 請參考閱讀清單,進一步瞭解 如何選擇 Kubeflow Pipelines SDK 或 TFX

請注意,如果您日後啟用其他 API,就必須將這些 API 新增到 適用 API 金鑰的「API 限制」清單。

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

最後,請建立新的 API 金鑰,僅適用於開發作業。Firebase ML 可以 在應用程式需要的環境中,使用這個 API 金鑰存取 Google Cloud 服務 進行驗證,例如在模擬器上執行時。

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

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

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

  2. 為了確保新的偵錯 API 金鑰不會與已發布的應用程式外洩, 在僅用於偵錯的 Android 資訊清單檔案中指定偵錯 API 金鑰 版本:

    1. 如果您還沒有偵錯資訊清單,請先按一下 檔案 >新增 >其他 >Android 資訊清單檔案並選取「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 功能時啟動應用程式。