Google OAuth2 集成 - redirect_uri 的参数值无效:缺少方案

时间:2020-12-24 19:54:50

标签: oauth-2.0 google-oauth

即使我在 Stackoverflow 上阅读了大量重复的问题,我仍然无法弄清楚我做错了什么。

问题:我成功收到了来自的授权代码,但是当我使用此代码请求访问令牌时,出现以下错误:

{
  "error": "invalid_request",
  "error_description": "Invalid parameter value for redirect_uri: Missing scheme: http%3A%2F%2Flocalhost%3A3030%2Fgoogle%2Foauth2%2Fcallback"
}

配置:

  • 我使用 http://localhost:3030/google/oauth2/callback 作为回调 URL

  • 在谷歌开发者控制台中设置:enter image description here

  • 这是我为了获取令牌而发送的“原始卷曲”请求:

    curl --location --request POST 'https://oauth2.googleapis.com/token' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data-urlencode 'code=4%2F0AY0e-g6zyewnsWjPEXoxZWawsp1E634ZlefYoBeYO1nXxBwjPQNCGVf7SGb4MxfNcjUApw' \
    --data-urlencode 'redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fgoogle%2Foauth2%2Fcallback' \
    --data-urlencode 'client_id=....' \
    --data-urlencode 'client_secret=....' \
    --data-urlencode 'grant_type=authorization_code'
    

    附言正如您所看到的,我“UrlEncoded”redirect_urlcode 因为它确实包含斜杠。为了站在同一边,我也尝试对 client_idclient_secretgrant_type 进行编码,但由于它们只包含 ASCII 字符,因此它们的结果相同。

我做了什么:

  • 研究了 SO 上的类似问题:jenkins issueios issuephp issuemissing http issuenodejs issue - similar to this one 跟进 discussionthisthat 以及此处出现的所有其他内容 - 为简洁起见将省略它们。

  • 我已经尝试设置

    • http://localhost/google/oauth2/callback:3030 以及
    • http://127.0.0.1:3030/google/oauth2/callback
    • http://127.0.0.1/google/oauth2/callback:3000(虽然最后指定端口非常奇怪并且将 localhost 更改为 127.0.0.1,但在类似线程之一中被建议),这些都不起作用。
  • 阅读所有文档 from google

  • 在 OAuth2 Playground 上玩过(很明显),但对我不起作用

  • 针对 body + 不同内容类型尝试了多种变体,同样的问题,但有时我也会遇到

    {
      "error": "invalid_grant",
      "error_description": "Bad Request"
    }
    

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

一段时间后,我能够成功获得令牌。事实证明,我没有正确地向 Google API 发出请求。此外,对于“curl”请求,它应该是 --data 而不是 --data-urlencode。以下请求对我有用:

curl --request POST \
  --url https://oauth2.googleapis.com/token \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data code=4%2F0AY0e-g4TLGE7c7VyMe8-95baQzeh0uERiKuGnHG5Sqccb4MCsmJOzV_a2jSbI9bm62VZ6Q \
  --data redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fgoogle%2Foauth2%2Fcallback \
  --data client_id=********* \
  --data client_secret=********* \
  --data grant_type=authorization_code

curl --request POST \
  --url https://oauth2.googleapis.com/token \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data 'code=4%2F0AY0e-g4TLGE7c7VyMe8-95baQzeh0uERiKuGnHG5Sqccb4MCsmJOzV_a2jSbI9bm62VZ6Q&redirect_uri=http%3A%2F%2Flocalhost%3A3030%2Fgoogle%2Foauth2%2Fcallback&client_id=*********&client_secret=*********&grant_type=authorization_code'

再观察:测试时,授权码只能使用一次(出于安全原因)。有时,即使您使用相同的代码发送多个“不成功的请求”,Google 的 API 也会拒绝所有带有该代码的后续请求(您需要再次通过 OAuth2 流程以获取新的请求)。让我感到困惑的最“令人沮丧”的部分是错误代码的响应如下所示:

{
  "error": "invalid_grant",
  "error_description": "Bad Request"
}

而不是诸如“代码无效”或“代码已过期”之类的内容。

因此,如果您遇到上述错误,则表示请求已正确制作,但代码有误。