Feb 24, 2022 by Zacharia Mansouri | 12035 views
No. Setting HTTPS is not enough to ensure that your cookies are encrypted. But Laravel proposes some very simple ways to achieve that.
As stated by OWASP, the cookie secure attribute is necessary to ensure that a cookie is sent over a secure connection (HTTPS) only. If it is sent over HTTP, the cookie is in clear text and therefore its content can be read by anyone who is able to observe your online activity. The secure attribute is a value in the cookie structure that has to be set to true in order to ensure that the cookie is encrypted over HTTPS requests only.
Modern versions of Laravel (tested with Laravel 8+) offers two simple ways to add that secure attribute to your cookies. Before showing how to do it, let’s discuss about the two types of cookie considered by Laravel:
Securing Session and XSRF-TOKEN cookies can be done with the following steps:
SESSION_SECURE_COOKIE=true
'secure' => env('SESSION_SECURE_COOKIE', true),
Tip: if your deployment uses Kubernetes, you probably use a deployment file (e.g. deploy.tmpl). If that is the case, you need to define your environment variable in that file too. It will be present in the data of your ConfigMap:
SESSION_SECURE_COOKIE: "true"
That is even easier ! In fact, you have nothing to do. When you activated the secure session, which is what we did in the previous section, then all your cookies are encrypted by default. Indeed, the file app/Http/Middleware/EncryptCookies.php is a middleware that gives you the possibility to choose the cookies you don’t want to be encrypted:
<?php
namespace AppHttpMiddleware;
use IlluminateCookieMiddlewareEncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
];
}
That middleware is called for each request since it is placed in the app/Http/Kernel.php file:
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareEncryptCookies::class,
...,
],
...,
];
Custom cookies will only be encrypted when HTTPS is used, which is logical since that is the whole purpose of the secure attribute. Here is the message shown in the Firefox console when you try to encrypt cookies over an HTTP connection:
In the Firefox Developer Mode, in the Storage tab, you can see the value of the cookies before and after setting the secure attribute:
Your cookies are now secured!
This blog post is licensed under CC BY-SA 4.0