PHP创建授权标头

时间:2018-09-05 08:24:18

标签: php authentication

我正在尝试在PHP中创建一个Authorization标头,我尝试过的每一次尝试都导致请求错误,我不知道它是我的方法还是格式。

我从API获得的文档的标头必须采用以下格式:

POST https://api.URL.com/api/access/authtoken/ 
HEADERS { 
"Accept": "application/json", 
"Content-Type": "application/x-www-form-urlencoded"
, 
"Authorization": "Basic 8fqchs8hsafhjhc8392ch8evhdv 
dvf4239gy0wNVSDVHSDJVJWd209qfhznznc932fyzIHFEOIGH
CNFCaFWFh83hfwehvljv9fbueqgf89ahwaoihOHOIHBVjeh890
owev98ewgvw209fyqnf0fmf9fm0snfa098nfw0q09fmevm9eqZ
HF89FHWE==" 
} 
DATA: { 
"grant_type": "password", 
"username": "APIUSERNAME", 
"password": "password" 
}

我在PHP中的最新尝试是使用 stream_context_create file_get_contents

代码段采用以下格式。

$api_url = 'https://api.URL.com/api/access/authtoken/';

$AuthHeader = array(
  'http'=>array(
    'method'=>"POST",
    'HEADERS'=>"Accept: application/json" .
               "Content-Type: application/x-www-form-urlencoded".
               "Authorization: Basic " . base64_encode("$ClientID:$ClientSecret")),
   'content'=>array(
   'DATA'=>"grant_type:password".
           "username:USERNAME".
           "password:PASSWORD"  )  

);



$context = stream_context_create($AuthHeader);
$result = file_get_contents($api_url, false, $context);

是我创建标头的方式错误或格式错误。 API文档不是最好的,我得到的响应也没有表明它在哪里失败。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

对于HTTP stream context options,它是header,而不是HEADERS。它还接受数组,以简化多头规范。

内容似乎应为x-www-form-urlencoded,因此您需要使用http_build_query()对其进行编码

结合起来:

$api_url = 'https://api.URL.com/api/access/authtoken/';

$AuthHeader = array(
  'http' => array(
    'method' => "POST",
    'header' => array(
      "Accept: application/json",
      "Content-Type: application/x-www-form-urlencoded",
      "Authorization: Basic " . base64_encode("$ClientID:$ClientSecret")
    ),
    'content' => http_build_query(array(
      "grant_type" => "password",
      "username" => "USERNAME", // to be replaced with actual username value
      "password" => "PASSWORD" // ditto
    ))
  ) 
);

$context = stream_context_create($AuthHeader);
$result = file_get_contents($api_url, false, $context);