How to get the Google Refresh Token step by step (OAuth 2.0)

Tiempo de lectura: 2 minutos

We will today learn how to get a refresh token from Google OAuth 2.0 in order to use services of Google Console.

Enredaderas fhachada - pexels

We will first get the authentication data using a Google token.

For this:

client_id and client_secret

You get them from the .

Enable APIs and Services
Google Play Android Developer API
Oath Credentials

NOTA: you can ask to create an informed consent screen, in this case we have to create it.

We are choosing external users. And we’re creating a test one (nothing happens since we’ll use it to validate ourselves).

If we create a web application.

Publish to Authorized Origins of JavaScript:

http://localhost:8000

And Redirecting:

http://localhost:8000/auth/callback

Add scopes

https://www.googleapis.com/auth/androidpublisher

We add the scope

You need to press SAVE below the page.

2. Getting refresh token

This is obtained once you complete the OAuth 2.0 authentication process with a user (usually yourself).

You can generate a URL like this to obtain an authorization code:

https://accounts.google.com/o/oauth2/v2/auth? scope=https://www.googleapis.com/auth/androidpublisher& access_type=offline& include_granted_scopes=true& state=xyz123& redirect_uri=http://localhost:8000/auth/callback& response_type=code& client_id=TU_CLIENT_ID

The code appears above in ?code=

Copy that URL into a browser, log in with your Google account, and it returns a code.

That code is the code you’ll use to get an authorization_code

Note: if there’s blocked access, give access.

For access for users go to Public > Test Users

Test Users in Google Auth

<

p’It will tell you that Google hasn’t verified this app, but we don’t care, and click continue.

We are continuing:

Ahora it will return the Permission code that you should save.

To get the access token we use this:

curl -X POST https://oauth2.googleapis.com/token \ -d "code=EL_CODE_QUE_COPIASTE" \ -d "client_id=TU_CLIENT_ID" \ -d "client_secret=TU_CLIENT_SECRET" \ -d "redirect_uri=http://localhost:8000/auth/callback" \ -d "grant_type=authorization_code"

*In code, you enter the code that was returned to you.

This call will only return a refresh token and an access token on the first occasion. The refresh token never expires, so you’ll need to store it in order to get new access tokens.

Ejemplo de respuesta que devuelve:

{ "access_token": "...", "expires_in": 3599, "refresh_token": "...", "scope": "https://www.googleapis.com/auth/androidpublisher", "token_type": "Bearer" } 

You can now get an access token every time you need it:

curl -X POST https://oauth2.googleapis.com/token \ -d "client_id=TU_CLIENT_ID" \ -d "client_secret=TU_CLIENT_SECRET" \ -d "refresh_token=2303432efg..." \ # ← The value given in the previous call -d "grant_type=refresh_token"

Leave a Comment