驗證功能可確認使用者身分,通常稱為使用者註冊或登入。授權是指授予或拒絕存取資料或資源的程序。舉例來說,您的應用程式會要求使用者同意存取其 Google 雲端硬碟。
驗證和授權呼叫應根據應用程式需求,採用兩個獨立且不同的流程。
如果應用程式具有可使用 Google API 資料的功能,但這並非應用程式核心功能的必要條件,則應設計可在無法存取 API 資料時妥善處理的應用程式。舉例來說,如果使用者未授予雲端硬碟存取權,您可以隱藏最近儲存的檔案清單。
只有在使用者執行需要存取特定 API 的動作時,您才應要求存取 Google API 所需的範圍。舉例來說,當使用者輕觸「儲存至雲端硬碟」按鈕時,您應要求存取使用者雲端硬碟的權限。
將授權與驗證分開,可避免新使用者感到不堪負荷,或對要求提供特定權限的原因感到困惑。
如要進行驗證,建議您使用 Credential Manager API。如要授權需要存取 Google 儲存的使用者資料,建議您使用 AuthorizationClient。
設定 專案
- 在 中開啟專案,或建立專案 (如果尚未建立)。
- 在 中,請確認所有資訊都完整且正確。
- 在 中,為應用程式建立 Android 用戶端 ID (如果尚未建立)。您需要指定應用程式的套件名稱和 SHA-1 簽名。
- 在 中,建立新的「網頁應用程式」用戶端 ID (如果尚未建立)。您可以先忽略「Authorized JavaScript Origins」和「Authorized redirect URIs」欄位。當後端伺服器與 Google 驗證服務通訊時,這個用戶端 ID 會用於識別後端伺服器。
宣告依附元件
在模組的 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() 方法,取得驗證碼,然後傳送至後端,以交換存取權和更新權杖。