Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get refreshToken when using GoogleAuthUtil

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.

like image 261
Wesley Avatar asked Nov 17 '14 09:11

Wesley


2 Answers

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.

like image 63
mbonnin Avatar answered Oct 24 '22 06:10

mbonnin


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/

like image 28
Michael S. Avatar answered Oct 24 '22 05:10

Michael S.