在尝试从 Play Services 8.1 中的 Google+ 登录切换到 Play Services 8.3 中的新 Google 登录时,服务器端组件停止工作并开始在对 Google 服务器的每个 API 调用中抛出 401。
当 Android 应用使用 Google Play Services 8.1 时:
构建.gradle:
compile 'com.google.android.gms:play-services-plus:8.1.0'
安卓客户端:
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE)
.addScope(new Scope("email"))
.build();
String scopes = "oauth2:profile email";
accessToken = GoogleAuthUtil.getToken(
SignInActivity.this,
Plus.AccountApi.getAccountName(mGoogleApiClient),
scopes); // then send accessToken to the server
服务器端:
// get user details from Google+ REST API
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
Plus plusService = new Plus.Builder(new NetHttpTransport(), new JacksonFactory(), null)
.setApplicationName("AppName")
.setHttpRequestInitializer(credential)
.build();
Person person = plusService.people().get("me").execute();
切换到 Google Play 服务 8.3 时:
构建.gradle:
compile 'com.google.android.gms:play-services-auth:8.3.0'
安卓应用:
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestServerAuthCode("GOOGLE_CLIENT_ID", false)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
使用相同的服务器代码,get("me") 调用返回:
com.google.api.client.googleapis.json.GoogleJsonResponseException: 401 Unauthorized
{
"code" : 401,
"errors" : [ {
"domain" : "global",
"location" : "Authorization",
"locationType" : "header",
"message" : "Invalid Credentials",
"reason" : "authError"
} ],
"message" : "Invalid Credentials"
}