How to Build a Secure REST API with JWT Authentication in PHP

Building a secure REST API is a fundamental skill for modern web development. While traditional applications rely on server-side sessions to track user states, REST APIs are inherently stateless.

This is where JSON Web Tokens (JWT) come in. JWT provides a compact, URL-safe means of representing claims to be transferred between two parties. Instead of storing a session on your server, you authenticate the user once, issue a signed token, and the client sends that token with every subsequent request.

Key insight: A JWT consists of three parts—header, payload, and signature. Because the signature is cryptographically signed, the server can verify the token's authenticity without needing to query a database for a session ID.

Prerequisites

To follow this guide, you will need:

  • A local development environment running PHP (e.g., XAMPP, WAMP, or Laravel Valet).
  • MySQL for database management. Composer installed globally to manage PHP dependencies.
  • An API testing tool like Postman or Insomnia.

Building the API

This guide uses native, object-oriented PHP to ensure the concepts remain clear and framework-agnostic. Follow these steps sequentially to build your authentication system.

Testing Your Implementation

  • Create a User: Manually insert a user into your database. Make sure to hash the password using password_hash('your_password', PASSWORD_DEFAULT) in PHP before inserting it into the database.
  • Generate a Token: Open Postman, make a POST request to login.php with a JSON body containing the email and password. If successful, copy the returned "token" string.
  • Access Protected Data: Make a GET request to protected.php. In Postman, go to the Headers tab, add a key called Authorization, and set the value to Bearer YOUR_COPIED_TOKEN.

By implementing this flow, your PHP application is now equipped to handle scalable, stateless API requests securely.

  1. Set Up the Database:
    1. MySQL Configuration.
    2. First, we need a table to store our user credentials. Run the following SQL query in your database manager to create the api_db database and the users table.

SQL

CREATE DATABASE api_db;
    USE api_db;    CREATE TABLE users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(50) NOT NULL,
        email VARCHAR(50) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );

  ```

*Note: Always ensure you insert passwords using PHP's `password_hash()` function when creating users.*
 Create a new directory for your project and open your terminal inside it. We will use the popular `firebase/php-jwt` library to handle the encoding and decoding of our tokens.

```bash
 composer require firebase/php-jwt
```
This will generate a `vendor` folder containing the library and an `autoload.php` file.
Create a `config` folder and add a `database.php` file. We will use PDO (PHP Data Objects) for a secure, object-oriented database connection.

PHP

class Database {

private $host = "localhost";

private $db_name = "api_db";

private $username = "root";

// Change to your DB username private $password = "";

// Change to your DB password public $conn;

public function getConnection() {
        $this->conn = null;
        try {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        } catch(PDOException $exception) {
            echo "Connection error: " . $exception->getMessage();
        }
        return $this->conn;
    }
}

This endpoint will verify the user's credentials against the database. If successful, it generates a signed JWT and returns it to the client. Create a file named `login.php` in your root directory.

    ```php
    getConnection();

    // Get posted data
    $data = json_decode(file_get_contents("php://input"));

    if(!empty($data->email) && !empty($data->password)){
        $query = "SELECT id, name, password FROM users WHERE email = :email LIMIT 0,1";
        $stmt = $db->prepare($query);
        $stmt->bindParam(":email", $data->email);
        $stmt->execute();
        if($stmt->rowCount() > 0){
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            // Verify the hashed password
            if(password_verify($data->password, $row['password'])){
                $secret_key = "YOUR_SUPER_SECRET_KEY"; // Store this securely in production
                $issuedat_claim = time(); 
                $expire_claim = $issuedat_claim + 3600; // Token valid for 1 hour
                $token = array(
                    "iat" => $issuedat_claim,
                    "exp" => $expire_claim,
                    "data" => array(
                        "id" => $row['id'],
                        "name" => $row['name'],
                        "email" => $data->email
                    )
                );

                // Generate JWT
                $jwt = JWT::encode($token, $secret_key, 'HS256');
                echo json_encode(array("message" => "Successful login.", "token" => $jwt));
            } else {
                http_response_code(401);
                echo json_encode(array("message" => "Login failed. Incorrect credentials."));
            }
        } else {
            http_response_code(401);
            echo json_encode(array("message" => "Login failed. User not found."));
        }
    } else {
        http_response_code(400);
        echo json_encode(array("message" => "Incomplete data."));
    }
    ?>
    ```  

Now, let's create a route that only authenticated users can access. This script intercepts the incoming request, extracts the Bearer token from the authorization header, and verifies its signature.

PHP

require 'vendor/autoload.php';

use \Firebase\JWT\JWT;

use \Firebase\JWT\Key;

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// Fetch the authorization header
$headers = apache_request_headers();
$auth_header = isset($headers['Authorization']) ? $headers['Authorization'] : "";

// Extract token (Format: "Bearer ")
$jwt = str_replace('Bearer ', '', $auth_header);

if($jwt){
    try {
        $secret_key = "YOUR_SUPER_SECRET_KEY";
        
        // Decode and verify token
        $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
        
        http_response_code(200);
        echo json_encode(array(
            "message" => "Access granted.", 
            "user_data" => $decoded->data
        ));
        
    } catch (Exception $e){
        // Token is invalid, expired, or tampered with
        http_response_code(401);
        echo json_encode(array("message" => "Access denied.", "error" => $e->getMessage()));
    }
} else {
    http_response_code(401);
    echo json_encode(array("message" => "Access denied. No token provided."));
}

{/* Reason: Broad technical topic with multiple valid next steps. */}