如何使用curl直接获取Google OAuth 2.0 Access令牌? (不使用谷歌库)

问题描述 投票:16回答:1

我正在尝试按照this教程使用他们的OAuth 2.0 API对Google进行身份验证。但是,我想直接进行curl调用,而不是使用他们的库。

我已获得客户端ID和客户端密钥。现在我正在尝试获取这样的访问令牌:

curl \
--request POST \
--header "Content-Type: application/json" \
--data '{
  "client_id":"MY_CLIENT_ID",
  "client_secret":"MY_SECRET_KEY",
  "redirect_uri": "http://localhost/etc",
  "grant_type":"authorization_code"
}' \
"https://accounts.google.com/o/oauth2/token"

但是,它不起作用。它给了我以下错误:

{
  "error" : "invalid_request",
  "error_description" : "Required parameter is missing: grant_type"
}

有人可以请我提供样本卷曲调用以获取访问令牌(和刷新令牌)吗?

curl oauth-2.0 google-api google-oauth2
1个回答
15
投票

a)您提供的数据应采用表单编码,而不是作为JSON对象呈现; b)您还应在“code”参数中提供授权代码值。例如。:

curl -d "client_id=MY_CLIENT_ID&\
  client_secret=MY_SECRET_KEY&\
  redirect_uri=http://localhost/etc&\
  grant_type=authorization_code&\
  code=CODE" https://oauth2.googleapis.com/token
© www.soinside.com 2019 - 2024. All rights reserved.