JWT Authentication in Laravel 5.8

Faisal Islam Raju
Monstar Lab Bangladesh Engineering
5 min readAug 22, 2019

One of the core features of a web based application is authorization and it can be implemented in many ways. The way I like to implement it is by token based authentication.

jwt authentication integration in laravel

JWT stands for JSON Web Token. JWT defines a way to transmit information between parties securely using JSON object. You can learn more about JWT from here.

We are going to integrate JWT authentication in our Laravel project and then we will check it with Postman.

If you haven’t created a Laravel project already, please create one. Lets name the project jwt-laravel. As of writing this article the latest Laravel version is 5.8.

Run the necessary migration command

php artisan migrate

and make sure the database is working perfectly.

Now lets start integrating JWT authentication in our project.

Step 1: Install the JWT package

We will be using the tymondesigns/jwt-auth package by Sean Tymon.

composer require tymon/jwt-auth 1.0.*

This will install the JWT package with the necessary files.

Step 2: Publish config

We will publish the config for our JWT auth.

php artisan vendor:publish --provider=”Tymon\JWTAuth\Providers\LaravelServiceProvider”

You can see there is a new file jwt.php created in the config folder.

Step 3: Create JWT secret key

php artisan jwt:secret

A JWT secret key will be created in our .env file. Never share this key with anyone.

Step 4: Modify User Model

We will modify our User model to include some more methods. First we will implement the JWTSubject contract on our User model. Then we will add some methods named getJWTIdentifier(), getJWTCustomClaims() and setPasswordAttribute()

The model will look like this

User.php

Step 5: Configure Auth

We will need to configure the auth guard to make the system use our JWT authentication. By default Laravel uses web guard which uses the session driver. We will change it to use the api guard and change the driver to jwt. So in config/auth.php we will make some changes so that the config inside will look similar to this

auth.php

Step 6: Make AuthController

We will create an auth controller named AuthController. To make the controller we will run the following command

php artisan make:controller AuthController

Then we put the following code in the file.

AuthController.php

Step 7: Add Routes

Next we add some routes in our routes/api.php file for the basic authentication. The file will look similar to this

routes/api.php

JWT authentication integration is complete. If we have a user and we input valid user data in route like localhost:80/api/login we should be able to get access token for that user.

So how do we check it for our current project? We don’t have any users. Lets just create a user controller with the following command

php artisan make:controller UserController

Next put the following code into the controller.

UserController.php

Lets modify our routes/api.php to include the following code

Route::post(‘users’, ‘UserController@store’);
Route::get(‘users’, ‘UserController@index’);

Our project is now ready to be tested for working authentication in Postman.

Let’s create a new user. We will use this user for authentication.

Open Postman. Enter the url localhost:80/api/users . Select the method as POST. In the body section add the necessary name, email, password and press the send button. You will get a response like this.

After the user creation is done. Lets enter a new url for login localhost:80/api/login . Set the method as GET. In the body section select form data and enter the value of email and password. Press send and you will get a response like this.

login with postman

It contains the information about the access token which will be used for all the necessary authentication tasks.

So if you want to access an api which requires an access token you have put the token as a Bearer Token in authorization. For example, if you want to know the details of the logged in user, you have to go the link localhost:80/api/me . You will get an empty response like below because you didn’t pass an access token.

To get more detailed error messages, such as: ‘Token is not valid’, ‘Token has expired’ etc we can add validation in the individual methods but the best practice would be to make a middleware that checks if a token is valid for specific requests.

So to do that lets create a new middleware named JWTMiddleware

php artisan make:middleware JWTMiddleware

Now add the following code into the newly created middleware.

Next add the next lines of code in the alias array in the config/app.php file.

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,

This will register the facades necessary for the middleware. Next, we will add the following code in routeMiddleware array of our app/Http/Kernel.php file.

'jwt.verify' => \App\Http\Middleware\JWTMiddleware::class,

Here we are giving our middleware a name jwt.verify to be recognized by our system.

Our middleware is now ready. To check for a specific route or method we will add the middleware to the necessary routes. Lets modify our routes/api.php file to include the jwt.verify middleware.

Route::post('login', 'AuthController@login');Route::group([
'middleware' => ['api','jwt.verify'],
], function ($router) {
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');
Route::post('me', 'AuthController@me');
});

Notice we have moved the login route outside of the group as that doesnt need the JWT validation. So now if you try the localhost:80/api/me route again without the access token, you will get a response similar to the one below.

You will have to put the bearer token in the authorization->Bearer Token field. Copy the access_token you got after login and paste it in the Token field. And then try the api again. This time you will get a response like this.

You can follow the same steps to get refresh tokens and also for logout.

So that is it for the basic JWT authentication integration in Laravel. In this article we have learned:

  • Setting up JWT authentication
  • Creating User
  • Testing with Postman
  • Adding middleware to verify token

If you want the source code and immediately want to run the project then you can go to the repository and follow the readme file:

You can follow the official documentation for the jwt-auth package to learn more.

Check out other articles from our engineering team:

https://medium.com/monstar-lab-bangladesh-engineering

Visit our website to learn more about us:

www.monstar-lab.co.bd

--

--