【问题标题】:Correct way to set Bearer token with CURL使用 CURL 设置 Bearer 令牌的正确方法
【发布时间】:2015-08-06 05:00:48
【问题描述】:

我从 API 端点获取我的不记名令牌并设置以下内容:

$authorization = "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

接下来我想使用 CURL 访问安全端点,但是我不确定如何或在何处设置 Bearer 令牌。

我试过了,但还是不行:

 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result);

编辑:

根据文档,我应该这样使用不记名令牌:https://apigility.org/documentation/auth/authentication-oauth2

GET /oauth/resource HTTP/1.1
Accept: application/json
Authorization: Bearer 907c762e069589c2cd2a229cdae7b8778caa9f07

【问题讨论】:

  • 这是 PHP 吗?服务器如何期望这个令牌被发送?标题?
  • 嗨 - 是的,这是 PHP,通常将不记名令牌设置为标头。
  • 标题的名称是什么?
  • 我从文档中添加了一个编辑。

标签: php http curl oauth-2.0


【解决方案1】:
<?php
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "your api goes here",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer eyJ0eciOiJSUzI1NiJ9.eyJMiIsInNjb3BlcyI6W119.K3lW1STQhMdxfAxn00E4WWFA3uN3iIA"
  ),
 ));

$response = curl_exec($curl);
$data = json_decode($response, true);

echo $data;

?>

【讨论】:

    【解决方案2】:

    从 PHP 7.3 开始:

    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BEARER);
    curl_setopt($ch,CURLOPT_XOAUTH2_BEARER,$bearerToken);
    

    【讨论】:

      【解决方案3】:

      Guzzle 示例:

      use GuzzleHttp\Client;
      use GuzzleHttp\RequestOptions;
      
      $token = 'your_token';
      
      $httpClient = new Client();
      
      $response = $httpClient->get(
          'https://httpbin.org/bearer',
          [
              RequestOptions::HEADERS => [
                  'Accept' => 'application/json',
                  'Authorization' => 'Bearer ' . $token,
              ]
          ]
      );
      
      print_r($response->getBody()->getContents());
      

      https://github.com/andriichuk/php-curl-cookbook#bearer-auth

      【讨论】:

        【解决方案4】:

        这是一个可以发送或检索数据的 cURL 函数。它应该适用于任何支持 OAuth 的 PHP 应用程序:

            function jwt_request($token, $post) {
        
               header('Content-Type: application/json'); // Specify the type of data
               $ch = curl_init('https://APPURL.com/api/json.php'); // Initialise cURL
               $post = json_encode($post); // Encode the data array into a JSON string
               $authorization = "Authorization: Bearer ".$token; // Prepare the authorisation token
               curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization )); // Inject the token into the header
               curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
               curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POST
               curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // Set the posted fields
               curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
               $result = curl_exec($ch); // Execute the cURL statement
               curl_close($ch); // Close the cURL connection
               return json_decode($result); // Return the received data
        
            }
        

        在单向或双向请求中使用它:

        $token = "080042cad6356ad5dc0a720c18b53b8e53d4c274"; // Get your token from a cookie or database
        $post = array('some_trigger'=>'...','some_values'=>'...'); // Array of data with a trigger
        $request = jwt_request($token,$post); // Send or retrieve data
        

        【讨论】:

        • 有人投了反对票,请您在下面的 cmets 中详细说明。
        • 感谢 Serge... 为这样的电话苦苦挣扎了太久。 ALL 文档说“使用 http_build_query () 构建 POST 数组”。但是这不起作用 - 我不知道这是否是 OAuth 特性,但您需要的是 json_encode,如您在此处显示的那样。发送虚拟啤酒。
        • @anoldermark 很高兴能提供帮助。非常感谢您的赞许,确实有所作为。写出高质量的答案需要时间和精力,点赞和积极的 cmets 令人鼓舞……写得更多,写得好;)
        • @SergeDirect,我们将如何在文件APPURL.com/api/json.php 中获取帖子值以及jwt authitication 的工作原理。请举个例子。
        【解决方案5】:

        这应该可行

        $token = "YOUR_BEARER_AUTH_TOKEN";
        //setup the request, you can also use CURLOPT_URL
        $ch = curl_init('API_URL');
        
        // Returns the data/output as a string instead of raw data
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        //Set your auth headers
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
           'Content-Type: application/json',
           'Authorization: Bearer ' . $token
           ));
        
        // get stringified data/output. See CURLOPT_RETURNTRANSFER
        $data = curl_exec($ch);
        
        // get info about the request
        $info = curl_getinfo($ch);
        // close curl resource to free up system resources
        curl_close($ch);
        

        【讨论】:

          【解决方案6】:

          如果您使用的是私有令牌(像 Gitlab API),您应该替换:

          $authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

          与:

          $authorization = "PRIVATE-TOKEN 080042cad6356ad5dc0a720c18b53b8e53d4c274";

          【讨论】:

            【解决方案7】:

            替换:

            $authorization = "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"
            

            与:

            $authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274";
            

            使其成为有效且有效的授权标头。

            【讨论】:

            • 嗨 - 这是我尝试过的,但是同样的问题。我怀疑这个问题可能与 Apigility 更新有关,因为我也无法让它在邮递员上工作。
            • 通过将 ApiGility 回滚到以前的稳定版本来解决此问题。感谢您的意见,虽然不是我的解决方案,但它是其他有类似问题的解决方案,它确实让我走上了正确的轨道。感谢您的意见!
            猜你喜欢
            • 2019-02-16
            • 2019-02-18
            • 2021-04-17
            • 2021-07-28
            • 2017-06-25
            • 2016-12-30
            • 1970-01-01
            • 1970-01-01
            • 2018-12-16
            相关资源
            最近更新 更多