PHP:在 CURL GET 调用中使用 API 密钥

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26495065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:55:54  来源:igfitidea点击:

PHP: Using API key in CURL GET Call

phpjsonapirestcurl

提问by Florentino

I have seen the post for using api key for authenticating post calls in curl. I have a GET call that requires apikey for authorization i.e the request must have an authorization header cantaining the apiKey. I have obtained the api key and try to use it for a GET call :

我已经看到使用 api 密钥来验证 curl 中的 post 调用的帖子。我有一个 GET 调用,它需要 apikey 进行授权,即请求必须有一个包含 apiKey 的授权标头。我已获得 api 密钥并尝试将其用于 GET 调用:

<?php

$service_url = 'http://localhost/finals/task_manager/v1/tasks/Authorization:'.$apiKey;
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('error occured during curl exec. Additioanl info: ' . var_export($info));
}

curl_close($curl);
$decoded1 = json_decode($curl_response,true);
if (isset($decoded1->response->status) && $decoded1->response->status == 'ERROR') {
    die('error occured: ' . $decoded1->response->errormessage);
}
echo 'response ok!';
var_export($decoded1->response);
?>

I am getting error in json response:

我在 json 响应中收到错误:

{"error":true,"message":"Api key is misssing"}

I have tried a few other ways like passing a header array but i keep getting the error. How to correctly get the curl_response ? How should I pass the Authorization header which uses the api key ?

我尝试了其他一些方法,例如传递标头数组,但我不断收到错误消息。如何正确获取 curl_response ?我应该如何传递使用 api 密钥的 Authorization 标头?

The api for the get call I am making is (created using Slim Library) :

我正在进行的 get 调用的 api 是(使用 Slim 库创建的):

index.php
/**
 * Listing all tasks of particual user
 * method GET
 * url /tasks          
 */
$app->get('/tasks', 'authenticate', function() {
            global $user_id;
            $response = array();
            $db = new DbHandler();

            // fetching all user tasks
            $result = $db->getAllUserTasks($user_id);

            $response["error"] = false;
            $response["tasks"] = array();

            // looping through result and preparing tasks array
            while ($task = $result->fetch_assoc()) {
                $tmp = array();
                $tmp["id"] = $task["id"];
                $tmp["task"] = $task["task"];
                $tmp["status"] = $task["status"];
                $tmp["createdAt"] = $task["created_at"];
                array_push($response["tasks"], $tmp);
            }

            echoRespnse(200, $response);
        });

The authenticate function is :

身份验证功能是:

in the same index.php file
/**
 * Adding Middle Layer to authenticate every request
 * Checking if the request has valid api key in the 'Authorization' header
 */
function authenticate(\Slim\Route $route) {
    // Getting request headers
    $headers = apache_request_headers();
    $response = array();
    $app = \Slim\Slim::getInstance();

    // Verifying Authorization Header
    if (isset($headers['Authorization'])) {
        $db = new DbHandler();

        // get the api key
        $api_key = $headers['Authorization'];
        // validating api key
        if (!$db->isValidApiKey($api_key)) {
            // api key is not present in users table
            $response["error"] = true;
            $response["message"] = "Access Denied. Invalid Api key";
            echoRespnse(401, $response);
            $app->stop();
        } else {
            global $user_id;
            // get user primary key id
            $user = $db->getUserId($api_key);
            if ($user != NULL)
                $user_id = $user["id"];
        }
    } else {
        // api key is missing in header
        $response["error"] = true;
        $response["message"] = "Api key is misssing";
        echoRespnse(400, $response);
        $app->stop();
    }
}

回答by trueicecold

ok so it should be pretty straightforward... Could you try and add:

好的,所以它应该非常简单......你可以尝试添加:

curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $apiKey
));

to your curl? After that, do a print_r($headers) in your authenticate() function to see if you receive it ok.

你的卷发?之后,在您的 authenticate() 函数中执行 print_r($headers) 以查看您是否收到它。

回答by Muhammad Shahzad

Access web service using custom Authorization key.

使用自定义授权密钥访问 Web 服务。

PHP Client,client.php

PHP客户端,client.php

$name = 'Book name';
//Server url
$url = "http://localhost/php-rest/book/$name";
$apiKey = '32Xhsdf7asd5'; // should match with Server key
$headers = array(
     'Authorization: '.$apiKey
);
// Send request to Server
$ch = curl_init($url);
// To save response in a variable from server, set headers;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Get response
$response = curl_exec($ch);
// Decode
$result = json_decode($response);

PHP Server, index.php

PHP 服务器,index.php

header("Content-Type:application/json");
$seceretKey = '32Xhsdf7asd';
$headers = apache_request_headers();
    if(isset($headers['Authorization'])){
        $api_key = $headers['Authorization'];
        if($api_key != $seceretKey) 
        {
            //403,'Authorization faild'; your logic
            exit;
        }
    }

回答by Deepak

to overcome this problem when passing Api key from Advance rest client use Authorization rather than authorization in header parameter. then it will work.

当从 Advance rest 客户端传递 Api 密钥时,要克服这个问题,请使用授权而不是标头参数中的授权。然后它会起作用。