Simple Api Authentication For Laravel

Sometimes, when you are creating a web app, you might want to create some routes for your API.

Laravel fortunately, laravel makes this easy by shipping with a routes/web.php and routes.api.php file.

The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.

The api middleware helps you to guard your api routes and you can easily guard multiple routes by defining as follows: Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); Or Route::middleware('auth:api')->group(function(){

Route::get(‘users’, “UserController@index”);

Route::post(‘users’, “UserContoller@save”); Route::get(‘home’, function(){ return ‘something’; }); });

After creating and setting up your routes and it’s guard, now you’ll need to authenticate users making calls to your API. You might possibly want to use Laravel Passport or other sophisticated means of authentication, but the purpose of this tutorial is to show you a simple method and still relatively secure.

Step 1:

Add an api_token column to your users table

$table->string(‘api_token’)

You can fill this column manually or create a random string for every new user signing up

Tip: str_random(60)

Step 2:

On every call to your api routes, add the query parameter ?api_token=[your_api_token] and laravel will automatically compare the token to the one in the database

It’s that simple.


Originally published at sdktalks.blogspot.com on July 14, 2017.

Like what you read? Give Elusoji Sodeeq a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.