【问题标题】:Google OAuth: "invalid_grant" still a thingGoogle OAuth:“invalid_grant”仍然存在
【发布时间】:2019-03-08 15:24:44
【问题描述】:

在我的 Node/Express 应用程序中运行 Google OAuth2 流程时,我已经被困了好几个小时。基础相当简单:

  1. 创建 Google 应用程序凭据
  2. 将用户重定向到同意屏幕
  3. 接收code
  4. code 交换为access_tokenrefresh_token
  5. 为未来存储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 的令牌创建限制

综上所述,以下是我的困境的具体情况:

主持人http://localhost:3000

回调 #1http://localhost:3000/auth/google/callbackcode 被发送到并运行以下交换操作

回调 #2http://localhost:3000/auth/google/callbacktwoaccess_tokenrefresh_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 中可见

See screenshot


总而言之,我被困住了。我的设置/方法存在根本性错误,或者我是第一个遇到此错误的开发人员(后者不可能是真的)。也可以支付帮助。

【问题讨论】:

    标签: google-api google-oauth


    【解决方案1】:

    在一个令人震惊的事件中,我在上面发布的几分钟内解决了这个问题,并进行了以下更改:


    更改 #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": "*****"
    }
    

    免责声明:这并不意味着上述内容对你有用,但它对我有用,我会接受。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-26
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      相关资源
      最近更新 更多