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
Tinkerwell

Version 4 of Tinkerwell is available now. Get the most popular PHP scratchpad with all its new features and simplify your development workflow today.

Visit Tinkerwell
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
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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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 Vue and Livewire 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 →
Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4 image

Create a DateTime from a Timestamp With this New Method Coming to PHP 8.4

Read article
Neovim Plugin to for Navigating Laravel and Livewire Components image

Neovim Plugin to for Navigating Laravel and Livewire Components

Read article
Laravel Herd v1.7 is out with updates to the dump UI image

Laravel Herd v1.7 is out with updates to the dump UI

Read article
Share Error Package for Laravel's New Exception Page image

Share Error Package for Laravel's New Exception Page

Read article
Sentry and Laravel announce a new partnership image

Sentry and Laravel announce a new partnership

Read article
"Fast Projects" by Larafast: Real life, ready to use Laravel based Boilerplates image

"Fast Projects" by Larafast: Real life, ready to use Laravel based Boilerplates

Read article