Cookies are small blocks of data that are created by web servers while users are browsing a website. These are placed by the web browser on the user’s computer., where they remain until they expire or are deleted. Cookies are useful for authentication processes, as well as for storing information about user preferences for a site. There can be more than one cookie on the user’s device during a session. Read more about cookies here. In general, it is assumed that the HTTPS protocol is sufficient to encrypt cookies. In the event that this is not true, how can cookies be secured? Laravel proposes very straightforward ways to accomplish it. 

HTTPS is the only recommended way to make use of the cookie secure attribute. This makes sure that a cookie is passed through a secure connection. HTTP does not have a secure connection and cookies passed over it can be accessed easily by anyone.

In this article, we will explain how you can secure cookies with Laravel.

What is Laravel?

Laravel is a cross-platform PHP framework for building robust web applications. It has a large library of pre-programmed functionality. Developers can access this library and build web applications quickly as the amount of coding required is limited.

It provides developers with a highly functional development environment and uses object-relational mapping to simplify data access and manipulation. It also allows you to create applications that are highly scalable, and have easy-to-maintain codebases

Globally, over 36576 companies have adopted Laravel as a programming framework in 2022. Laravel is used most often by companies in the United States with 12490 customers. The United States accounts for 24.69% of Laravel customers. Other countries that are highly using Laravel are India with 4713 (9.32%) and the United Kingdom with 3917 (7.74%) customers. Most companies now hire Laravel developers for their specific projects. 

Understanding Laravel Cookies

A Laravel cookie helper can be used to create cookies. It is an example of Symfony\Component\HttpFoundation\Cookie. You can attach the cookie to the response by using the withCookie() method. The response will be created as an instance of the Illuminate\Http\Response class to call the withCookie() method. Cookies which are generated by Laravel are fully encrypted and signed. These cookies cannot be modified nor can they be read by the client.

Let’s look at this with a sample code:

laravel cookies sample code

There are three arguments that will be passed to Cookie(). In the first argument, we provide the name of the cookie, in the second argument, we provide its value, and in the third argument, we provide its duration.

In the code below, the “forever” method is used to set cookies forever.

setting cookies forever

The latest versions of Laravel offer you two simple and effective methods to add attributes that are secure to your cookies. Let us discuss two cookie types considered by Laravel before discussing how you can do it:

  • Custom Cookies 

These are all the cookies you add (consent, language, etc). They are used to track users or improve the user experience.

  • Session & XSRF-TOKEN cookies 

Session cookies contain data about a user’s session, including the user’s ID and the time of the last request. These cookies are essential because HTTP applications are stateless; they do not store information from previous visits to the site. The XSRF-TOKEN is passed along with each request to counter Cross-site Request Forgery (XSRF) attacks.

Why is it important to make cookies secure?

Web applications utilize the client-server model and hence they are stateless. Hence, sessions are used in order to persist data from one request to another request. One of the most common methods which is used to identify a session is the creation of a unique session ID. This ID is obviously stored on the server. This is done either in a database or directly on the filesystem. But the question that arises here is in what way will this be stored when it comes to the client side? This is where the role of cookies comes in. 

Most websites utilize cookies as a mode of identifier for sessions that are user based. This is because other modes of identifying web users come with few vulnerabilities and limitations. If any website utilizes cookies as a mode to identify sessions, attackers will have the ease of impersonating users’ requests. They do this by stealing an entire set of victims’ cookies. When looked at from the point of view of a web server, requests from an attacker have the same authentication as requests from a victim; thus, the attack is undertaken on behalf of the victim.

Hence, it is very important that cookies are made secure. 

How to secure Session and XSRF-TOKEN cookies with Laravel?

You can secure your session and the XSRF-TOKEN cookies by following the below-mentioned ways:

  • Announce the value of the SESSION_SECURE_COOKIE environment variable as true in your .env file as below:
SESSION_SECURE_COOKIE=true
  • Once done, look for the ‘secure’ key in the config/session.php file. Once you find it, all you have to do is set the key to the value of your formerly defined SESSION_SECURE_COOKIE variable as below:
secure cookies with laravel

How to Secure custom cookies with Laravel? 

We’ve discussed how to secure the session and XSRF-TOKEN cookies. What about cookies that have a custom script? The procedure to secure such cookies is even simpler.

Once you have activated the session that is secure (like mentioned in the above point), all your cookies are already encrypted by the system by default. There are no additional steps required to secure your custom cookies. However, if you’re wondering if there is a way to select cookies that should not be encrypted, yes, there is. The file App/Http/Middleware/EncryptCookies.php is a middleware which allows you to exclude certain cookies from being encrypted.

<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
   /**
    * The names of the cookies that should not be encrypted.
    *
    * @var array
    */
   protected $except = [
   ];
}

Every time a request is received, that middleware is invoked. This is because it is positioned in the app/Http/Kernel.php file.

/**
 * The applications' route middleware groups
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
       \App\Http\Middleware\EncryptCookies::class,
       ...,
    ],
    ...,
];

Key points to consider for securing custom cookies:

  • You can only encrypt custom cookies whenever HTTPS is utilized, which makes use of the secure attribute. If you make an attempt to encrypt cookies through an HTTP connection, you will receive the message:
 Cookie "lang" has been rejected because a non-HTTPS cookie can't be set as "secure"
  • Before and after setting the secure attribute, you can check the cookie values in Firefox Developer Mode’s Storage tab.

You can follow the above steps to secure cookies with Laravel. And if you’re looking to develop a web application with Laravel and secure it, connect with the best Laravel web development company and let your ideas turn into reality. 

Frequently asked questions

Is the session of Laravel secure?

With Laravel, you can encrypt data with AES-256 and AES-128 using the OpenSSL library. Laravel uses a Message Authentication Code (MAC) to ensure that encrypted values cannot be modified by unauthorized and unwanted parties.

Is Laravel safer and more secure than PHP?

Because of the Laravel security features, this framework is comparatively more secure when compared with other PHP frameworks.

What kind of encryption does Laravel make use of?

Laravel’s encrypter makes use of OpenSSL in order to provide  AES-128 and AES-256 encryption. It is strongly recommended that you do not try to roll your own encryption algorithms and instead use Laravel’s built-in encryption facilities.

Author bio: A marketer, developer and expert in the Internet of Things, ChatBot, and blockchain technologies, Harikrishna Kundariya is the cofounder of eSparkBiz Technologies and serves as its Director. With over ten years of experience in the field, he provides digital solutions to new start-ups based on IoT and ChatBot.

Disclaimer: This guest article is for general informational purposes only and should not be relied upon as legal or professional advice. The views expressed in this article are the guest author’s own and do not necessarily reflect those of CookieLawInfo, which will not be held liable for any inaccuracy. We do not endorse any products or services mentioned in the article.