[英]Securing Rest API with Basic Authentication
我目前正在制作一個rest API,它將使用SSL HTTP通過cURL調用(例如:curl http://domain.com/api/v1/hello -X POST -u my@email.com:1x5a6s9x4q1z2 -d post =“數據”)。
這就是我目前的位置-這是最好,最可靠的方法嗎?
我擔心“ hello”類-僅在登錄有效時才需要調用它。
<?php
require_once '../rest.class.php';
class Api extends Rest {
protected $user;
public function __construct($request) {
parent::__construct($request);
$this->db = new PDO('mysql:host=******;dbname=******;charset=utf8', '******', '******');
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
$DBH = $this->db;
$STH = $DBH->prepare("SELECT id FROM user WHERE email=:email AND api=:api LIMIT 0,1");
$STH->execute(array(
'email' => $_SERVER['PHP_AUTH_USER'],
'api' => $_SERVER['PHP_AUTH_PW']
));
if($STH->rowCount() == 1) {
while($row = $STH->fetch()) {
$this->user = $row["id"];
}
}
else {
throw new Exception('Invalid API login credentials.');
}
}
else {
throw new Exception('Please provide valid API login credentials.');
}
}
protected function hello() {
if($this->method == 'POST') {
$response = array();
$response['user'] = $this->user;
$response['method'] = $this->method;
return $response;
}
else {
return "Only accepts POST requests";
}
}
}
try {
$Api = new Api($_REQUEST['request']);
echo $Api->processAPI();
}
catch (Exception $e) {
echo json_encode(Array(
'error' => $e->getMessage()
));
}
?>
您可以創建新功能來驗證用戶
function validate_user()
{
}
and call this function in hello
protected function hello()
{
if($this->validate_user())
{
if($this->method == 'POST') {
$response = array();
$response['user'] = $this->user;
$response['method'] = $this->method;
return $response;
}
else {
return "Only accepts POST requests";
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.