问题
I'm using GoogleAuthUtil
in Google Play Services
on Android. After calling GoogleAuthUtil.getToken(context, userName, scope)
, I got a token like this:
ya29.wQBWztab5kcgMLcMbAI0LwFzHC_DPrxauSWbX4P6KOnBEOgjcm9V7OI9AFr6JGxDY54gP00RemzzgML56_gWRHn8Q5jK16BLY-0y83Gc5vfe3xN-QpyM4d7z
This is an access_token, which can be used in calling Google Apis. Then, how can I get a refresh token to refresh this access_token, because I also use Google oauth java library and YouTube Java Library in my Android project, I want to use these two libraries to maintain/manage the access_token
, refresh token
and expires_in
values. (When using Google oauth java library, the TokenResponse
it returned contains access_token
, refresh token
and expires_in
)
Thanks in advance.
回答1:
You cannot directly get a refreshToken using GoogleAuthUtil.getToken()
but if you call getToken()
each time you get a 401 error, GoogleAuthUtil will return you a new valid token if needed.
回答2:
In order to get a refresh token, make sure that your scope is in the following format:
Account account = new Account(mEmail, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
mScope="oauth2:server:client_id:"+ OAUTH_WEBCOMPONENT_ID+":api_scope:"+"https://www.googleapis.com/auth/userinfo.email";
return GoogleAuthUtil.getToken(mActivity, account, mScope);
This will give you an authorization code, which can be sent to your web component.
Your webcomponent than can use this authorization code only once to get an access token and refresh token with this code. You have to save the refresh token in your database, so that when the access code is no longer valid you can get a new access token when needed.
POST /oauth2/v3/token HTTP/1.1
Host: www.googleapis.com
Content-length: 233
content-type: application/x-www-form-urlencoded
user-agent: google-oauth-playground
code=4%2FVL2YMuPMheOP2-0vyKBSfGd-4er5GsMY17Ecp8ITK4U&redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground&client_id=407408718192.apps.googleusercontent.com&client_secret=************&scope=&grant_type=authorization_code
You can simulate how this works here:
https://developers.google.com/oauthplayground/
回答3:
Call requestServerAuthCode(String, true)
instead requestServerAuthCode(String)
which forces the request to include a refresh_token when it succeeds.
https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInOptions.Builder.html#requestServerAuthCode(java.lang.String, boolean)
val task = GoogleSignIn.getSignedInAccountFromIntent(data);
task.addOnSuccessListener {
val account = task.getResult(ApiException::class.java)
val authCode = account!!.serverAuthCode
// Send authcode to server to exchange access and refresh tokens.
exchangeAuthCodeForAccessToken(authCode)
}
来源:https://stackoverflow.com/questions/26969622/how-to-get-refreshtoken-when-using-googleauthutil