A Chang's avatar

Sanctum login route in routes/api.php or routes/web.php?

I am manually implementing login for Sanctum SPA (AngularJS) app and based on the Sanctum documentation, I need to "If authentication is successful, you should regenerate the user's session to prevent session fixation"

Since routes/api.php is "Stateless and token based", do I need to define the login routes in routes/web.php only?

Thanks

0 likes
2 replies
fylzero's avatar

It really doesn't matter since your auth post routes will not be beneath auth middleware regardless if you are adding the login pages to your SPA or logging in with Blade pages to an SPA.

It just becomes sort of a preference as to whether you want said routes to be prepended with /api

Personally, I add them to the web.php since that is how Jetstream and Laravel/UI have their auth routes setup.

1 like
ks217's avatar

I also have been feeling confused about api.php vs web.php when writing login routes manually.

Some differences I found by testing from Postman are:

(A) When using routes/api.php:

  1. The login routes work if I skip both Origin,X-XSRF-TOKEN headers from Postman. I was expecting this to throw a 419 error. I am not sure if I should be concerned about this for using in production?

  2. These login routes work as long as the controller is not using session in the code. Since api routes are stateless, any usage of $request->session or Session:: throws an exception Session store not set on request.

  3. I was under the impression that since we add EnsureFrontendRequestsAreStateful middleware to 'api' above 2 issues should not happen.

(B) When using routes/web.php:

  1. The login routes dont work without 'X-XSRF-TOKEN' header. Which is great.

(C) In both cases:

  1. Routes within auth:sanctum guard work without 'X-XSRF-TOKEN' header as long as request has the authenticated session cookie (by default laravel_session). I was under the impression X-XSRF-TOKEN should be present with each request?

I feel I am missing some concept about this CSRF setup for an SPA. Please correct me wherever needed. TIA.

Please or to participate in this conversation.