【问题标题】:PHP CURL request to oauth2 password grant type for Content-Type: application/x-www-form-urlencoded内容类型的 oauth2 密码授予类型的 PHP CURL 请求:application/x-www-form-urlencoded
【发布时间】:2017-03-01 15:27:56
【问题描述】:

我正在尝试使用需要 Content-Type: application/x-www-form-urlencoded 来发布令牌的 API。以下 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."
 }

当我检查 curl 请求标头时,我发现内容类型已更改为 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

有人遇到过上述问题吗?

【问题讨论】:

  • 经过一些分析,我意识到第一个生成Authorization: Basic U3dWbDk3SFJVZ1dIdXRKR3pPMXd0MUpNakk1SlZWNjI6U2dueVFBQThhcDBwUGNGZg==,而第二个生成Authorization: Basic dXNlcjpwYXNz认为两者都使用base64编码......有想法的人请分享......跨度>
  • 没关系...正在使用 curl_setopt($curl, CURLOPT_USERPWD, urlencode('user').':'.urlencode('pass'));而不是 curl_setopt($curl, CURLOPT_USERPWD, urlencode('SwVl97HRUgWHutJGzO1wt1JMjI5JVV62').':'.urlencode('SgnyQAA8ap0pPcFf')); ....虚拟错误...猜我累了

标签: types oauth-2.0 request passwords grant


【解决方案1】:

要设置你必须使用的标题:CURLOPT_HTTPHEADER

示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    • 2018-04-04
    • 2022-11-21
    • 1970-01-01
    • 2018-08-05
    相关资源
    最近更新 更多