不久前,为了使用谷歌联系人,我不得不将OAuth 2.0集成到一个项目中。我使用了这个库:
https://github.com/openid/AppAuth-Android
您还可以在这里看到一些重要的文档:
https://developers.google.com/identity/protocols/OAuth2
碎片java:
AuthorizationServiceConfiguration serviceConfiguration =
new AuthorizationServiceConfiguration(
Uri.parse(GoogleConstants.OAUTH_URL) /* auth endpoint */,
Uri.parse(GoogleConstants.TOKEN_URL) /* token endpoint */,
null
);
AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder(
serviceConfiguration,
getString(GoogleConstants.CLIENT_ID),
ResponseTypeValues.CODE,
Uri.parse(GoogleConstants.REDIRECT_URI))
.setScope(GoogleConstants.OAUTH_SCOPE);
AuthorizationRequest request = authRequestBuilder.build();
AuthorizationService authorizationService = new AuthorizationService(getActivity());
String action = GoogleConstants.APP_ACTION;
Intent postAuthorizationIntent = new Intent(getActivity(), ExampleActivity.class);
postAuthorizationIntent.setAction(action);
PendingIntent pendingIntent =
PendingIntent.getActivity(getActivity(), 0, postAuthorizationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
authorizationService.performAuthorizationRequest(request, pendingIntent);
活动java:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkIntentAction(intent);
}
...
private void checkIntentAction(@Nullable Intent intent) {
if (intent != null) {
String action = intent.getAction();
if (action != null) {
switch (action) {
case GoogleConstants.APP_ACTION:
if (!intent.hasExtra(USED_INTENT)) {
handleAuthorizationResponse(intent);
intent.putExtra(USED_INTENT, true);
}
break;
default:
// do nothing
}
}
}
}
...
private void handleAuthorizationResponse(final @NonNull Intent intent) {
final AuthorizationResponse response = AuthorizationResponse.fromIntent(intent);
if (response != null) {
final AuthorizationService service = new AuthorizationService(this);
service.performTokenRequest(response.createTokenExchangeRequest(),
new AuthorizationService.TokenResponseCallback() {
@Override
public void onTokenRequestCompleted(@Nullable TokenResponse tokenResponse,
@Nullable AuthorizationException exception) {
...
}
});
}
}