Security Tip: Laravel 11's Middleware Configuration

[Tip#74] Laravel 11 shifts the default middleware into the framework itself and exposes configuration through the bootstrap/app.php class.

Security Tip: Laravel 11's Middleware Configuration

We’re starting our new series on Laravel 11’s security features at the top of the Release Notes. The first security-related change that we come across is the restructure of the default app Middleware:

Previously, new Laravel applications included nine middleware. These middleware performed a variety of tasks such as authenticating requests, trimming input strings, and validating CSRF tokens.

In Laravel 11, these middleware have been moved into the framework itself, so that they do not add bulk to your application's structure. New methods for customizing the behaviour of these middleware have been added to the framework and may be invoked from your application's
`bootstrap/app.php` file.
->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(
        except: ['stripe/*']
    );
 
    $middleware->web(append: [
        EnsureUserIsSubscribed::class,
    ])
})

While this is great for reducing the amount of noise in the default app scaffolding, especially since most of these you won’t need to change in most apps, it does make it harder to find the security related middleware and make the changes you need to make.

To make it easier to know what’s available and what it does, here are the different middleware configuration methods currently available:

Disable Cookies Encryption

Laravel automatically encrypts cookie values to keep then secure. If you need to access them outside Laravel, you can disable encryption on specific values. (Laravel docs)

->withMiddleware(function (Middleware $middleware) {
    $middleware->encryptCookies(except: [
        'cookie_name',
    ]);
})

Disable CSRF Protection

Sometimes you need to disable CSRF protection on specific routes, such as webhooks or external APIs. (Laravel docs)

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateCsrfTokens(except: [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ]);
})

Excluding Parameters from Signed URL Validation

Social media sites, email newsletters, and analytics love tacking extra parameters onto URLs when users click on them, however these extra parameters can break signed URLs. To avoid this, you can specifically exclude these extra parameters from validation. (Laravel docs)

->withMiddleware(function (Middleware $middleware) {
    $middleware->validateSignatures(except: [
        'fbclid',
        'utm_campaign',
        'utm_content',
        'utm_medium',
        'utm_source',
        'utm_term',
    ]);
})

Configure Trusted Hosts & Proxies

It’s important to configure your trusted hosts and proxies to prevent forwarded host poisoning attacks from making malicious requests to your app. The most common example is triggering Password Reset emails that provide links to the attacker’s injected domain. (Laravel docs)

->withMiddleware(function (Middleware $middleware) {
    $middleware
        ->trustProxies(at: [
            '192.168.1.1',
            '192.168.1.2',
        ])
        ->trustHosts(
            at: ['laravel.test']
        );
})

Allow Specific Routes During Maintenance

Sometimes you need to allow specific routes to work while maintenance mode is enabled.

->withMiddleware(function (Middleware $middleware) {
    $middleware->preventRequestsDuringMaintenance(except: [
        'stripe/*',
    ]);
})

Enable API Throttling

It’s a good idea to enable sensible throttling on your API, to prevent abuse and malicious activity. (Laravel docs)

->withMiddleware(function (Middleware $middleware) {
    $middleware->throttleApi(limiter: 'api', redis: true);
})

Invalidate ‘web’ Sessions on Other Devices

As an additional layer of security, you can invalidate any active sessions on other devices, either via a button click or after a password change. (Laravel docs)

->withMiddleware(function (Middleware $middleware) {
    $middleware->authenticateSessions();
})

Phew! There were a few of those, but we’ve made it to the end.

I hope this serves as a useful reference - some of them aren’t fully documented (yet), and there isn’t a quick reference page.


🕵️
Worried about your app being hacked? Book in a Laravel Security Audit and Penetration Test! I can find the vulnerabilities before a hacker does, and help you fix them!
🥷
Learn to Think Like a Hacker with my hands-on practical security course: Practical Laravel Security!