Skip to content
PHP

How to Generate Simple JWT Authentication System in PHP

A
Author
Apr 1, 2025 · 3 min read
How to Generate Simple JWT Authentication System in PHP

JWT tokens are widely used for secure user authentication and data exchange. This article explains how to build a simple JWT authentication system in PHP using Composer and PSR-4 autoloading.

Start by setting up a clean project structure with an index.php as the entry point, a composer.json to manage dependencies, and a src/ directory for your core classes like JwtManager. This structure leverages PSR-4 to automatically load classes via Composer.

The JwtManager class creates, validates, and decodes JWTs. It constructs a token by encoding a header (with algorithm and token type) and a payload (containing user data and expiration time) using a base64 URL-safe method. Then, it generates a signature with HMAC SHA-256 using your secret key, combining these components into a single token.

The validateToken method splits the token, decodes the signature, and verifies it against a newly generated signature. The decodeToken method extracts and decodes the payload for further processing.

Composer’s autoloading (via composer dump-autoload) ensures new classes in src/ are automatically available, promoting a modular codebase. In your index.php, include Composer’s autoloader, instantiate JwtManager with your secret key, create a token with a payload, and validate it.

This streamlined approach results in a robust, scalable, and secure JWT-based authentication system, ideal for both small projects and larger applications.

JSON Web Tokens (JWT) are a secure method for transmitting information between parties. In this guide, we’ll create a basic JWT system using PHP, Composer, and the PSR-4 autoloading standard.

Project Structure

To generate your Composer configuration and install Guzzle HTTP, run the following commands in your project directory:

Composer init
composer require guzzlehttp/guzzle

Organize your project as follows:

jwt-php/
├── composer.json
├── index.php
├── src/
│   └── JwtManager.php
└── vendor/
  • composer.json: Defines autoloading and any dependencies.
  • index.php: Acts as the entry point.
  • src/JwtManager.php: Contains the core JWT logic.

composer.json

Configure PSR-4 autoloading in your composer.json:

{
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

Run the following command to generate the autoloader:

composer dump-autoload

JwtManager Class

Create src/JwtManager.php with the following content:

<?php
namespace App;

class JwtManager
{
    private $secretKey;

    public function __construct($secretKey)
    {
        $this->secretKey = $secretKey;
    }

    public function createToken($payload)
    {
        $header = json_encode(["alg" => "HS256", "typ" => "JWT"]);
        $payload = json_encode($payload);
        $base64UrlHeader = $this->base64UrlEncode($header);
        $base64UrlPayload = $this->base64UrlEncode($payload);
        $signature = hash_hmac('sha256', $base64UrlHeader . '.' . $base64UrlPayload, $this->secretKey, true);
        $base64UrlSignature = $this->base64UrlEncode($signature);
        return $base64UrlHeader . '.' . $base64UrlPayload . '.' . $base64UrlSignature;
    }

    private function base64UrlEncode($data)
    {
        $base64 = base64_encode($data);
        $base64Url = strtr($base64, '+/', '-_');
        return rtrim($base64Url, '=');
    }

    private function base64UrlDecode($data)
    {
        $base64 = strtr($data, '-_', '+/');
        $padding = strlen($base64) % 4;
        if ($padding) {
            $base64 .= str_repeat('=', 4 - $padding);
        }
        return base64_decode($base64);
    }

    public function validateToken($token)
    {
        list($header, $payload, $signature) = explode('.', $token);
        $expectedSignature = hash_hmac('sha256', $header . '.' . $payload, $this->secretKey, true);
        return hash_equals($this->base64UrlDecode($signature), $expectedSignature);
    }

    public function decodeToken($token)
    {
        list(, $payload, ) = explode('.', $token);
        return json_decode($this->base64UrlDecode($payload), true);
    }
}

Entry Point (index.php)

In index.php, load Composer’s autoloader and use the JwtManager class:

<?php
require __DIR__ . '/vendor/autoload.php';

use App\JwtManager;

$secretKey = 'your_secret_key';
$jwtManager = new JwtManager($secretKey);

$payload = [
    "user_id"  => 123,
    "username" => "john_doe",
    "exp"      => time() + 3600, // 1 hour expiration
];

$jwt = $jwtManager->createToken($payload);
echo "JWT Token: " . $jwt . PHP_EOL;

if ($jwtManager->validateToken($jwt)) {
    echo "JWT is valid." . PHP_EOL;
    $decoded = $jwtManager->decodeToken($jwt);
    echo "Decoded Payload: " . json_encode($decoded, JSON_PRETTY_PRINT) . PHP_EOL;
} else {
    echo "JWT is invalid.";
}

This simple JWT system forms a foundation for authentication in PHP applications, ensuring secure token management with a modern, modular approach.

A
Author

Author at The Creative Coders.

The monthly build log

One email a month. New posts, lessons, and the occasional strong opinion. No spam.