Laravel Security Middleware

Published on by

Laravel Security Middleware image

Middleware isn't something new. We have been using it in our applications for quite a while now for various usages, from Authentication, to Authorization and beyond.

In this tutorial, I will walk through how you can leverage the power of middleware in your Laravel application to help increase the security of your applications. You can add countless headers to your application, which do different things. Let's dive into a few different security headers to see what they do - and what I like to do in my applications.

The first thing we want to do when thinking about security in our Laravel application is think about the headers we do not want to expose. Typically your application will reveal the following headers by default: X-Powered-By - this will display the tech stack your application is powered by. server/Server - this will reveal the server technology running your application. For example, apache or nginx etc.

The first thing we want to do here is to remove these headers.

I work for a company called Treblle, which is like Google Analytics for your API. We are releasing a new API Security check soon, and I have open-sourced the middleware we use to hide specific headers. It looks like the following:

final class RemoveHeaders
{
public function handle(Request $request, Closure $next): Response
{
/**
* @var Response $response
*/
$response = $next($request);
 
/**
* @var string $header
*/
foreach ((array) config('headers.remove') as $header) {
$response->headers->remove(
key: $header,
);
}
 
return $response;
}
}

This middleware goes through the configured headers in my config file and ensures they are removed from the response before returning it to the user.

The next thing I typically do here is set the Referrer-Policy header to no-referrer-when-downgrade when the request returns to the same origin - but not for any cross-origin requests. I do this using another piece of middleware:

final class SetReferrerPolicy
{
public function handle(Request $request, Closure $next): Response
{
/**
* @var Response $response
*/
$response = $next($request);
 
$response->headers->set(
key: 'Referrer-Policy',
values: config('headers.referrer-policy),
);
 
return $response;
}
}

I split these actions into separate middleware classes so that I can be specific about the level that is important to me regarding security in each route. I want to be more open for some routes, while I want them to be slightly less open for others.

Let's talk about the Strict-Transport-Security header for a moment. This will tell the client/browser to connect to our application using HTTPS and how long this rule should be in place. This header helps to protect your application users from man-in-the-middle attacks. You can also add the includeSubdomains to this header, telling the browser to apply this policy to all website subdomains.

final class StrictTransportSecurity
{
public function handle(Request $request, \Closure $next): Response
{
/**
* @var Response $response
*/
$response = $next($request);
 
$response->headers->set(
key: 'Strict-Transport-Security',
values: config('headers.strict-transport-security'),
);
 
return $response;
}
}

The following header I like to look at is the Content-Security-Policy header, one of the more commonly used ones. I did not create custom middleware for this one, as Spatie has a fantastic package you can use. The Laravel News article linked has excellent instructions on how to set this up, so I will not go through the specifics for this one. So let's move on.

Your SSL certificate can have different transparency levels for your users. This public logging mechanism will allow anyone to monitor certificate issuance. This will help detect and prevent things such as fake certificates. It also has various configuration options: max-age will specify the maximum time (in seconds) for which the browser should remember the policy. enforce will specify if you want the browser to enforce the policy. If we set this to true, the browser will not allow no-SSL connections to your application. report-uri will specify the URL where the browser should send any reports about violations of your application's CT policy. Let's look at the middleware for this and see what we want to do:

final class CertificateTransparencyPolicy
{
public function handle(Request $request, \Closure $next): Response
{
/**
* @var Response $response
*/
$response = $next($request);
 
$response->headers->set(
key: 'Expect-CT',
values: config('headers.certificate-transparency'),
);
 
return $response;
}
}

As you can see, some of these middleware classes are simple. The combination of them will give you the best protection against potential attacks.

The last middleware we want to look at is the Permissions-Policy header. We can use this header to tell the browser what features and APIs the browser is allowed to use. This will help protect you against things such as XSS attacks and click-jacking.

final class PermissionsPolicy
{
public function handle(Request $request, \Closure $next): Response
{
/**
* @var Response $response
*/
$response = $next($request);
 
$response->headers->set(
key: 'Permissions-Policy',
values: config('headers.permissions-policy'),
);
 
return $response;
}
}

Using this middleware, I can be particular about the features I want to enable, meaning that I can ensure more safety for my end user and myself.

Another great package you can check out is Laravel Security Headers by Rob Fonseca.

Do you have any additional middleware that you use? Or maybe a specific setting for one of the ones listed? Let us know on Twitter!

Steve McDougall photo

Technical writer at Laravel News, Developer Advocate at Treblle. API specialist, veteran PHP/Laravel engineer. YouTube livestreamer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Forge
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
Bacancy - Staff Augmentation logo

Bacancy - Staff Augmentation

Leave your web app development hustles to the leading IT Staff Augmentation Service Providers. Choose from an extensive pool of 1050+ developers and give yourself the sigh of success you deserve with Bacancy. Get In Touch Today!

Bacancy - Staff Augmentation
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Add Architecture Tests to Saloon API Integrations with Lawman image

Add Architecture Tests to Saloon API Integrations with Lawman

Read article
Protect Routes with JWT Tokens Using This Package for Laravel image

Protect Routes with JWT Tokens Using This Package for Laravel

Read article
Increment a Rate Limiter by a Custom Amount in Laravel 10.46 image

Increment a Rate Limiter by a Custom Amount in Laravel 10.46

Read article
Add Kanban Boards to Your Laravel App in Seconds image

Add Kanban Boards to Your Laravel App in Seconds

Read article
October CMS v3.6 Ships Today, Full of New Features image

October CMS v3.6 Ships Today, Full of New Features

Read article
Laracon EU Videos are now out image

Laracon EU Videos are now out

Read article