Nelutu Fona
Nelutu Fona

Reputation: 569

How to authenticate API requests in Laravel?

I am currently building some sort of posts based web application using Laravel 5(.4). I have decided to load asynchronously the comment section for each post(and refresh it periodically). After some research I have decided to write a small integrated REST API (using the api routes of Laravel) that should answer to the requests made through AJAX.
However, I am facing the problem if authenticating the incoming requests. Take for example a request to post some comment. How exactly would you recommend to do that?

Upvotes: 0

Views: 1815

Answers (2)

Shahzaib Sheikh
Shahzaib Sheikh

Reputation: 667

If you are making AJAX requests from browser and you are signed in then you don't need to use Laravel Passport tokens. You can define certain routes which will be using web,auth middleware on requests like webapi/comments/get like this.

Route::group(['middleware' => ['web','auth]], function () {
        Route::get('webapi/comments/get', 'CommentsController@get');
}

And use Auth Facade as you do in web request i.e Auth::check(), Auth::user() etc. and return the data in JSON like this.

class CommentsController extends Controller
{
    public function get(Request $request)
    {
         if($request->acceptsJson()){
            $data = array();

            // add data

            return response()->json([
                   "data"=> $data,
                   "status" => true
                  ]);
         }else{
            return abort(404);
         }

    }
}

You can also send Accept header in AJAX request as application/json and in controller check if request $request->acceptsJson() and make your decision to show content when url is loaded from browser address bar or requested as AJAX.

Laravel Passport token are useful where there is no session and cookies are managed.

hope this helps :)

Upvotes: 1

Nelutu Fona
Nelutu Fona

Reputation: 569

"Passport includes an authentication guard that will validate access tokens on incoming requests. Once you have configured the api guard to use the passport driver, you only need to specify the auth:api middleware on any routes that require a valid access token" - from the Laraven Documentation.
Apparently I have to configure passport, and after that configure the auth:api middleware to use the passport driver. Correct me if I'm wrong, please :)

Upvotes: 0

Related Questions