Adding JSON Web Token (JWT) Authentication to a Lumen Application

Table of Contents

Prerequisites

  1. PHP >= 7.2
  2. Composer

Installation

  1. Install the required packages: To use JWT in Lumen, you'll need to install the tymon/jwt-auth package. You can install it by running the following command in your terminal:

    composer require tymon/jwt-auth

Configuration

  1. Add the service provider: Open the bootstrap/app.php file in your project, and add the following line to the providers array:

    $app->register(Tymon/JWTAuth/Providers/LumenServiceProvider::class);
  2. Create the configuration file: Run the following command to create the configuration file for JWT:

    php artisan jwt:secret

    This will generate a new key in your .env file which will be used to sign the tokens.

Protecting Routes

To protect your routes with JWT, you can use the auth:api middleware. You can add it to a specific route or group of routes.

$router->group(['middleware' => 'auth:api'], function () use ($router) {
    // your routes here
});

Creating a Guard

Open the config/auth.php file, and add a new guard to the guards array, like this:

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

Creating a Controller

Create a new controller that will handle the authentication process. In this controller, you can define methods for logging in and logging out, and for returning a user's information.

Testing the Implementation

You can test your implementation by sending a request to the login route with a valid email and password, and checking the response for a valid token. Then, you can use this token to authenticate yourself for other routes that are protected by the auth:api middleware.

Seed Section

After you created the migration for the users table and run the migration. you can add a new user to the table using tinker or seeder by running this command :

php artisan tinker

then add the user by running this command :

App/User::create(['email' => 'admin@admin.com', 'password' => Hash::make('123456789')]);

Please note that this is a high-level overview and some steps may need to be adapted to your specific use case. Also you need to install lumen as well before you start following these steps by running the following command:

composer create

Share it if you like it 😉

© 2024 Khannoussi Malek, Inc. All rights reserved.

HTML🎨CSSJavaScript🌠✨TypeScript✨PHP⚛️React🔥Jhipster NodeJS⚡️Chakra-UiReact-queryLumen🦊 Gitlab 🦊