PHP CURL请求内容类型的oauth2密码授予类型:application / x-www-form-urlencoded

时间:2017-03-01 15:27:57

标签: types oauth-2.0 request passwords grant

尝试使用需要Content-Type的API:application / x-www-form-urlencoded来发出令牌。以下curl命令有效

curl -i \
  -X POST \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -u SwVl97HRUgWHutJGzO1wt1JMjI5JVV62:SgnyQAA8ap0pPcFf \
  -d 'grant_type=password&username=user&password=pass' \
  https://api.test.com/identity/v1-sandbox/token

但在用PHP发布请求时,即

$params = array(
  "client_id" => "SwVl97HRUgWHutJGzO1wt1JMjI5JVV62",
  "client_secret" => "SgnyQAA8ap0pPcFf",
  "username" => "user",
  "password" => "pass",
  "grant_type" => "password");

$curl = curl_init($endpoint);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER,'Content-Type: application/x-www-form-urlencoded');
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, urlencode('user').':'.urlencode('pass'));

// Remove comment if you have a setup that causes ssl validation to fail
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$postData = "";

//This is needed to properly form post the credentials object
foreach($params as $k => $v)
{
   $postData .= $k . '='.urlencode($v).'&';
}

$postData = rtrim($postData, '&');

curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
echo "Performing Request...";

$json_response = curl_exec($curl);
//print_r($json_response);

print_r(curl_getinfo($curl));

API拒绝我的凭据。即。

 {
                    "code":"401.01.001",
                    "error":"unauthorized",
                    "message":"Unauthorized - Please check your credentials."
 }

当我检查卷曲请求标题时,我发现内容类型已更改为application / json但我已请求它使用application / x-www-form-urlencoded即。

[url] => https://api.test.com/identity/v1-sandbox/token
[content_type] => application/json
[http_code] => 401
[header_size] => 166
[request_size] => 314

有没有人遇到过上述问题?

1 个答案:

答案 0 :(得分:0)

要设置标题,您必须使用:CURLOPT_HTTPHEADER

示例:

curl_setopt($curl, CURLOPT_HTTPHEADER,'Content-Type: application/x-www-form-urlencoded');