How to create a JWT Authentication in PHP

JWT authentication module in PHP using the firebase/php-jwt library:

Step 1: Install the firebase/php-jwt library You can install the library using Composer by running the following command in your project’s root directory:

 

				
					composer require firebase/php-jwt
				
			

Step 2: Create the JWT authentication module Create a new file called AuthModule.php with the following contents:

				
					<?php

require_once 'vendor/autoload.php';

use Firebase\JWT\JWT;

class AuthModule
{
    private $secretKey;
    private $expirationTime;

    public function __construct()
    {
        // Set the secret key (replace with your own secret key)
        $this->secretKey = 'your-secret-key';

        // Set the expiration time for the JWT (in seconds)
        $this->expirationTime = 3600; // 1 hour
    }

    public function generateToken($userId)
    {
        // Prepare the payload data
        $payload = [
            'user_id' => $userId,
            'exp' => time() + $this->expirationTime,
        ];

        // Generate the JWT token
        $token = JWT::encode($payload, $this->secretKey);

        return $token;
    }

    public function validateToken($token)
    {
        try {
            // Attempt to decode the token
            $payload = JWT::decode($token, $this->secretKey, ['HS256']);

            // Check if the token has expired
            if (time() > $payload->exp) {
                return false;
            }

            return true;
        } catch (\Exception $e) {
            // Invalid token or other error occurred
            return false;
        }
    }

    public function getUserIdFromToken($token)
    {
        try {
            // Attempt to decode the token
            $payload = JWT::decode($token, $this->secretKey, ['HS256']);

            // Check if the token has expired
            if (time() > $payload->exp) {
                return null;
            }

            // Return the user ID from the payload
            return $payload->user_id;
        } catch (\Exception $e) {
            // Invalid token or other error occurred
            return null;
        }
    }
}
				
			

Step 3: Using the JWT authentication module You can use the AuthModule class to generate and validate JWT tokens. Here’s an example of how you can use it:

				
					require_once 'AuthModule.php';

$auth = new AuthModule();

// Generate a token for a user ID
$userId = 1;
$token = $auth->generateToken($userId);
echo "Generated token: $token\n";

// Validate a token
$isValid = $auth->validateToken($token);
echo "Is valid token: " . ($isValid ? 'true' : 'false') . "\n";

// Get the user ID from a token
$userId = $auth->getUserIdFromToken($token);
echo "User ID from token: $userId\n";
				
			

In this example, the generateToken method generates a JWT token based on a user ID. The validateToken method checks if a token is valid and not expired. The getUserIdFromToken method extracts the user ID from a token.

Please note that this is a basic example, and you may need to customize it further based on your specific requirements, such as adding additional claims, handling token storage, and integrating it with your authentication workflow.