Have you installed and configured Passport? https://laravel.com/docs/5.5/passport
Protecting API routes with session guard
I'm using Laravel 5.4 and trying to protect an API route with a session guard but I keep getting 401 Unauthorized errors.
In the frontend app I'm doing my AJAX request like this:
import axios from 'axios';
axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': window.csrf_token
};
axios.post('/api/do_thing');
In the backend, I have set the API guard to be session:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'session',
'provider' => 'users',
],
],
And protected my route with the API sesion guard.
Route::post('/api/do_thing', function() { ... })->middleware('auth:api');
By my reckoning, laravel_session cookie gets sent with the AJAX request and should therefore pass the auth check. But I get a 401, any idea why?
Follow up question: what is the downside to using session guard for an API? Why is token/passport preferred?
I figured it out. The API routes don't have the required middleware to use session cookies. This answer explains it: https://laravel.io/forum/02-09-2016-52-ajax-auth-not-picking-up-session
Please or to participate in this conversation.