0
votes

I am trying to protect API routes with a bearer token using Laravel Sanctum.

I have added the middleware correctly for the route as follows in api.php. The api/me route is set to return auth()->user();

Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::post('/me', 'App\Http\Controllers\APIController@me');
});

To test this, I first login successfully and generate a bearer token, so that is working fine.

However, when I try to access the api/me route without the bearer token, it still displays the full user. It is not supposed to be allowing access to the route without a bearer token, why is it doing that?

I've searched for hours but no joy - does anyone have any insight?

1

1 Answers

0
votes

I'm just guessing here.. Did you "EnsureFrontendRequestAreStateful" in kernel.php? Because then Sanctum will use Session-Cookie based authentication. Sanctum will only use the bearer token if you authenticate third party apps, that don't run on your domain or subdomain.

If you don't want to use session-cookie based authentication for your SPA remove the "EnsureFrontendRequestsAreStateful" class from kernel.php. Now Sanctum will always use the bearer token for authentication.