How To Create A JWT Authentication In Laravel

Laravel has built-in support for JWT authentication through the tymon/jwt-auth package. Here’s an example of a JWT authentication module using tymon/jwt-auth in Laravel:

Step 1: Install the tymon/jwt-auth package You can install the package using Composer by running the following command in your Laravel project’s root directory:

				
					composer require tymon/jwt-auth
				
			

Step 2: Configure the package Run the following command to generate the configuration file for JWT:

				
					php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
				
			

This command will generate a jwt.php file in your config directory.

Step 3: Generate the JWT secret key Run the following command to generate a secret key for JWT:

				
					php artisan jwt:secret
				
			

This command will generate a random key and update your .env file with the generated key.

Step 4: Create the JWT authentication module Create a new file called JWTAuthModule.php in your preferred location with the following contents:

				
					<?php

namespace App\Modules;

use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;

class JWTAuthModule
{
    public function generateToken($user)
    {
        try {
            // Generate a token for the user
            $token = JWTAuth::fromUser($user);
            
            return $token;
        } catch (JWTException $e) {
            // Failed to generate token
            return null;
        }
    }

    public function validateToken($token)
    {
        try {
            // Validate the token
            $isValid = JWTAuth::parseToken()->check();

            return $isValid;
        } catch (TokenExpiredException $e) {
            // Token has expired
            return false;
        } catch (TokenInvalidException $e) {
            // Token is invalid
            return false;
        } catch (JWTException $e) {
            // Other error occurred
            return false;
        }
    }

    public function getUserFromToken()
    {
        try {
            // Get the user from the token
            $user = JWTAuth::parseToken()->authenticate();

            return $user;
        } catch (TokenExpiredException $e) {
            // Token has expired
            return null;
        } catch (TokenInvalidException $e) {
            // Token is invalid
            return null;
        } catch (JWTException $e) {
            // Other error occurred
            return null;
        }
    }
}
				
			

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

				
					use App\Modules\JWTAuthModule;
use App\Models\User;

$jwtAuth = new JWTAuthModule();

// Generate a token for a user
$user = User::find(1);
$token = $jwtAuth->generateToken($user);
echo "Generated token: $token\n";

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

// Get the user from a token
$user = $jwtAuth->getUserFromToken();
if ($user) {
    echo "User ID: " . $user->id . "\n";
    echo "User Name: " . $user->name . "\n";
} else {
    echo "Invalid token or user not found\n";
}
				
			

In this example, the generateToken method generates a JWT token for a given user. The validateToken method checks if a token is valid and not expired. The getUserFromToken method retrieves the user from a token if the token is valid.

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.