我的 Android 应用目前使用 GoogleAuthUtil 来登录用户并获取传递到后端的 access_token
(下面的代码 fragment 显示了创建 GoogleApiClient 并使用 GoogleAuthUtil 获取 token )。
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope("profile"))
.build();
...
...
String accessToken = GoogleAuthUtil.getToken(GoogleLoginActivity.this,
Plus.AccountApi.getAccountName(mGoogleApiClient),
"oauth2:profile email");
然后我将其发送到后端
我现在正尝试迁移到新的 Google SignIn - https://developers.google.com/identity/sign-in/android/sign-in
因此更改了 GoogleApiClient 的创建,例如,
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestIdToken("<web client id>")
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
然后做登录使用,
startActivityForResult(Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient), RC_GET_TOKEN);
和 Activity 结果使用(类似于上面链接中的示例),
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
handleSignInResult(opr.get());
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgress();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgress();
handleSignInResult(googleSignInResult);
}
});
}
但现在看来,在 handleSingInResult(GoogleSignInResult result)
中,我只能返回一个 id token
result.getSignInAccount().getIdToken();
有谁知道是否可以从中获取访问 token (像以前一样),如果可以,如何获取?任何帮助表示赞赏。
最佳答案
登录后您将能够获得 token :
final String token = GoogleAuthUtil.getToken(mAppContext, mAccountName, AUTH_TOKEN_TYPE);
不要忘记执行一个异步任务。有关更多详细信息,请查看 here
编辑:
请注意,尽管方法名称:
GoogleAuthUtil.getToken()
它不会为您提供 OAuth token ,而是根据 documentation 返回一个“短期授权代码” .
What I should do after getting the Authorization Code by calling the GoogleAuthUtil.getToken() ?
您应该通过 HTTPS 将授权码传输到您的后端服务器。您应该仅从您的服务器尝试接收访问和/或刷新 token ,而不是在您的应用中。
关于android - 谷歌登录使用新的 GoogleSignInOptions 获取访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844330/