使用基本身份验证保护Rest API

时间:2014-03-12 04:57:59

标签: php api curl

我目前正在制作一个休息API,它将使用SSL HTTP使用cURL调用(例如:curl http://domain.com/api/v1/hello -X POST -u my@email.com:1x5a6s9x4q1z2 -d post =&# 34;数据"。)

这就是我现在所处的位置 - 这是最好和最安全的方式吗?

我关心"你好" class - 只有在登录有效时才需要调用它。

<?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()
    ));
}
?>

1 个答案:

答案 0 :(得分:0)

您可以创建新功能来验证用户

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";
        }
 }
}