简体   繁体   English

如何使用谷歌登录?

[英]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.我正在尝试在我的 Node.js 应用程序中不使用任何库的情况下实现 google oauth 2.0 登录。

I have created an app on the Google API console with the redirect url as http://localhost:3000 .我在 Google API 控制台上创建了一个应用程序,重定向 url 为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 .在登录期间,我的response_type是返回一次性使用code的代码,该代码需要与 token_endpoint 交换,如此所述。 The exchange is done on my node.js server with the following snippet.交换是在我的 node.js 服务器上使用以下代码段完成的。

 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.我尝试在raw内容中使用相同的有效负载进行 POSTMAN 查询,内容类型设置为application/json ,它给了我同样的错误。

You need to use params in place of your data while making your exchange call through axios, revised block will be like在通过 axios 进行交换调用时,您需要使用params代替您的data ,修改后的块就像

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. https://www.npmjs.com/package/azauth 5 分钟工作,超级简单。

NEVER include things like a clientSecret in GET parameters.切勿在 GET 参数中包含诸如 clientSecret 之类的内容。 This can lead to serious security issues !这可能会导致严重的安全问题!

The google doc is very clear about how to send the data ; google doc 非常清楚如何发送data

As a POST body - as always in OAuth2 : https://developers.google.com/identity/protocols/OAuth2WebServer - Step 5, REST code sample作为 POST 正文 - 在OAuth2中一如既往: https ://developers.google.com/identity/protocols/OAuth2WebServer - 第 5 步,REST 代码示例

They must be sent as a string but in the POST body / data :它们必须作为字符串发送,但在 POST 正文/ data中:

The string is the urlencoded parameters like该字符串是 urlencoded 参数,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM