Reputation: 1452
I have now followed two separate methods for using Laravel Sanctum for authentication in my Laravel 7/Vue SPA. Both have run into the same problem. Here are the methods:
https://blog.codecourse.com/setting-up-laravel-sanctum-airlock-for-spa-authentication-with-vue/
https://dev.to/aschmelyun/authenticating-a-vue-spa-is-easy-with-laravel-sanctum-392a
Both do much the same thing - install Sanctum, install the standard auth scaffolding, set up the middleware, add a dummy user or two. Then, use Axios to hit the sanctum/csrf-cookie
route, then the /login
routes, passing in an email and password.
However, with both methods, I get the same issue - a 401 'Unauthenticated' error. The Network tab of the browser dev tools shows that the sanctum/csrf-cookie route
returns 204 and the Laravel session and XSRF cookies are set. The login
route shows 302 and a redirect to /home which is the standard Laravel auth redirect. Then when it hits the route defined in the api.php file:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
It returns 401 - Unauthenticated.
Now, the only thing that makes this work seemingly as intended is tweaking the mapApiRoutes() function in RouteServiceProvider.php:
protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}
Changing the middleware property from 'api' to 'web' fixes the issue. But that seems to be a complete bodge and something that I shouldn't need to do.
I have followed both methods to the letter - all the domains, middleware etc are set up exactly the same in both cases.
Any ideas?
Upvotes: 1
Views: 5478
Reputation: 113
I faced the same problem but when I replaced
->middleware('api')
with ->middleware('web')
it worked!!
Upvotes: 1
Reputation: 1348
The Laravel api
guard works based on a token, not on the session. It looks like you have three guards in place: web
, api
and sanctum
. Could it be that you're logging in on web
or api
, while still requiring authentication through the sanctum
guard as well?
Upvotes: 0