[php] CURL로 Bearer 토큰을 설정하는 올바른 방법

API 끝점에서 Bearer 토큰을 가져오고 다음을 설정합니다.

$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



답변

바꾸다:

$authorization = "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

와:

$authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274";

유효하고 작동하는 Authorization 헤더로 만듭니다.


답변

데이터를 보내거나 검색 할 수있는 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


답변

이것은 작동합니다

$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);


답변

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를


답변

PHP 7.3에서 :

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


답변

대신 비공개 토큰 ( 예 : Gitlab API )으로 작업하는 경우 다음을 대체해야합니다.

$authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"

와:

$authorization = "PRIVATE-TOKEN 080042cad6356ad5dc0a720c18b53b8e53d4c274";


답변

<?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;

?>