How to use JWT Token in Laravel

AuthorSumit Dey Sarkar

Pubish Date21 Mar 2023

categoryLaravel

In this tutorial we will learn how to use JWT token in Laravel.

JSON Web Tokens (JWTs) are a popular way of securely transmitting information between parties as a JSON object. Laravel makes it easy to work with JWTs by providing a package called "tymon/jwt-auth" that handles the creation, signing, and verification of tokens.

 

How to use JWT token in Laravel

Here are the steps to use JWT tokens in Laravel:

 

Step 1 - Install the tymon/jwt-auth package via Composer:

composer require tymon/jwt-auth

 

Step 2 - Run the package's installation command:

php artisan jwt:secret

 

Step 3 - Update the `config/auth.php` file to use JWT as the default driver:

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

 

Step 4 - Create a new authentication controller using the make:auth command:

php artisan make:controller AuthController

 

Step 5 - Define a method for generating a JWT token in the AuthController:

use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');

    try {
        if (!$token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'Invalid credentials'], 401);
        }
    } catch (JWTException $e) {
        return response()->json(['error' => 'Could not create token'], 500);
    }

    return response()->json(compact('token'));
}

 

Step 6 - Protect your routes with the `jwt.auth` middleware:

Route::group(['middleware' => 'jwt.auth'], function () {
    Route::get('protected', function () {
        return response()->json(['foo' => 'bar']);
    });
});

 

Step 7 - Send the JWT token with each request in the Authorization header:

Authorization: Bearer {your-token-here}

 

That's it! You can now use JWT tokens in your Laravel application.

Comments 0

Leave a comment