身份验证可识别某人,通常称为用户注册或登录。授权是授予或拒绝数据或资源的访问权限的过程。例如,您的应用请求用户同意访问用户的 Google 云端硬盘。
根据网站或应用的需求,身份验证和授权调用应该是两个不同且独立的流程。
如果您的应用具有可以使用 Google API 数据的功能,但应用核心功能并非必需功能,您应将应用设计为能够妥善处理 API 数据无法访问的情况。例如,如果用户未授予云端硬盘访问权限,您可以隐藏最近保存的文件的列表。
只有在用户执行需要访问特定 API 的操作时,您才能请求访问 Google API 所需的范围。例如,只要用户点按“保存到云端硬盘”按钮,您就应该请求访问用户的云端硬盘的权限。
通过将授权与身份验证分离,您可以避免让新用户感到应接不暇,或者让用户不清楚为什么需要他们授予某些权限。
在 Google 身份服务中,身份验证是使用 SignInClient 完成的。如需向需要访问 Google 存储的用户数据的操作授权,我们建议使用 AuthorizationClient。
请求用户操作所需的权限
每当用户执行需要额外范围的操作时,都调用 AuthorizationClient.authorize()
。
例如,如果用户执行的操作需要访问其云端硬盘应用存储空间,请执行以下操作:
List<Scopes> requestedScopes = Arrays.asList(DriveScopes.DRIVE_APPDATA);
AuthorizationRequest authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(requestedScopes).build();
Identity.getAuthorizationClient(this)
.authorize(builder.build())
.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));
在 activity 的 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);
}
}