Here’s an example of how to implement JSON Web Token (JWT) authentication in Laravel:
Contents hide
Install the required packages:
composer require tymon/jwt-auth
Add the service provider in config/app.php:
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],
Publish the configuration file:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Generate the secret key:
php artisan jwt:secret
Add the middleware to the app/Http/Kernel.php file:
protected $routeMiddleware = [
...
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
];
Create a LoginController with the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
class LoginController extends Controller
{
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 400);
}
return response()->json(compact('token'));
}
}
Add a route in the web.php file to point to the LoginController:
Route::post('login', 'LoginController@login');
To protect a route, add the ‘jwt.auth’ middleware:
Route::get('protected', function() {
return response()->json([
'message' => 'Access granted'
]);
})->middleware('jwt.auth');
This is a basic example of how to integrate JWT authentication into a Laravel application. You can customize and extend the implementation based on your specific needs.