我已经费了好几个小时才能将Google OAuth2流程输入到我的Node / Express应用程序中。基本知识很简单:
code
值code
和access_token
交换为refresh_token
refresh_token
以备将来使用无论出于何种原因,我都无法通过上面的第4步,总是得到以下响应:
{
"error": "invalid_grant",
"description": "Bad Request"
}
关于上述问题,还有很多其他解决方案,但还没有一种解决方案对我有效:
code
access_type
设置为 offline (确实如此)scope
参数,例如OAuth Playground application/x-www-urlencoded
是内容类型根据上述情况,这是我的困境的具体情况:
回调#1 :http://localhost:3000/auth/google/callback(发送code
并运行下面的交换操作)
回调#2 :http://localhost:3000/auth/google/callbacktwo(其中应返回access_token
和refresh_token
)
交换操作:针对请求模块进行了调整
{
method: 'POST',
uri: 'https://www.googleapis.com/oauth2/v4/token',
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
body: {
'code': req.query.code,
'redirect_uri': 'http://localhost:3000/auth/google/callbacktwo',
'client_id': '***.apps.googleusercontent.com',
'client_secret': '***',
'scope': null,
'grant_type': 'authorization_code'
}
}
授权的重定向URI :在应用程序>凭据> OAuth 2.0客户端ID中可见
总而言之,我被困住了。我的设置/方法根本上有问题,或者我是第一个遇到此错误的开发人员(后者不能成立)。也可以支付协助费用。
答案 0 :(得分:0)
在令人震惊的事件中,我解决了此问题,发布时间超过了以下内容:
更改#1
在我的“授权重定向URI”列表中添加了“ http://127.0.0.1”变体
由于'127.0.0.1'等同于'localhost',以为我会尝试一下。在其他地方阅读。
更改#2
将Exchange操作的
redirect_uri
更改为回调#1,即发送code
的位置。
我想“如果Google不喜欢redirect URI
而不是它发送code
的地方会怎样?”
更改#3
删除了Exchange操作的
scope
参数
尽管在OAuth Playground中清晰可见,但在文档中却没有。
结果如何?收到了我一直寻找了几个小时的物体:
{
"access_token": "****",
"expires_in": 3600,
"refresh_token": "***",
"scope": "https://www.googleapis.com/auth/userinfo.profile",
"token_type": "Bearer",
"id_token": "*****"
}
免责声明:这并不意味着以上内容对您有用,但对我有用,我会接受。