Laravel API Token Authentication

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.

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.

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.

By Arjun

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

1 reply on “Laravel API Token Authentication”

Leave a Reply

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