- Install the "php-open-source-saver/jwt-auth" package: Use the following command to install it:
composer require php-open-source-saver/jwt-auth
- 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"
- Generate a secret key: Use the following command to generate a secret key for your JWT tokens:
php artisan jwt:secret
-
Configure the package: In the config/jwt.php file, you'll find several options that you can use to configure the package.
-
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]);
}
}
- 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,
...
];
- Update the
defaults
andguards
inauth.php
file:
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash'=>false,
],
],
- Update the
User
model imlementing the clas JWTSubject:
...
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
...
- Implement the
AuthController
and add the routes toapi.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");
- 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": {}
}
- Request private resources
curl --location --request GET 'http://localhost:8080/api/user-profile' \
--header 'Authorization: Bearer ACCESS_TOKEN_HERE' \
--data-raw ''