Hello, dear readers! I’m Shahzad Ahmad Mirza, and today, I will guide you through creating a basic PHP API with token authentication. Let me tell you a little story about why this topic is close to my heart. A few days back, I wrote another tutorial on developing a basic PHP CRUD Rest API. I received several comments from readers who wanted to know how to write PHP code to create a basic PHP API with token authentication, So I am writing this tutorial for you.
Contents
A Journey into API Development
A few years back, I was working on a project for a client who needed a secure way to access their data from various platforms. They wanted something lightweight, easy to manage, and secure. After researching and experimenting, I found that building a PHP API with token authentication was the perfect solution. This journey helped me understand the importance of secure API development and solidified my love for PHP. Now, I’m excited to share this knowledge with you.
What You’ll Learn
In this tutorial, we will cover:
- Setting Up Your Environment
- Creating a Basic PHP API
- Implementing Token Authentication
- Testing Your API
1. Setting Up Your Environment
Before we dive into coding, we need to set up our environment. Here’s what you’ll need:
- PHP (at least version 7.4)
- Composer (for dependency management)
- A Web Server (like Apache or Nginx)
- Postman (for testing your API)
Install PHP and Composer
If you don’t have PHP and Composer installed, follow these steps:
- Download PHP from the official PHP website.
- Install Composer by following the instructions on the Composer website.
Once installed, verify the installation by running:
php -v
composer -v
Both commands should output their respective versions, indicating a successful installation.
2. Creating a Basic PHP API
Now, let’s create our basic PHP API. We’ll start by setting up a simple project structure.
Project Structure
my_api/
├── public/
│ └── index.php
├── src/
│ └── api.php
├── vendor/
├── composer.json
└── .htaccess
Step 1: Create composer.json
In the root directory (my_api
), create a composer.json
file:
{
"name": "my_api",
"description": "A basic PHP API with token authentication",
"require": {
"firebase/php-jwt": "^5.0"
}
}
Run composer install
to install the JWT package, which we’ll use for token generation and validation.
Step 2: Set Up .htaccess
If you’re using Apache, create a .htaccess
file in the public
directory to handle URL rewriting:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
This will redirect all requests to index.php
.
Step 3: Create index.php
In the public
directory, create index.php
:
<?php
require '../vendor/autoload.php';
require '../src/api.php';
use Firebase\JWT\JWT;
header("Content-Type: application/json; charset=UTF-8");
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode('/', $uri);
if ($uri[1] !== 'api') {
header("HTTP/1.1 404 Not Found");
exit();
}
$method = $_SERVER['REQUEST_METHOD'];
$api = new API();
switch ($method) {
case 'POST':
$api->handlePostRequest();
break;
case 'GET':
$api->handleGetRequest();
break;
default:
header("HTTP/1.1 405 Method Not Allowed");
exit();
}
Step 4: Create api.php
In the src
directory, create api.php
:
<?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class API
{
private $secretKey = 'your_secret_key'; // Replace with your actual secret key
public function handlePostRequest()
{
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input['username']) && isset($input['password'])) {
$token = $this->generateToken($input['username']);
echo json_encode(['token' => $token]);
} else {
header("HTTP/1.1 400 Bad Request");
echo json_encode(['message' => 'Invalid input']);
}
}
public function handleGetRequest()
{
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
$authHeader = $headers['Authorization'];
list($jwt) = sscanf($authHeader, 'Bearer %s');
if ($jwt) {
try {
$decoded = JWT::decode($jwt, new Key($this->secretKey, 'HS256'));
echo json_encode(['message' => 'Access granted', 'user' => $decoded->username]);
} catch (Exception $e) {
header("HTTP/1.1 401 Unauthorized");
echo json_encode(['message' => 'Access denied', 'error' => $e->getMessage()]);
}
} else {
header("HTTP/1.1 400 Bad Request");
echo json_encode(['message' => 'Invalid token format']);
}
} else {
header("HTTP/1.1 400 Bad Request");
echo json_encode(['message' => 'Authorization header not found']);
}
}
private function generateToken($username)
{
$payload = [
'iss' => "http://example.org",
'aud' => "http://example.com",
'iat' => time(),
'nbf' => time(),
'username' => $username
];
return JWT::encode($payload, $this->secretKey, 'HS256');
}
}
3. Implementing Token Authentication
In this section, we’ll explore token authentication and its role in ensuring secure access to your API.
What is Token Authentication?
Token authentication is a security technique in which a token (a unique string) is used to verify a user’s identity. This token is usually generated upon successful login and must be included in subsequent requests to access protected resources.
Generating Tokens
As seen in our api.php
, we generate a token using the Firebase\JWT
package. This token contains essential user information and an expiry time, making it secure and temporary.
Verifying Tokens
When a request is made with a token, we decode and verify it. If valid, the user gains access; if not, an error is returned. This ensures only authenticated users can interact with your API.
4. Testing Your API
Now that our API is set up, let’s test it using Postman.
Step 1: Generate a Token
- Open Postman.
- Create a new POST request to
http://yourdomain.com/api
. - In the body, select
raw
andJSON
format, and input:jsonCopy code{ "username": "test_user", "password": "test_password" }
- Send the request and you should receive a token in the response.
Step 2: Access Protected Resource
- Create a new GET request to
http://yourdomain.com/api
. - Go to the
Headers
tab and add:makefileCopy codeAuthorization: Bearer YOUR_TOKEN_HERE
- Send the request. If the token is valid, you’ll see a success message; if not, an error message.
Conclusion
And there you have it! You’ve created a basic PHP API with token authentication. This setup not only ensures secure access to your API but also gives you a solid foundation to build upon.
Remember, security is paramount, and token authentication is a powerful way to protect your APIs. Feel free to reach out if you have any questions or need further assistance.
Happy coding!