user3743266 user3743266 - 1 year ago 94
Ajax Question

Laravel api routes with auth

I'm trying to make an api route that's only accessible if the user making the request is logged in. This is what I have in my

but it returns

Route::group(['middleware' => ['auth:api'], function () {
Route::post('schedules', ['uses' => 'Api\ScheduleController@store']);

Can this be done without laravel passport and how? I only need the route for in-app use for logged in users.

Answer Source

I assumed the login mentioned is on "web" which using "session" as driver.

Your are getting this issue because "web" and "api" guard is using different driver for authentication. Take a look in config/auth.php. The "api" guard is using "token" as it's default driver.

Thus, you have few options to encounter this.

  1. Move the route for "schedules" in web.php. No worry, your ajax will failed if not authenticated. But, take note that anything that involved POST method will require csrf (_token parameter), unless you are using laravel axios
  2. Using authentication using api also which you can refer this tutorial for "token" driver and all your secure routes will be using token in its Authentication header
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download