Posted on Updated on - Arjun

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.
(or)
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 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.
https://github.com/laravel/framework/blob/master/src/Illuminate/Auth/TokenGuard.php

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.

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.
  • Thanks for your post.
    I have a problem about the api_token.
    It’s… what if I want to add a expiry time to the token ?

DMCA.com Protection Status