【发布时间】:2019-03-08 15:24:44
【问题描述】:
在我的 Node/Express 应用程序中运行 Google OAuth2 流程时,我已经被困了好几个小时。基础相当简单:
- 创建 Google 应用程序凭据
- 将用户重定向到同意屏幕
- 接收
code值 - 将
code交换为access_token和refresh_token - 为未来存储
refresh_token
无论出于何种原因,我无法通过上面的第 4 步,并且总是得到以下响应:
{
"error": "invalid_grant",
"description": "Bad Request"
}
有很多其他解决方案询问上述问题,但还没有解决方案对我有用:
- 无论结果如何,都不要使用相同的
code - 添加新的授权重定向 URI 后稍等片刻
- 包含 http://localhost:3000 作为授权重定向 URI
- 包括所有带/不带协议、端口、尾部斜杠的变体
- 如果需要(确实如此),请提前将
access_type设置为离线 - 使用 Request 代替 Axios
- 包括一个空的
scope参数,例如 OAuth Playground - 使用查询字符串编码参数
- 确认
application/x-www-urlencoded是 Content-Type - 重试时退出所有 Google 帐户
- 注意 Google 的令牌创建限制
综上所述,以下是我的困境的具体情况:
回调 #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'
}
}
授权重定向 URIs:在应用程序 > 凭据 > OAuth 2.0 客户端 ID 中可见
总而言之,我被困住了。我的设置/方法存在根本性错误,或者我是第一个遇到此错误的开发人员(后者不可能是真的)。也可以支付帮助。
【问题讨论】: