Posted by Arjun on Thursday 15th June 2017

Laravel API Token Authentication

Laravel 5.x Laravel 5.2 laravel 5.3 Laravel 5.4

If you want to create a simple REST API, secured by web tokens for your mobile application or angular based application, you could develop it with Laravel, with very simple steps.

In Laravel 5.2, Taylor Otwell introduced TokenGuard class which allows you to authenticate users with tokens.

In order to access the protected routes, you just have to make a request with a valid api_token, as a query string or via header, and then return the relevant information, as JSON.

How to Authenticate with API Token

Just follow the below simple steps.

1. Add an api_token column to user table. If your Laravel application is brand new, go to migration folder, update your user table migration file, by adding below line, run the migrations.
you can even add the api_token column manually to your user table.

 $table->string('api_token', 60)->unique();

For each user you have to generate random token upon successful login; update/insert it, in the api_token column of user table for the authenticated user.

2. To protect your routes, use the middleware called auth:api. Here :api means we are telling Laravel that we want to use the driver for the api guard which is set up in the config/auth.php and is defaulted to token.

// for single route 
Route::get('/users', ['uses' => '[email protected]', 'middleware' => 'auth:api']);

// for group of routes 
Route::group(['middleware' => 'auth:api'], function () {
    Route::get('/users', '[email protected]');

At this point, any routes wrapped with your auth:api middleware are only accessible to those that visit the route with a valid api_token in their request.

Example - http://localhost:8080/users?api_token=your_token

Getting the User

You can get current user by passing API to the guard method as shown below,


Link for Token Guard.