問題描述
谷歌登錄使用新的 GoogleSignInOptions 獲取訪問令牌 (Google login get access token with new GoogleSignInOptions)
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");
但現在看來,在 handleSingInResult(GoogleSignInResult result)
我只能用 result.getSignInAccount().getIdToken() 得到一個
id token
;
有誰知道是否可以從這裡獲取訪問令牌(就像以前一樣),如果可以,怎麼辦?任何幫助表示讚賞。
參考解法
方法 1:
After signing in you'll be able to get the token:
final String token = GoogleAuthUtil.getToken(mAppContext, mAccountName, AUTH_TOKEN_TYPE);
dont forget to do it an Asynctask. for more detail have a look at here
EDIT:
Note that, despite the method name:
GoogleAuthUtil.getToken()
it does not give you an OAuth Token, it rather returns a "short‑lived authorization code" according to the documentation.
What I should do after getting the Authorization Code by calling the GoogleAuthUtil.getToken() ?
You should transmit the Authorization Code to your backend server over HTTPS. Only from your server you should attempt to receive Access and/or Refresh token, not in your app.
方法 2:
So i was having the same problem. they have changed it now so the token comes through in
GoogleSignInAccount acct = result.getSignInAccount();
Log.d(TAG, "handleSignInResult2: "+acct.getIdToken());
To get access too this token you have too ask for it in
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail().requestProfile().requestId().requestIdToken(getString(R.string.server_client_ID))
.build();
The R.string.server_client_ID
is the client ID
from the project that you make in your Google developer Console.
I hope this helps you.
here is also the documentation i followed. https://developers.google.com/identity/sign‑in/android/backend‑auth
(by Bootstrapper、abedfar、pjapple15)