amrnn90 / breeze-nuxt

An application / authentication starter kit frontend in Nuxt3 for Laravel Breeze.
MIT License
198 stars 33 forks source link

initCsrf is always called #15

Closed carlosvaldesweb closed 1 year ago

carlosvaldesweb commented 1 year ago

Hello, i'm looking that initCsrf function is called always, so if i make a post request e.g to /blogs, always first is called /sanctum/csrf-cookie. I think that CSRF route only should be called in login and register but i could be wrong. I want to develop a module where the user can save while he writes with a short debounce, so the user can make many requests while he is tipyng, i wouldn't like that if the user make 50 requests they be 100 by always make initCsrf. According laravel docs:

Laravel CSRF Docs

Laravel automatically generates a CSRF "token" for each active [user session](https://laravel.com/docs/10.x/session) managed by the application.

Sanctum docs

To authenticate your SPA, your SPA's "login" page should first make a request to the /sanctum/csrf-cookie endpoint to initialize CSRF protection for the application:

During this request, Laravel will set an XSRF-TOKEN cookie containing the current CSRF token. This token should then be passed in an X-XSRF-TOKEN header on subsequent requests

If we have e.g. forms or routes that we need to be protected if we are guest users, maybe we can use like this, to not use only in login and register:

if (
      process.client &&
      ["post", "delete", "put", "patch"].includes(
        options?.method?.toLowerCase() ?? "",
      ) &&
      !token
    ) {
      await initCsrf();
      token = useCookie(CSRF_COOKIE).value;
    }
amrnn90 commented 1 year ago

Thanks

amrnn90 commented 1 year ago

The reason it is necessary to sometimes make a csrf request after logging in is because the csrf cookie set by Laravel has an expiration date configured by Laravel's session lifetime (120 minutes by default). So if a user logged in, checked the "remember me" option, then closed his browser and returned after 2 hours, he is still logged in but the csrf token has expired by then.