授權在 Android 裝置上存取使用者資料

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

驗證和授權呼叫應根據網站或應用程式的需求,採用兩個獨立且不同的流程。

如果應用程式的功能可以使用 Google API 資料,但應用程式的核心功能不需要使用這些資料,則您應該設計應用程式,以便在無法存取 API 資料時妥善處理情況。例如,如果使用者未授予雲端硬碟存取權,您可以隱藏最近儲存的檔案清單。

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

將授權與驗證區隔開來,可避免新使用者感到不堪負荷,或讓使用者感到混淆,從而瞭解他們要求特定權限的原因。

在 Google Identity 服務中,系統會使用 SignInClient 完成驗證。如要授權需要存取 Google 所儲存使用者資料的動作,建議您使用 AuthorizationClient

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

每當使用者執行需要額外範圍的動作時,請呼叫 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);
  }
}