我们是否应该在注册之前先向 /sanctum/csrf-cookie 发出请求,以便在成功注册后登录用户?

Should we make a request to /sanctum/csrf-cookie first, before registration that logs in a user after a successful registration?

我的 SPA 与我的 laravel 应用程序在同一个存储库中,并且文档指出在使用 sanctum 时,您的 SPA 的“登录”页面应该首先向 /sanctum/csrf-cookie 端点发出请求以进行初始化应用程序的 CSRF 保护。 Link: https://laravel.com/docs/9.x/sanctum#spa-authenticating

就我而言,当我成功注册用户时,我不会将他们重定向到登录页面进行登录,而是重定向到他们的仪表板。因此,根据我对上述观点的理解,我认为我应该先向 /sanctum/csrf-cookie 端点发出请求,然后再向 register api 发出 post 请求,这样我们就有了登录用户免受 CSRF 攻击,但我不确定我是否正确解释了文本。

我的方法

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);
}

我进一步调查了这个问题,发现 /sanctum/csrf-cookie 端点实际上只有 return 一个 204 空内容。您可以在这里查看:

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

return new JsonResponse(null, 204);

文件中的注释是:

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

实际上,您可以从 SPA 调用任何 GET API 端点,它将 return CSRF cookie。基本上你只需要在调用任何 POST 端点之前调用一次 GET 端点,包括登录端点,它应该是 POST.

原因是当您为 SPA 调用 GET 端点时(使用相同的主机或相同的 sub-host),默认情况下 sanctum return 是一个 CSRF cookie。

因此,对于大多数用例,您可能不需要在登录前调用 /sanctum/csrf-cookie 端点,因为您可能在此之前已经调用了 GET 端点。但是,如果登录或任何其他 POST 端点是您调用的第一个端点,则您首先需要调用上述 GET 端点,以触发浏览器中 CSRF cookie 的存储。

文档对此不是很清楚我正在尝试提交 PR 来解决这个问题。