Authentication establishes who someone is, and is commonly referred to as user sign-up or sign-in. Authorization is the process of granting or rejecting access to data or resources. For example, your app requests your user's consent to access the user's Google Drive.
Authentication and authorization calls should be two separate and distinct flows based on the needs of the site or app.
If your app has features that can make use of Google API data, but are not required as part of your app's core features, you should design your app to be able to gracefully handle cases when API data isn't accessible. For example, you might hide a list of recently saved files when the user hasn't granted Drive access.
You should request access to scopes that you need to access Google APIs only when the user performs an action that requires access to a particular API. For example, you should request permission to access the user's Drive whenever the user taps a "Save to Drive" button.
By separating authorization from authentication, you can avoid overwhelming new users, or confusing users as to why they are being asked for certain permissions.
In Google identity Services, authentication is done using the SignInClient. For authorizing actions that need access to user data stored by Google, we recommend using AuthorizationClient.
Requesting permissions required by user actions
Whenever a user performs an action that requires additional scope, call
AuthorizationClient.authorize()
.
For example, if a user performs an action that requires access to their Drive app storage, do the following:
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));
In your activity's onActivityResult
callback, you can check if the required
permissions were successfully acquired, and if so, carry out the user action.
@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);
}
}