Search code examples
laravelpostmanlaravel-8laravel-sanctum

SPA Authentication Issues with Sanctum and Postman


I'm currently trying to test an SPA using Laravel 8.19.0 and Postman 7.36.1 but I keep getting an "Unauthenticated" response from a route that's guarded by "auth:sanctum", even though I have logged in correctly.

As far as I can understand, I've followed the documentation fully at https://laravel.com/docs/8.x/sanctum in order to set Sanctum up to be used for SPA so I've done the following:

  • Installed Sanctum.
  • Published the Sanctum config.
  • Performed a migration.
  • Included the EnsureFrontendRequestsAreStateful middleware and 'EnsureFrontendRequestsAreStateful::class' to the Http Kernal.
  • Added my local domains (same top-level domain but 1 with the "test" sub domain and another with "api") to the "stateful domains" option in the Sanctum config file.
  • Set the "supports_credentials" option in the cors config to "true".
  • Set my top level domain, prefixed with a "." for the "domain" option in the session config.

Then, I've set Postman up using the guide at https://blog.codecourse.com/laravel-sanctum-airlock-with-postman/ so I've written a script to get the CSRF token from "/sanctum/csrf-cookie" then used said token as the value for the "X-XSRF-TOKEN" in the request header and I can succesfully log in. however, when I try to access a route afterwards that's guarded by the "auth:sanctum" guard, even with the referrer and 'X-XSRF-TOKEN' being set up in the request header I cannot access the route.

After debugging, I can see that $this->auth->guard($guard)->check() is returning false in the authenticate($request, array $guards) method where $guard = "sanctum" in \vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php on line 63 because $this->user() is null for the Illuminate\Auth\RequestGuard instance.

Any help or even ideas on things to check would be greatly appreciated as I'm unsure on what to do from here, short of spending a day digging deeper into the request guard object and its instantiation!

Thanks.


Solution

  • Issue has since been resolved and was caused by Postman only saving the "XSRF-TOKEN" and "laravel_session" cookies to the "test" subdomain after logging in (the login URL used this sub domain) and thus not passing them to the "api" subdomain when trying to access the route which was protected by "auth:sanctum". By adding the same cookies to the "api" subdomain via the "Manage Cookies" menu in Postman, the route can now be accessed as intended.