PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to Login with Google?

 October 14, 2022     axios, google-oauth, javascript, node.js, oauth-2.0     No comments   

Issue

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.


Solution

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!



Answered By - David R
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing