Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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.

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
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
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

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

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

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant 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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Announcing Inertia 2.0: Redefining Frontend Development for Laravel image

Announcing Inertia 2.0: Redefining Frontend Development for Laravel

Read article
Converting Collections to Queries in Laravel Using toQuery() image

Converting Collections to Queries in Laravel Using toQuery()

Read article
Dynamic Page Updates with Laravel Blade Fragments image

Dynamic Page Updates with Laravel Blade Fragments

Read article
Using Fluent to Work With HTTP Client Responses in Laravel image

Using Fluent to Work With HTTP Client Responses in Laravel

Read article
Managing Concurrent Requests with Laravel Session Blocking image

Managing Concurrent Requests with Laravel Session Blocking

Read article
URI Parsing and Mutation in Laravel 11.35 image

URI Parsing and Mutation in Laravel 11.35

Read article