How to get refreshToken when using GoogleAuthUtil

梦想与她 提交于 2019-12-04 04:37:12

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.

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/

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)

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!