3
votes

I'm using Laravel sanctum (former Airlock) and have a question about it. I read in the docs:

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

axios.get('/sanctum/csrf-cookie').then(response => {
// Login... }); 

Once CSRF protection has been initialized, you should make a POST request to the typical Laravel /login route. This /login route may be provided by the laravel/ui authentication scaffolding package.

Does this mean that for every request I make, I should first check if the cookie has already been set? Because let's say I have a user that registers. Before making the POST request to register a user I should first make a GET request to get the CSRF-Cookie from my backend and then make the POST request to register the user.

Now the user gets redirected to the login webpage and is asked to login. Does the frontend then first have to check if there's a CSRF-Cookie, and if there isn't should it first again make the GET request to get the cookie?

This last bit also confuses me, because when calling the register method a user doesn't actually get logged in so the user has to be redirect to the login page to log in with the credentials the user just filled in to register which for me seems like a bad user experience, right?

2

2 Answers

3
votes

When you get the csrf token, in the following request, laravel will update the token automatic, so you dont need focus this after axios.get('/sanctum/csrf-cookie').

3
votes

Once you hit axios.get('/sanctum/csrf-cookie') API, after that you don't have to hit it again and again for every request, Because this/sanctum/csrf-cookie will save the XSRF token on browser and Axios will send it with the request.

You can learn about it in detail in this video: https://www.youtube.com/watch?v=8Uwn5M6WTe0