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); });
{ "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.
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!
If you only need authentication I would use this, no registration needed. https://www.npmjs.com/package/azauth 5 min work , super simple.
NEVER include things like a clientSecret in GET parameters. This can lead to serious security issues !
The google doc is very clear about how to send the data
;
As a POST body - as always in OAuth2 : https://developers.google.com/identity/protocols/OAuth2WebServer - Step 5, REST code sample
They must be sent as a string but in the POST body / data
:
The string is the urlencoded parameters like
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https://yourOauth2redirectUrl.example.com/code&
grant_type=authorization_code
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.