Wondering how to resolve “Unauthenticated error” while using Laravel Sanctum for SPA? We can help you.
At Bobcares, we offer solutions for every query, big and small, as a part of our Server Management Service.
Today, let’s take a look at how our Support Team help a customer deal with this error.
How to resolve “Unauthenticated error” while using Laravel Sanctum for SPA?
Usually, when making requests to routes wrapped within auth:sanctum middleware, you may get an unauthenticated error.
It is because of misconfigurations.
Today, let us see the steps followed by our Support Techs to resolve it.
- Firstly, make sure the laravel app is serving from localhost (127.0.0.1) by doing the good old php artisan serve.
Do not use virtual hosts because you cannot serve the front-end apps from the same virtual host.
- Then, check the port numbers of your front-end app. Usually, React app serves at http://localhost:3000 and Vue app serve from http://localhost:8080.
- It is necessary for the front-end app(s) and the laravel app to serve from the same domain — localhost in our case.
- Next, set sanctum stateful domains in .env file. These are the addresses of our front-end apps including the port numbers.
SANCTUM_STATEFUL_DOMAINS=localhost:8080,127.0.0.1:8080,localhost:3000,127.0.0.1:3000
- Then, set session domain in .env file. You need to change this at production to your domain name.
SESSION_DOMAIN=localhost
- Set paths and supports_credentails in cors.php The routes of web.php you wish to have access to in your front-end app should be added to the paths array.
‘paths’ => [‘api/*’, ‘login’, ‘register’, ‘otp/*’, ‘sanctum/csrf-cookie’],’supports_credentials’ => true,
- And finally, you should make requests from the front-end app to the localhost/api/other-route but not to 127.0.0.1/api/other-route using axios.
[Need a solution to another query? We are just a click away.]
Conclusion
Today, we saw steps followed by our Support Engineers in order to resolve “Unauthenticated error” while using Laravel Sanctum.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
0 Comments