Zubair Mohsin
Posted on February 11, 2020
Laravel adds two cookies by default when you create a fresh project.
- XSRF-TOKEN ( stores current CSRF token )
- laravel_session ( stores session data ). Read more
These cookies have encrypted data. Laravel takes care of encryption and decryption for us.
Where to find their implementation?
Laravel comes with many middlewares out of the box. You can see them in App/Http/Kernel.php
.
Two such middleware classes are:
\App\Http\Middleware\VerifyCsrfToken::class
\Illuminate\Session\Middleware\StartSession::class
VerifyCsrfToken::class
extend a base class of same name.
Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class
Above base class from framework contains the implementation fo XSRF-TOKEN cookie.
XSRF-TOKEN cookie implementation
/**
* Add the CSRF token to the response cookies.
*
* @param \Illuminate\Http\Request $request
* @param \Symfony\Component\HttpFoundation\Response $response
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function addCookieToResponse($request, $response)
{
$config = config('session');
if ($response instanceof Responsable) {
$response = $response->toResponse($request);
}
$response->headers->setCookie(
new Cookie(
'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']),
$config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
)
);
return $response;
}
Session cookie implementation
\Illuminate\Session\Middleware\StartSession::class
contains the same method as above.
/**
* Add the session cookie to the application response.
*
* @param \Symfony\Component\HttpFoundation\Response $response
* @param \Illuminate\Contracts\Session\Session $session
* @return void
*/
protected function addCookieToResponse(Response $response, Session $session)
{
if ($this->sessionIsPersistent($config = $this->manager->getSessionConfig())) {
$response->headers->setCookie(new Cookie(
$session->getName(), $session->getId(), $this->getCookieExpirationDate(),
$config['path'], $config['domain'], $config['secure'] ?? false,
$config['http_only'] ?? true, false, $config['same_site'] ?? null
));
}
}
Let me know if I missed a cookie 🍪 Happy coding with Laravel.
💖 💪 🙅 🚩
Zubair Mohsin
Posted on February 11, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.