Home > Back-end >  Should we make a request to /sanctum/csrf-cookie first, before registration that logs in a user afte
Should we make a request to /sanctum/csrf-cookie first, before registration that logs in a user afte

Time:05-13

My SPA is in the same repository as my laravel application and the documentation states that when using sanctum, your SPA's "login" page should first make a request to the /sanctum/csrf-cookie endpoint to initialize CSRF protection for the application. Link: https://laravel.com/docs/9.x/sanctum#spa-authenticating

In my case, When I register a user successfully I'm not redirecting them to the login page to log in but rather to their dashboard. So, in my understanding going by the point above, I think I should first make a request to the /sanctum/csrf-cookie endpoint as well before making a post request to the register api so that we have a logged-in user that is protected from CSRF attacks but I'm not that sure if I'm interpreting the text correctly.

my method

public function register(Request $request){
    $fields = $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:users,email', 
        'password' => 'required|confirmed',
    ]);

    $fields['password'] = bcrypt($fields['password']);
    $user = User::create($fields);
    auth()->login($user);
}

CodePudding user response:

I investigated this issue further and found that the /sanctum/csrf-cookie endpoint actually only returns a 204 empty content. You can check here:

https://github.com/laravel/sanctum/blob/5a602d520474e103174900301d7b791e6d7cd953/src/Http/Controllers/CsrfCookieController.php#L12

return new JsonResponse(null, 204);

And the comment in the file says:

Return an empty response simply to trigger the storage of the CSRF cookie in the browser.

Actually you can call any GET API endpoint from your SPA and it will return the CSRF cookie. Basically you just need to have called a GET endpoint once before calling any POST endpoint, including the login endpoint, which should be POST.

The reason for this is that sanctum by default returns a CSRF cookie when you call a GET endpoint for SPAs (using same host or same sub-host).

So for most use cases out there you might not need to call the /sanctum/csrf-cookie endpoint before login, because you might have already called a GET endpoint before that. However if the login, or any other POST endpoint is the first one you are calling, you first need to call the above GET endpoint just to trigger the storage of the CSRF cookie in the browser.

The docs are not so clear on this I am trying to submit a PR to clear this up.

  • Related