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.

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.

0 0 vote
Article Rating
Notify of
1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
3 years ago

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 ? Protection Status
Would love your thoughts, please comment.x