我正在尝试使用以下代码从谷歌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"
}
答案 0 :(得分:0)
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);