如何请求带有授权标头的Http

时间:2019-11-18 05:09:51

标签: php laravel guzzle

我对Guzzle POST请求有疑问

这是我的代码

$req = $client->request('POST', $endpoint, [
      'headers' => [
          'Content-Type' => 'application/json',
          'Authorization' => 'Basic '.$this->api_credential
         ], $body);

其始终响应401 "Please include your API key as an Authorization header"

我必须对凭据进行base64编码吗?

及其使用的基本授权

4 个答案:

答案 0 :(得分:1)

根据您要尝试进行身份验证的API,您需要base64_encode个用于Basic身份验证的凭据(username:password)[其中username是您的API密钥并且password将为空白]:

对于Authorization标头:

'Authorization' => 'Basic '. base64_encode($this->api_credential .':'),

答案 1 :(得分:0)

使用Bearer代替基本授权。希望能解决这个问题

$req = $client->request('POST', $endpoint, [
      'headers' => [
          'Content-Type' => 'application/json',
          'Authorization' => 'Bearer '.$this->api_credential
         ], $body);

答案 2 :(得分:0)

请确保您的服务器接受授权标头。下面给出接受授权标头的.htaccess代码

RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

您可以使用以下curl请求检查服务器是否接受授权代码

$ch = curl_init();  
curl_setopt( $ch,CURLOPT_URL,'https://yourendpoint.com/apiFile.php'  );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Basic ' .$api_credential
));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);    
$returnData = json_decode($result, true);

答案 3 :(得分:0)

使用Bearer

$req = $client->request('POST', $endpoint, [
      'headers' => [
          'Accept' => 'application/json',
          'Authorization' => 'Bearer '.$this->api_credential
         ], $body);