In the last post, we explained how to create a basic REST service. But everybody can access to it. What do if we want to make it accessible only for authenticated users? There are a few authentication methods for REST service, and the most used of them is the OAuth, but today we shall speak about another method more simple called Basic Auth.
We shall skip the database connection and we shall use a static array for the data. This is the PHP code:
File: app/controllers/framework_controller.php
<?php
class FrameworkController extends RestController {
protected $fw = array(1 => array(
"name" => "KumbiaPHP",
"description" => "The best PHP framework on the world"
),
array(
"name" => "Laravel",
"description" => "The new boy in the neighbourhood"
),
array(
"name" => "Symfony",
"description" => "The old veteran man"
),
);
public function get($id) {
if (isset($this->fw[$id])) {
$this->data = $this->fw[$id];
} else {
$this->error('This framework doesn\'t exist', 404);
}
}
public function getAll() {
$this->data = $this->fw;
}
}
We created a new controller called Framework controller with two actions: getAll for getting all frameworks, and get for getting a framework by id. But this controller is still accessible for all users. Now, we shall open the rest_controller.php file located in the directory default\app\libs. Add the user’s data for the authentication in an array and add the validation in the initialize method.
<?php
require_once CORE_PATH . 'kumbia/kumbia_rest.php';
class RestController extends KumbiaRest {
protected $users = array(
'alberto' => '123456',
'ashrey' => '0000'
);
final protected function initialize() {
$user = isset($_SERVER['PHP_AUTH_USER']) ? filter_var($_SERVER['PHP_AUTH_USER']) : null;
$pass = isset($_SERVER['PHP_AUTH_PW']) ? filter_var($_SERVER['PHP_AUTH_PW']) : null;
if (isset($this->users[$user]) && ($this->users[$user] == $pass)) {
return true;
} else {
$this->data = $this->error("Fail authentication", 401);
header('WWW-Authenticate: Basic realm="Private Area"');
return false;
}
}
final protected function finalize() {
}
}
Now, you need to send a valid user and password for access to the results. You can use a tool like Postman or HttpRequester for to test, or your browser. Using Firefox, you will look a dialogue like:
If you type a correct user and password you can see a page like:
else you will see a page like: