Creation of refresh token for Google APIs

Martin
Programming tricks
Published in
2 min readApr 23, 2024

With this article, you will learn how to generate a refresh token that will allow you to autonomously create tokens to use Google APIs without having to log in with your user every time.

Let’s get started!

First, go to the Google Developers Console and register your app. https://console.developers.google.com/apis/

Next, create credentials of type “Web application” where you will specify the valid redirect URL as https://developers.google.com/oauthplayground

Now, open the URL https://developers.google.com/oauthplayground in a browser. Open the settings on the right and set these options:

  • OAuth flow: Server-side
  • Access type: Offline
  • Use your own OAuth credentials: TICK
  • Enter the client ID and client secret generated when creating the credentials for the Web application
  • Find and select the API you want to use, then click the ‘Authorize APIs’ button and log in with your user.

Now, go to Step 2 and click on the ‘Exchange authorization code for tokens’ button. Save the generated refresh token.

Now, let’s see how to use the refresh token to generate a valid token for calling Google APIs. For this, we will use JavaScript code.

const refresh_token = "refresh_token_generated";
const client_id = "client_id";
const client_secret = "client_secret";
const refresh_url = "https://www.googleapis.com/oauth2/v4/token";

const post_body = `grant_type=refresh_token&client_id=${encodeURIComponent(client_id)}&client_secret=${encodeURIComponent(client_secret)}&refresh_token=${encodeURIComponent(refresh_token)}`;

let refresh_request = {
body: post_body,
method: "POST",
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
})
}

fetch(refresh_url, refresh_request).then( response => {
return(response.json());
}).then( response_json => {
console.log(response_json.access_token)

});

¡We’ve got it!

Now you have the access_token to call Google APIs automatically.

Remember, if you liked the article, you can buy me a coffee ;-)

https://ko-fi.com/arekjaar

--

--

Martin
Programming tricks

Experto en integración de aplicaciones con más de 5 años de experiencia con IBM WMB y IIB y en la creación de flujos para Mule ESB con Anypoint Studio