For anyone having an Unauthenticated error, please ensure you follow these steps.
- Send a GET request to /sanctum/csrf-cookie
- Send a post request to web route /login to get authenticated
After this step, you will be successfully authenticated by auth:sanctum middleware in the WEB route or any resource route that needs CRSF token present.
[Why did this work]
Sending a GET request(empty request) to /sanctum/csrf-cookie
enables laravel to send the fresh set cookies command to your browser to set a fresh CRSF token which can be found in your cookies. Axios and most library send this fresh token as part of headers X-CSRF-TOKEN
by default, for regular ajax request, please include them explicitly in your headers or in form _token, else your SPA will still hit the 419(token expired) error
Other things to be aware of:
- Ensure your SESSION_DOMAIN is set to localhost
- SANCTUM_STATEFUL_DOMAIN is set to your sub domain/SPA with the port e.g localhost:8000
For the original question please ensure you maintain same domain. I mean use localhost for both. And set SANCTUM_STATEFUL_DOMAIN = localhost:4200
Edited
Also set SESSION_DRIVER