在php中通过身份验证调用restfull API编辑:安全性

时间:2018-08-22 14:38:25

标签: php rest api restful-authentication

嗨,谢谢您的阅读。

我通过http查询来调用restfull API。它需要用户名和密码,因此我将其放在查询中(请参阅下面的代码)。我希望用户(同事)输入用户名和密码以将其放入查询中。这样,他们可以从拥有权限的api访问数据。但这不是内部api,因此我问自己如何确保查询的安全性,以使信息不会被拦截。

这是我尝试做的事情:

<?php
$username="user";
$passw="password";
$url="https://domaine.dom/api/path/to/file";
$params = array('limits' => '10', );

$header = array('Content-Type' => 'application/json');



//add the http authentication to the header
function addBasicAuth($header, $username, $password) {
    $header['Authorization'] = 'Basic '.base64_encode("$username:$password");
    return $header;
}

// method should be "GET", "PUT", etc..
function request($method, $url, $header, $params) {
$opts = array(
    'http' => array(
        'method' => $method,
    ),
);

// serialize the header if needed
if (!empty($header)) {
    $header_str = '';
    foreach ($header as $key => $value) {
        $header_str .= "$key: $value\r\n";
    }
    $header_str .= "\r\n";
    $opts['http']['header'] = $header_str;
}

// serialize the params if there are any
if (!empty($params)) {
    $params_array = array();
    foreach ($params as $key => $value) {
        $params_array[] = "$key=$value";
    }
    $url .= '?'.implode('&', $params_array);
}


//create flow context with option array completed with authentication informations
$context = stream_context_create($opts);
//get content in json ($header['Content-Type']=>'application/json')
//get back content in json
$data = file_get_contents($url, false, $context);
return $data;
}

$header = addBasicAuth($header, $username, $password);
/*after we call this function we have :
$header=array('Content-Type' => 'application/json',
            'Authorization' => Basic.base64("$username:$password")
);*/
$response = request("GET", $url, $header, $params);//create context, create request and launch it
echo $response;




/* code i tried to do myself
$authstring= $username.":".$passw;
$encodeauth= base64_encode($authstring);
$options = array('httpauth' => $encodeauth, );
$reponse=http_get($url, $options);
echo $reponse;
*/
?>

0 个答案:

没有答案