Search code examples
authenticationoauth-2.0google-oauthrefresh-token

Request to Get Google OAuth Access Token Failing


I'm trying to get a refresh token and use it to issue an access token, but the request to generate the access token isn't working.

I'm calling this API to get the refresh token:

URL: https://accounts.google.com/o/oauth2/v2/auth (GET)

    var params = {'client_id': '{MY_CLIENT_ID}',
                  'redirect_uri': '{MY_REDIRECT_URI}',
                  'response_type': 'code',
                  'scope': 'https://mail.google.com/',
                  'access_type': 'offline',
                  'prompt': 'consent'};

This request works properly and results in a token, but when I try to get the access token, the request fails with this error message:

{
    "error": "invalid_grant",
    "error_description": "Bad Request"
}

Here is my request to get the access token:
URL: https://accounts.google.com/o/oauth2/token (POST)

x-www-form-urlencoded BODY: grant_type="refresh_token", client_id={MY_CLIENT_ID}, client_secret={MY_CLIENT_SECRET}, refresh_token={THE TOKEN I JUST GOT}

Here's a screenshot of my request in Postman.


Solution

  • You need to change token URL

    https://oauth2.googleapis.com/token
    

    You can the new access token by curl with refresh_token

    curl -X POST https://oauth2.googleapis.com/token \
      --silent \
      -H "Content-Type: application/x-www-form-urlencoded" \
      -d client_id=[YOUR CLIENT_ID] \
      -d client_secret=[YOUR CLIENT_SECRET] \
      -d refresh_token=[YOUR REFRESH TOKEN] \
      -d grant_type=refresh_token
    

    Result by curl

    enter image description here

    Result by Postman

    enter image description here

    This code is how to get refresh_toke by node.js

    const express = require('express');
    const session = require('express-session');
    const { OAuth2Client } = require('google-auth-library'); // Corrected import statement
    const fs = require('fs');
    
    const CLIENT_SECRETS_FILE = "client_secret.json";
    const SCOPES = ['openid', 'https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'];
    const PORT = 3000; // Port number need to change by your configuration.
    
    let rawdata = fs.readFileSync(CLIENT_SECRETS_FILE);
    let clientSecrets = JSON.parse(rawdata);
    
    const app = express();
    
    app.use(session({
      secret: clientSecrets.web.client_secret,
      resave: false,
      saveUninitialized: true,
    }));
    
    const oAuth2Client = new OAuth2Client(
      clientSecrets.web.client_id,
      clientSecrets.web.client_secret,
      clientSecrets.web.redirect_uris[0] // This usually is the first URI in the array
    );
    
    app.get('/login', async (req, res) => {
      const authUrl = oAuth2Client.generateAuthUrl({
        access_type: 'offline',
        prompt: 'consent',
        scope: SCOPES,
      });
      res.redirect(authUrl);
    });
    
    app.get('/callback', async (req, res) => {
      const { code } = req.query;
      const { tokens } = await oAuth2Client.getToken(code);
      req.session.credentials = tokens;
      res.redirect('/token');
    });
    
    app.get('/token', (req, res) => {
      if (!req.session.credentials) {
        return res.redirect('/login');
      }
    
      oAuth2Client.setCredentials(req.session.credentials);
      res.json({
        token: req.session.credentials.access_token,
        refresh_token: req.session.credentials.refresh_token,
        token_uri: oAuth2Client.tokenUri,
        client_id: oAuth2Client._clientId,
        scopes: req.session.credentials.scope
      });
    });
    
    app.listen(3000, () => {
      console.log(`Server started on http://localhost:${PORT}`);
    });
    

    Access login by Browser

    http://localhost:3000/login
    

    enter image description here

    enter image description here

    enter image description here

    You can get the refresh_token

    enter image description here

    more detail explain in here

    It will be describe "how to save client_secret.json?"