Skip to content

Instantly share code, notes, and snippets.

@rolandstarke
Last active September 7, 2024 17:48
Show Gist options
  • Save rolandstarke/926473f757dae1f6cc1c383cfb3d72df to your computer and use it in GitHub Desktop.
Save rolandstarke/926473f757dae1f6cc1c383cfb3d72df to your computer and use it in GitHub Desktop.
Laravel less cookies in response

Laravel less Cookies in Response

Laravel sends the session and csrf cookie in every response. That is additional trafic that's not needed. With this changes the session cookie and csrf cookie don't get resend to the client every time if they did not change (but at least once an hour to prevent client side expiring).

/*
replace
\Illuminate\Session\Middleware\StartSession::class
with
\App\Http\Middleware\StartSession::class
*/
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Contracts\Session\Session;
class StartSession extends \Illuminate\Session\Middleware\StartSession
{
/**
* After how many seconds the cookie should be resend to the client
*/
const COOKIE_RESEND_INTERVAL = 3600;
protected $request;
public function handle($request, \Closure $next)
{
$this->request = $request;
return parent::handle($request, $next);
}
/**
* Add the session cookie to the application response.
* But only if it was not set recently. (reduce cookie encryption and bandwith overhead)
*/
protected function addCookieToResponse(Response $response, Session $session)
{
$cookieSetTime = $session->get('session_cookie_set_time');
if (
$session->getId() !== $this->request->cookie($session->getName())
|| !$cookieSetTime
|| $cookieSetTime + self::COOKIE_RESEND_INTERVAL < time()
) {
$session->put('session_cookie_set_time', time());
parent::addCookieToResponse($response, $session);
}
}
}
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* After how many seconds the cookie should be resend to the client
*/
const COOKIE_RESEND_INTERVAL = 3600;
/**
* Indicates whether the XSRF-TOKEN cookie should be set on the response.
*
* @var bool
*/
protected $addHttpCookie = true;
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
];
protected function addCookieToResponse($request, $response)
{
$session = $request->session();
$cookieSetTime = $session->get('csrf_cookie_set_time');
if (
$request->session()->token() !== $request->cookie('XSRF-TOKEN')
|| !$cookieSetTime
|| $cookieSetTime + self::COOKIE_RESEND_INTERVAL < time()
) {
$session->put('csrf_cookie_set_time', time());
return parent::addCookieToResponse($request, $response);
}
return $response;
}
}
@hdwong
Copy link

hdwong commented Mar 8, 2023

GREAT JOB!

I would like to ask is there any security risk in doing this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment