何时重新生成会话 ID Laravel?

When Regenerate Session ID Laravel?

我正在构建一个带登录的应用程序,我已经阅读了有关使用 $request->session()->regenerate(); 重新生成会话 ID 的信息,但我不明白我应该在哪里使用它,有人可以解释我应该在何时何地使用它重新生成会话 ID?

https://laravel.com/docs/5.6/session#regenerating-the-session-id

如文档中所述,如果使用内置 LoginController 框架完成该部分,则无需重新生成会话 ID。

如果您使用的是自定义代码,当 password/username 验证成功时,您可以通过调用 $request->session()->regenerate()

手动生成会话 ID

如果您看到默认身份验证,那么您可以看到他们正在为每个登录身份验证重新生成会话。

protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        if ($response = $this->authenticated($request, $this->guard()->user())) {
            return $response;
        }

        return $request->wantsJson()
                    ? new JsonResponse([], 204)
                    : redirect()->intended($this->redirectPath());
    }

主要目的是重新生成会话 ID,通常是为了防止恶意用户利用会话 固定攻击 对您的应用程序进行攻击。

什么是会话固定?

Session Fixation is an attack that permits an attacker to hijack a valid user session. The attack explores a limitation in the way the web application manages the session ID, more specifically the vulnerable web application. When authenticating a user, it doesn’t assign a new session ID, making it possible to use an existent session ID. The attack consists of obtaining a valid session ID (e.g. by connecting to the application), inducing a user to authenticate himself with that session ID, and then hijacking the user-validated session by the knowledge of the used session ID. The attacker has to provide a legitimate Web application session ID and try to make the victim’s browser use it.

根据文档

Regenerating the session ID is often done in order to prevent malicious users from exploiting a session fixation attack on your application.

Laravel automatically regenerates the session ID during authentication if you are using one of the Laravel application starter kits or Laravel Fortify; however, if you need to manually regenerate the session ID, you may use the regenerate method:

$request->session()->regenerate(); If you need to regenerate the session ID and remove all data from the session in a single statement, you may use the invalidate method:

$request->session()->invalidate();

参考:https://laravel.com/docs/8.x/session

参考:https://owasp.org/www-community/attacks/Session_fixation

什么是会话? 在 Laravel 中,session 是一种参数传递机制,它使我们能够跨多个请求存储数据。会话允许我们跨应用程序跟踪访问者。 Laravel 使用基于驱动程序的系统进行会话管理,每个驱动程序都用于定义会话数据的存储位置。 Laravel 框架具有以下内置会话驱动程序 –

参考:https://laravel.com/docs/5.6/session#regenerating-the-session-id

参考:https://owasp.org/www-community/attacks/Session_fixation

参考:https://www.w3adda.com/laravel-tutorial/laravel-session