Token Based Authentication With Laravel 5.5

In this tutorial i will demonstrate how to create token based authentication with laravel 5.5. Token authentication normally used in when have some sort of Apis and a need a way to authenticate users when they interact with your apis.

 

Overview

The traditional process of interacting with a website is that you login from the login page. Next, you perform you desired actions and then log out. However, in the case of REST API, the process is quite different. The traditional procedure does not work in the case of RESTful APIs because the methods used on login page does not make any sense. You need to use api_token instead.

So you have to append the api_token with every api request and the request is authenticated. we will implement this in laravel with the help of the Passport library.

 

For demonstration purposes we will create a simple application in laravel in which can register and login.

Requirements

  • Laravel 5.5
  • PHP 7.0 or higher
  • MySQL

Laravel Passport

After install successfully Passport package in our Laravel application i need to set their Service Provider. so, open your config/app.php file and add following Line in the ‘providers’ array.

 

create the Database

Now go to mysql and create a new database then  in the project root, you will find the .env and config/database.php files. Add the database credentials (username, DB name, and password) to setup the database and allow the Laravel app access it.

Run the migrations

After set providers array now run the migration command

Install Laravel Passport

After Migrations of tables is successfully completed now run the install passport command

Configuration of  Passport

After install of Passport , next move to next Three step to configure it .

First open app/User.php file and update with following code.

Second go to the app/Providers/AuthServiceProvider.php  and update following code

Third update the config/auth.php with following code

Run Laravel Auth 

Set API Route

Go in routes folder and open api.php

Create the Controller

Now go to app/Http/Controllers/Api and open PassportController.php

Testing The App

Finally, run the php artisan server command and check application

Next to test our apis i will use Postman as a restful client.

Share this: