In my last tutorial, we created an APIs for todo application without authentication. In this tutorial, I would like to show you building JWT based login system. Let’s start…

Create Project

Create a brand new Laravel 5.6 project with Composer create-project command:

Database connection settings

After creating project open .env file and update your database credentials:

Next step, would be, go to the project root and open the terminal and type the following command. It will create the two tables, which is by default ships by Laravel 5.6

You might get following error :

to fix this, all you have to do is to edit your AppServiceProvider.php file and add to the boot method a default string length:

We gonna use jwt-auth library to generate and handle the JWT tokens, so let got to root of the project and run following Composer command from your terminal:

Then add the service JWTAuthServceProvider to the providers’ array and the JWTAuth facade to the aliases array in config/app.php

Now publish the configuration file

Now generate a key in the published configuration

Note: if this error gives you an error checkout below link to fix it.
https://github.com/tymondesigns/jwt-auth/issues/1298

Edit app/Http/Kernel.php adding jwt.auth and jwt.refresh to the application’s route middleware array.

Now let’s create the AuthController by issuing below command from the root of your project:

Going forward we gonna define register, login, logout, refresh and user methods in the AuthController.

signup

Let register a signup route.

Let us also create a FormRequest to handle validation for every registration request.

Now edit our RegisterFormRequest class to reflect the code below.

Final setup, create the register method that will handle user registrations

Login

Let’s deinfe login route

Create the login method in AuthController, it will handle the user logins

Current User

Let us define user route, it will give you current user information

Define user method in controller, which will return current user information

Logout

Now define logout route in routes/api.php.

Here is the log-out method which will handle the logout requests.

Refresh token

Define route to check the current token is valid or not and refresh the token if it is not invalidated.

create refresh method with below code

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Published by Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.

Join the Conversation

29 Comments

  1. verry useful… thank you…
    and how to Authentication REST API with E-Mail Verification? thx

    1. Whenever you call refresh route, you have to grab the new token from the response header of that request and use that new token from that point

  2. Well, a lot of these methods are deprecetad/renamed.

    It’s not :

    php artisan vendor:publish –provider=”TymonJWTAuthProvidersJWTAuthServiceProvider”

    It is :

    php artisan vendor:publish –provider=”TymonJWTAuthProvidersLaravelServiceProvider”

    or

    php artisan vendor:publish –provider=”TymonJWTAuthProvidersLumenServiceProvider”

    It’s not :

    php artisan jwt:generate

    It is :

    php artisan jwt:secret

        1. I guess those changes are not yet released. When I run the composer require I am still seeing old files .. providers, protected $name = ‘jwt:generate’;..etc.

          You are referring to develop branch

          1. Well, the branch you are working on is 11 months old right now and it’s currently stale. Just wait couple more weeks/months to update this post if you wish. I just wanted to inform because you were refering to latest 5.6, also is hard to find 5.6 guides on blogs at these days. But 5.6 with a 11 months old package integration? I don’t think it’ll last long.

  3. after calling refresh() token not accepting returning
    {
    “error”: “token_invalid”
    }

    1. After calling refresh token method you old token will expire. You have to grab new token from the response header and you have to send that new token to access the protected resources

  4. is there any way to authenticate API before authentication(login) process like registration API, Login API. the current process is only authenticating API’s after login process.

  5. I get an error when going to url.com/api/signup in POSTMAN.

    ReflectionException: Class AppHttpControllersRegisterFormRequest does not exist in file /home/rbfs6nkk73qi/client/prototype/vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php on line 25

  6. Hi i am trying to use jwt auth i am successful with User model. I want to use same for Admin model as i have 2 different tables for both models. Any help?

  7. Can we make another class like MobileUser and work with jwt or do we have to use User class which laravel generates, if yes where shall i have to change the class names

      1. No help i have created 2 user in auth.php user and mobileuser and i can register but cant login even if the credentials are correct

Leave a comment

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