如何使用curl命令获取Google oAuth2.0访问令牌?

时间:2019-03-26 17:32:27

标签: android curl oauth-2.0 google-drive-api google-oauth

我正在尝试Google的REST API。在这里,我试图从cURL命令生成访问令牌,以在进一步的REST请求中使用该令牌。 但是我遇到了以下错误。

我试图通过下面的cURL命令获取访问令牌tru,但是我得到了以下错误响应。

curl \
--request POST \
--data "code=4/GQEg70zaxHAuRhhd6A1RB_6LIxwwBV8ak5xRP-nZIBTjuvt4g3fTWyU&client_id=954040553015-bphgid2596t65i91827omteq778cp7gj.apps.googleusercontent.com&client_secret=Sn3giYFFPMCNteKC--938xsP&redirect_uri=urn:ietf:wg:oauth:2.0:oob&grant_type=authorization_code" \
https://accounts.google.com/o/oauth2/token

响应:

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

然后我按如下所示编辑了命令,但是它失败了。

curl -d client_id=954040553015-bphgid2596t65i91827omteq778cp7gj.apps.googleusercontent.com -d client_secret=Sn3giYFFPMCNteKC--938xsP -d grant_type=authorization_code -d redirect_uri=urn:ietf:wg:oauth:2.0:oob -d code=4/GQEg70zaxHAuRhhd6A1RB_6LIxwwBV8ak5xRP-nZIBTjuvt4g3fTWyU https://oauth2.googleapis.com/token

响应:

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

因此,基于此链接https://gist.github.com/LindaLawton/cff75182aac5fa42930a09f58b63a309#file-googleauthenticationcurl-sh,我更改了grant_type = client_credentials。但是我又得到了错误响应。

{
"error": "unsupported_grant_type",
"error_description": "Invalid grant_type: client_credentials"
}

所以,请帮助我解决错误。

2 个答案:

答案 0 :(得分:1)

所以答案就在这个问题上。 "Invalid grant_type: client_credentials",而授予类型应为authorization_code

我对您的建议是前往OAuth运动场,将其发送的内容与发送的内容进行比较。这是操场上的粘贴...

POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-length: 277
content-type: application/x-www-form-urlencoded
user-agent: google-oauth-playground
code=4%2FGgFtOcUM73dTMJNpE7XR7w082MrYH-LCm7zMylg31ESKrwmpyQXnzOM
 &redirect_uri=https%3A%2F%2Fdevelopers.google.com%2Foauthplayground
 &client_id=407408718192.apps.googleusercontent.com
 &client_secret=************
 &scope=
 &grant_type=authorization_code

答案 1 :(得分:0)

不要使用save

也不要使用urn:ietf:wg:oauth:2.0:oob

但使用https://developers.google.com/oauthplayground ...

或任何Web服务器,它将回发重写为本地主机名。

除非处理回发操作,否则cURL请求本身是没有用的。

这个问题甚至都没有透露它是在线的还是在NAT后面的。

对于服务器到服务器的oAuth2流,您需要一个在线主机和一个服务帐户的凭据。

相关问题