1
votes

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?

2
did you set the session domain in .env? I skimmed through both links but don't think I caught anything about session domains. Also, documentation is a 100 times better than those links. - user3532758
@user3532758 what do you mean? the SESSION_DOMAIN variable or SANCTUM_STATEFUL_DOMAINS? - ElendilTheTall
both needs to be set. laravel.com/docs/7.x/sanctum#cors-and-cookies domain here refers to SESSION_DOMAIN - user3532758
According to the docs, SESSION_DOMAIN only needs to be set if you're using a subdomain. Also, neither of the two methods I followed make any mention of it, from fresh installs. - ElendilTheTall
Try setting it, worth a shot, no? - user3532758

2 Answers

0
votes

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?

0
votes

I faced the same problem but when I replaced ->middleware('api') with ->middleware('web') it worked!!