Laravel 5.6 – REST API – JWT Authentication

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.

DMCA.com Protection Status