【问题标题】:How do I curl this post?我如何卷曲这篇文章?
【发布时间】:2015-09-27 18:45:37
【问题描述】:

我正在尝试使用下面的代码从 google api 获取访问令牌,

$grant = urlencode("urn:ietf:params:oauth:grant-type:jwt-bearer") . "&assertion=" . $jwtSign;
$postfields = array('Host' => 'www.googleapis.com', 'Content-Type' => 'application/x-www-form-urlencoded', 'POST' => '/oauth2/v3/token HTTP/1.1', 'grant_type' => $grant);

$headers = array(
    "Content-Type: application/x-www-form-urlencoded"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v3/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
$result = curl_exec($ch);

但我说错了。请帮我看看有什么问题

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

【问题讨论】:

  • 您将需要编写一些代码/努力自己编写代码。不幸的是,我们只提供代码帮助,而不是为您编写:)

标签: php curl google-api access-token


【解决方案1】:

grant_type 参数的值现在变成了urn:..:jwt-bearer 和断言的串联。它们应该在对令牌端点的调用中作为单独的参数提供。

您还混合设置标题字段和提供 POST 参数。

最后,为CURLOPT_POSTFIELDS 设置提供一个数组将使Content-Type 更改为multipart/form-data

相当使用:

    $postfields = array(
      'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      'assertion' => $jwtSign
    ); 

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.googleapis.com/oauth2/v3/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // On dev server only!
    $result = curl_exec($ch);

【讨论】:

  • 谢谢汉斯,但你的意思是像这样 $postfields = array('Host' => 'www.googleapis.com', 'Content-Type' => 'application/x-www-form- urlencoded', 'POST' => '/oauth2/v3/token HTTP/1.1', 'grant_type' => urlencode("urn:ietf:params:oauth:grant-type:jwt-bearer"),'assertion' = > $jwtSign);
  • 它现在正在工作,但出现错误“error_description”:“Invalid grant_type
  • “invalid grant_type”还是“invalid_grant”?
  • { “错误”: “INVALID_REQUEST”, “ERROR_DESCRIPTION”: “无效grant_type:瓮:IETF:PARAMS:OAuth的:授予型:JWT承载&安培;断言= eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiJodHRwczovL3d3dy5nb29nbGVhcGlzLmNvbS9vYXV0aDIvdjMvdG9rZW4iLCJzY29wZSI6Imh0dHBzOi8vc3ByZWFkc2hlZXRzLmdvb2dsZS5jb20vZmVlZHMiLCJpYXQiOjE0MzY0NDk1NDIsImV4cCI6MTQzNjQ1MzE0MiwiaXNzIjoiMTQ0MTk5ODUwNTcxLTkycGEycTA4cHZhbGszN21pNnJocWNlNTFhMTVxOW5iQGRldmVsb3Blci5nc2VydmljZWFjY291bnQuY29tIn0”。 }
  • 这意味着 curl 请求现在可以了;您发送的 JWT 断言的内容不是,但那是另一个问题/主题; fwiw:您应该遵循 developers.google.com/identity/protocols/… 中的指南
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 2021-02-06
  • 1970-01-01
  • 2020-06-18
相关资源
最近更新 更多