Reputation: 2975
I am using Sanctum for SPA authentication. In several examples I have seen, people are creating auth routes (login, logout, register) in their web.php
routes file as opposed to the api.php
routes file. Is there a reason for this? In the documentation I do see a mention here...
You may be wondering why we suggest that you authenticate the routes within your application's routes/web.php file using the sanctum guard. Remember, Sanctum will first attempt to authenticate incoming requests using Laravel's typical session authentication cookie. If that cookie is not present then Sanctum will attempt to authenticate the request using a token in the request's Authorization header. In addition, authenticating all requests using Sanctum ensures that we may always call the tokenCan method on the currently authenticated user instance
...but that is for API Token Authentication and not directly under SPA Authentication.
Is there any reason my auth routes would be better handled in web.php
?
Upvotes: 2
Views: 1137
Reputation: 16339
Well, in a typical Laravel application, your API routes are stateless and do not persist a session; specifically they do not have the start session middleware.
As such, cookie based authentication will not work if you put these routes in your API file.
Having these routes in your web file allows these specific routes to be wrapped in a session, allowing cookie based authentication and then falls back to using the stateless Authorization header if required.
I forget the exact words, but Taylor is quite a fan of SPAs using cookie based authentication when they're the same domain over API tokens.
But this should explain the reasoning. You are, of course, welcome to change this if you like.
Upvotes: 5