Skip to content

Instantly share code, notes, and snippets.

@sergioloppe
Last active January 29, 2023 11:40
Show Gist options
  • Save sergioloppe/f2c4e83c976f86e5950d4bf4ffd5f848 to your computer and use it in GitHub Desktop.
Save sergioloppe/f2c4e83c976f86e5950d4bf4ffd5f848 to your computer and use it in GitHub Desktop.

How to use JWT Auth in Laravel 9

  1. Install the "php-open-source-saver/jwt-auth" package: Use the following command to install it:
composer require php-open-source-saver/jwt-auth
  1. Copy the package config file: Use the following command to copy the package config file to the config directory:
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
  1. Generate a secret key: Use the following command to generate a secret key for your JWT tokens:
php artisan jwt:secret
  1. Configure the package: In the config/jwt.php file, you'll find several options that you can use to configure the package.

  2. Implement the authentication middleware: You can use the "jwt.auth" middleware provided by the package to authenticate your API routes.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;

class JWTMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $message = '';
        try {
            // check validation of the token
            JWTAuth::parseToken()->authenticate();
            return $next($request);
        } catch (\PHPOpenSourceSaver\JWTAuth\Exceptions\TokenExpiredException $e) {
            $message = 'Token expired';
        } catch (\PHPOpenSourceSaver\JWTAuth\Exceptions\TokenInvalidException $e) {
            $message = 'Invalid token';
        } catch (\PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException $e) {
            $message = 'Provide token';
        }
        return response()->json(['success' => false, 'message' => $message]);
    }
}
  1. Update the Kernel.php file: Add the middleware to the $routeMiddleware array in the app/Http/Kernel.php file:
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'auth.jwt' => \App\Http\Middleware\JWTMiddleware::class,
        ...
    ];
  1. Update the defaults and guards in auth.php file:
    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
    
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
            'hash'=>false,
        ],
    ],
    
  1. Update the User model imlementing the clas JWTSubject:
...
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
...
  1. Implement the AuthController and add the routes to api.php file:
Route::post('/login',  [AuthController::class, 'login']);
Route::get('/logout', [AuthController::class, 'logout'])->middleware("auth.jwt");
Route::post('/refresh', [AuthController::class, 'refresh'])->middleware("auth.jwt");
Route::get('/user-profile', [AuthController::class, 'getUser'])->middleware("auth.jwt");
  1. Get access token:
curl --location --request POST 'http://localhost:8080/api/login' \
--header 'Content-Type: application/json' \
--data-raw '{
    "email":"admin@whatever.com",
    "password": "admin"
}'

Response:

{
    "success": true,
    "token": "eyJ0eXAiOiJK...",
    "user": {}
}
  1. Request private resources
curl --location --request GET 'http://localhost:8080/api/user-profile' \
--header 'Authorization: Bearer ACCESS_TOKEN_HERE' \
--data-raw ''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment