如何使我的PHP客户端成为唯一可以从我的PHP服务器获取数据的客户端


How to make my PHP client be the only one that can get data from my PHP server

你好,我有一个简单的代码:

客户端

<?php
function get_url($request_url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $request_url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
$request_url = 'http://localhost:8080/vb/dashboard/Marketing_dashboard/vb_server.php?function=somefunction';
$response = get_url($request_url);
print_r($response);

服务器

if(isset($_GET['function']) && $_GET['function'] == 'somefunction')
{
    echo somefunction();
}
function somefunction()
{
    return "this is the output of the server";
}

现在我需要添加安全性,这样只有我的客户端才能获得数据。我想到了一对密钥,所以我发送了一些用客户端私钥封装的哈希,并在服务器上用公钥对其进行解码。但我不知道如何实现这一点。我不知道如何获取密钥,也不知道如何编写代码。

我对选择持开放态度。如何使我的客户端成为唯一能够从该服务器获取数据的客户端?

首先,让客户端连接到https端点,以便对其进行加密。接下来,您可以通过HTTP头传入一个令牌,并在客户端进行检查。

Rackspace API使用以下标题:

X-Auth令牌:asdflkjasdflkjasdfrkjasdfsadflkjasf

然后您可以获取标头,验证令牌是否正确。如果是,请执行该函数。如果没有,返回空白页或其他内容。

你可以这样设置你的标题:

curl_setopt($c, CURLOPT_HTTPHEADER, array('X-Auth-Token: asdflkjasdflkjasdflkjsadflkjasdf'));

检查如下:

$headers = getallheaders();
if($headers['X-Auth-Token'] == 'asdflkjasdflkjasdflkjsadflkjasdf')
{
  if(isset($_GET['function']) && $_GET['function'] == 'somefunction')
  {
      echo somefunction();
  }
}
else
{
  echo "BAD TOKEN!";
}
function somefunction()
{
    return "this is the output of the server";
}

测试输出:

root@app01:/var/www/vhosts/application# curl -s http://localhost/headers.php -H "X-Auth-Token: asdflkjasdflkjasdflkjsadflkjasdf"
User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4   libidn/1.23 librtmp/2.3
Host: localhost
Accept: */*
X-Auth-Token: stuff
BAD TOKEN!

root@app01:/var/www/vhosts/application# curl -s http://localhost/headers.php -H "X-Auth-Token: asdflkjasdflkjasdflkjsadflkjasdf"
User-Agent: curl/7.22.0 (x86_64-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
Host: localhost
Accept: */*
X-Auth-Token: asdflkjasdflkjasdflkjsadflkjasdf
DO STUFF

您也可以设置客户端证书,以便它使用客户端提供的证书进行身份验证。这可能有点过头了,这取决于你试图做什么。请参阅"客户端身份验证和访问控制"一节

http://httpd.apache.org/docs/2.2/ssl/ssl_howto.html