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
Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes.

Visit Larafast: Laravel SaaS Starter Kit
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
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
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
DocuWriter.ai logo

DocuWriter.ai

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

DocuWriter.ai
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

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

Rector

The latest

View all →
Integrate Laravel with Stripe Connect Using This Package image

Integrate Laravel with Stripe Connect Using This Package

Read article
The Random package generates cryptographically secure random values image

The Random package generates cryptographically secure random values

Read article
Automatic Blade Formatting on Save in PhpStorm image

Automatic Blade Formatting on Save in PhpStorm

Read article
PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More image

PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More

Read article
Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released image

Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released

Read article
Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite image

Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite

Read article