Skip to content
Advertisement

How to Login with Google?

I am trying to implement a google oauth 2.0 login without using any libraries in my Node.js application.

I have created an app on the Google API console with the redirect url as http://localhost:3000. During login my response_type is code which returns a one-time use code that needs to be exchanged with the token_endpoint as described here. The exchange is done on my node.js server with the following snippet.

axios({
    url: 'https://www.googleapis.com/oauth2/v4/token',
    method: 'post',
    data: {
      code: code,
      client_id: sso.clientId,
      client_secret: sso.clientSecret,
      redirect_uri: sso.redirect_uri,
      grant_type: 'authorization_code',
    }
  })
  .then((response) => {
    console.log(response.data);
  })
  .catch(function(err) {
    console.log(err.response.data);
  });
But this is is sending me back an error response of
{
  "error": "unsupported_grant_type",
  "error_description": "Invalid grant_type: "
}

instead of the user token.

Please help me identify the issue.

I tried doing a POSTMAN query as well with the same payload in the raw with content-type set to application/json, and it gave me the same error.

Advertisement

Answer

You need to use params in place of your data while making your exchange call through axios, revised block will be like

params: {
    code: code,
    client_id: sso.clientId,
    client_secret: sso.clientSecret,
    redirect_uri: sso.redirect_uri,
    grant_type: 'authorization_code',
}

Hope this helps!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement