Rest API Authentication in PHP Using Access Token Part 1
In this tutorial, we will see how to create a rest API authentication system in PHP using an access token, the user can register and log in using his credentials, and once he is logged in he will get an access token that allows him to log out.
MySQL Tables
First, let's create a database I gave it 'php_events' as the name and added the following tables inside:
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `api_keys` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`api_key` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `api_keys`
ADD PRIMARY KEY (`id`),
ADD KEY `user_id` (`user_id`);
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
ALTER TABLE `api_keys`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;
ALTER TABLE `api_keys`
ADD CONSTRAINT `api_keys_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`);
Connect to the database
The structure of our project will be like this:
- src
-App
-Controllers
-Models
-Database
.htaccess
composer.json
index.php
so inside src, we have the files .htaccess, composer.json, and index.php, we have also the folder App which contains folders (controllers, models, database).
Now inside the folder Database we add a new file Database.php here we connect our app to the MySQL database.
<?php
namespace App\Database;
use PDO;
class Database
{
private $servername = 'localhost';
private $username = 'root';
private $password = '';
private $dbname = 'php_events';
public function connect()
{
try {
$db = new PDO("mysql:host=$this->servername;dbname=$this->dbname",
$this->username, $this->password);
$db->exec("set names utf8");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
} catch (PDOException $e) {
echo "Connection failed ". $e->getMessage();
}
}
}
Auto loading Classes
Next, to auto-load classes add the following code inside composer.json and run the command:
composer dump-autoload
{
"autoload": {
"psr-4": {
"App\\":"src/App"
}
}
}