授權存取 Google 使用者資料

驗證是確認使用者身分的程序,通常稱為使用者註冊或登入。授權是授予或拒絕存取資料或資源的程序。舉例來說,您的應用程式會要求使用者同意存取 Google 雲端硬碟。

驗證和授權呼叫應根據應用程式需求,分成兩個不同的流程。

如果應用程式的功能可使用 Google API 資料,但並非應用程式核心功能的一部分,您應設計應用程式,以便順利處理無法存取 API 資料的情況。舉例來說,如果使用者尚未授予雲端硬碟存取權,您可能會隱藏最近儲存的檔案清單。

只有在使用者執行需要存取特定 Google API 的動作時,您才應要求存取所需範圍。舉例來說,每當使用者輕觸「儲存到雲端硬碟」按鈕時,您就應要求存取使用者雲端硬碟的權限。

將授權與驗證分開,可避免新使用者感到困惑,或不明白為何系統要求他們提供特定權限。

建議使用 Credential Manager API 進行驗證。 如要授權需要存取 Google 儲存使用者資料的動作,建議使用 AuthorizationClient

設定專案

  1. 中開啟專案,或建立專案 (如果尚未建立)。
  2. 在「」中,確認所有資訊完整且正確。
    1. 請確認應用程式已指派正確的應用程式名稱、應用程式標誌和應用程式首頁。系統會在註冊時的「使用 Google 帳戶登入」同意畫面,以及「第三方應用程式和服務」畫面中,向使用者顯示這些值。
    2. 請確認您已指定應用程式隱私權政策和服務條款的網址。
  3. 中,為應用程式建立 Android 用戶端 ID (如果還沒有的話)。您需要指定應用程式的套件名稱和 SHA-1 簽章。
    1. 前往
    2. 按一下「建立用戶端」
    3. 選取「Android」Android應用程式類型。
  4. 中,建立新的「網頁應用程式」用戶端 ID (如果尚未建立)。目前可以忽略「已授權的 JavaScript 來源」和「已授權的重新導向 URI」欄位。後端伺服器與 Google 驗證服務通訊時,會使用這個用戶端 ID 識別自己。
    1. 前往
    2. 按一下「建立用戶端」
    3. 選取「網頁應用程式」類型。

宣告依附元件

在模組的 build.gradle 檔案中,使用最新版本的 Google Identity Services 程式庫宣告依附元件。

dependencies {
  // ... other dependencies

  implementation "com.google.android.gms:play-services-auth:<latest version>"
}

要求使用者動作所需的權限

每當使用者執行需要額外範圍的動作時,請呼叫 AuthorizationClient.authorize()

舉例來說,如果使用者執行的動作需要存取雲端硬碟應用程式儲存空間,請按照下列步驟操作:

List<Scopes> requestedScopes = Arrays.asList(DriveScopes.DRIVE_APPDATA);
AuthorizationRequest authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(requestedScopes).build();
Identity.getAuthorizationClient(this)
        .authorize(authorizationRequest)
        .addOnSuccessListener(
            authorizationResult -> {
              if (authorizationResult.hasResolution()) {
                    // Access needs to be granted by the user
                PendingIntent pendingIntent = authorizationResult.getPendingIntent();
                try {
startIntentSenderForResult(pendingIntent.getIntentSender(),
REQUEST_AUTHORIZE, null, 0, 0, 0, null);
                } catch (IntentSender.SendIntentException e) {
                Log.e(TAG, "Couldn't start Authorization UI: " + e.getLocalizedMessage());
                }
              } else {
            // Access already granted, continue with user action
                saveToDriveAppFolder(authorizationResult);
              }
            })
        .addOnFailureListener(e -> Log.e(TAG, "Failed to authorize", e));

在活動的 onActivityResult 回呼中,您可以檢查是否已成功取得必要權限,如果已取得,則執行使用者動作。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == MainActivity.REQUEST_AUTHORIZE) {
    AuthorizationResult authorizationResult = Identity.getAuthorizationClient(this).getAuthorizationResultFromIntent(data);
    saveToDriveAppFolder(authorizationResult);
  }
}

如果您要從伺服器端存取 Google API,可以呼叫 AuthorizationResult 的 getServerAuthCode() 方法取得驗證碼,然後將驗證碼傳送至後端,以交換存取和更新權杖。