LaravelLaravel & VueJsVueJs

Laravel JWT Authentication Tutorial Example

Laravel JWT Authentication Tutorial we will discuss today. Setting up JWT Token-based Authentication in Laravel 5.6 is easy. The traditional process of interacting with a website is that you log in from the login page. Next, you perform your desired actions and then log out. However, in the case of REST API, the process is entirely different. JWT (JSON Web Token) is usually used to send information that can be trusted and verified using a digital signature.

When we can use JSON Web Tokens

Let us say; you have a mobile application that needs to communicate with the server. Now, a server needs to identify that whom they are talking. HTTP is the stateless protocol. So we need to create a mechanism that resolves our issue that is how the server will identify that the user is new or old. Is it already registered with the application or not. Is it authorized a user or not? In that scenario, we can use JWT Authentication.

JWT Authentication

  1. A user sends a signup post request to the server and server creates a user and JWT token on that database and returns JWT token as a response.
  2. JWT  is stored either in the local storage of the browser or any other storage mechanisms.
  3. When a user makes another request, it needs to append that token in the request header.
  4. The server checked that token and based on whether the JWT token is valid or not; it returns a response.
  5. Until a user logs manually out of the application and destroys that token from the local storage, it always checks for the token. If the token is valid, then it can access the particular resources.
  6. If the token is either destroyed or manipulated then, user redirects to the login screen and he needs to fill the username and password.
  7. If the username and password are valid then in response it sends a JWT token back to the user. Again same procedure, the user stores it in local storage and send that token for every request to verify with the server that he has trusted user and can able to access the particular resources.
★ READ ALSO ★  Vue.js Google Adsense Component with InFeed Ads support

Laravel JWT Authentication Tutorial

As usual, we start this project by installing fresh Laravel 5.6.

 Step 1: Install and configure Laravel 5.6

Install Laravel by the following command.

composer create-project laravel/laravel jwtauth --prefer-dist

Configure the database.
Now, install the third-party jwtauth package by typing the following command.

composer require tymon/jwt-auth

It will install the package in the vendor folder and our composer.json file will be updated.

Step 2: Update the config/app.php for JWT package

Go to the config  >>  app.php file and add the following.

'providers' => [
'aliases' => [
    'JWTAuth' => 'TymonJWTAuthFacadesJWTAuth',
        'JWTFactory' => 'TymonJWTAuthFacadesJWTFactory',

To publish the configuration file in Laravel, you need to run following line of code :

php artisan vendor:publish --provider="TymonJWTAuthProvidersJWTAuthServiceProvider"

Now for token encryption, I need to generate a secret key by running following line of code :

php artisan jwt:generate

If you find an error like this after hit the above command.
ReflectionException : Method TymonJWTAuthCommandsJWTGenerateCommand::handle() does not exist
You need to do the following step.

Go to JWTGenerateCommand.php file located in vendor/tymon/src/Commands and paste this part of code public function handle() { $this->fire(); }

You can find more about this issue.

Step 3: Register the user into the database.

Migrate the tables into the database by the following command.

php artisan migrate

Now, create two controller files for user registration and authentication.

  1. APIRegisterController.php
  2. APILoginController.php
★ READ ALSO ★  Adding unspecified GET parameters to Routes

Type the following command to generate it.

php artisan make:controller APIRegisterController
php artisan make:controller APILoginController

Also, register the api routes inside routes  >>  api.php file.

Route::post('user/register', 'APIRegisterController@register');
Route::post('user/login', 'APILoginController@login');

First, we code the register function inside APIRegisterController.php file.


namespace AppHttpControllers;
use AppHttpControllersController;
use IlluminateHttpRequest;
use AppUser;
use JWTFactory;
use JWTAuth;
use Validator;
use Response;

class APIRegisterController extends Controller
    public function register(Request $request)
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255|unique:users',
            'name' => 'required',
            'password'=> 'required'
        if ($validator->fails()) {
            return response()->json($validator->errors());
            'name' => $request->get('name'),
            'email' => $request->get('email'),
            'password' => bcrypt($request->get('password')),
        $user = User::first();
        $token = JWTAuth::fromUser($user);
        return Response::json(compact('token'));

What I have done is that first check the validation, and then if all the form data seems right then, it will register the user in the database and returns a JWT token. We are generating the token based on the User object. You can create the token from anything as you want. You can find more guidance here.

Step 4: Test in Postman.

We are registering the user through postman. So let us do that.
First, we check the validation.

Now, fill name, email, and password and see, if we can get the token or not.

Laravel 5.6 JWT Authentication Tutorial

Yikes!! We have successfully registered the user and get back the JWT token. Now save this token in the local storage and when we need to access any protected resource then pass this token as Auth Bearer to get request, and you can obtain that route.

★ READ ALSO ★  Lies you've been told about testing

Step 5: Login the user.

We have already defined the login route in the api.php file. Now, go the APILoginController.php file and code the login function.

// APILoginController.php


namespace AppHttpControllers;
use AppHttpControllersController;
use IlluminateHttpRequest;
use Validator;
use JWTFactory;
use JWTAuth;
use AppUser;
use IlluminateSupportFacadesAuth;

class APILoginController extends Controller
    public function login(Request $request)
        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email|max:255',
            'password'=> 'required'
        if ($validator->fails()) {
            return response()->json($validator->errors());
        $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'));

If the email and password are correct then we can generate the JWT token otherwise we get an error. Now check this in the POSTMAN and see if we can get the token.

Laravel 5.6 API Authentication Tutorial

Step 6: Include middleware to protect the resources.

The /jwt-auth package provides us by default two middlewares.

We just need to register these middlewares into app  >>  Http  >> Kernel.php file.

protected $routeMiddleware = [
'jwt.auth' => 'TymonJWTAuthMiddlewareGetUserFromToken',
'jwt.refresh' => 'TymonJWTAuthMiddlewareRefreshToken',

Define one route that needs to be protected via JWT Token Authentication.

// api.php

Route::middleware('jwt.auth')->get('users', function(Request $request) {
    return auth()->user();

Now, login to the application and get the token. Now, we can use this token in the get request like the following.

Authorization: Bearer {yourtokenhere}


And, we are getting the User back. So Our fully functional Laravel JWT Authentication Tutorial Example is working. Finally, Laravel JWT Authentication Tutorial is over. I have put this code on Github. So please check that out as well.

Fork Me

Source link

2 thoughts on “Laravel JWT Authentication Tutorial Example”

Leave a Reply

Your email address will not be published. Required fields are marked *