dhanashri dhanashri - 3 months ago 9
reST (reStructuredText) Question

How to authenticate RESTful API in Laravel 5.2?

I created RESTful API in Laravel 5.2. I need to authenticate everytime a user accesses AbcController. I created my routes as below:

Route::group(['prefix' => 'user'], function () {
Route::post('login', 'Auth\AuthController@authenticate');
Route::post('register', 'UserController@userRegister');
Route::post('register', 'UserController@userRegister');
});

Route::group(['prefix' => 'abc'], function () {
Route::get('abclists', 'AbcController@movieLists');
Route::get('upcoming', 'AbcController@upcomingMovieLists');
});


When user registers for the first time or logs-in, at that time I create random 64 bit char string for session token. This session token is stored in a different table. Now I am confused how to check if a user is logged in or not in AbcController. I am not using any library for this. Please suggest how to reslove this problem.

Answer

The easiest way to do this would be to use middleware. In the handle() method you can make the check against the token stored in the table.

<?php

namespace App\Http\Middleware;

class AgeMiddleware
{

    public function handle($request)
    {
        if(TOKEN == $request->get('token')
        return $next($request);
    }

}

You can look here for more info: Laravel Docs