HTTP Security Headers for Laravel Application

To add security headers to a Laravel application’s response, you can do this in multiple ways, depending on whether you want to apply these headers globally or to specific routes or controllers.

Method 1: Add Headers Globally via Middleware

Laravel allows you to create custom middleware to add headers to every response. Here’s how to do it:

  1. Create Middleware:

    You can create a new middleware using the Artisan command:

    php artisan make:middleware SecureHeaders
    
  2. Add Headers in Middleware:

    Open the newly created middleware file located at app/Http/Middleware/SecureHeaders.php and add the security headers:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class SecureHeaders
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $response = $next($request);
    
            // Add security headers
            $response->headers->set('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; style-src 'self' 'unsafe-inline' https:; img-src 'self' data: https:; font-src 'self' data: https:; connect-src 'self' https:; frame-src 'self' https:; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests; block-all-mixed-content;");
            $response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
            $response->headers->set('X-Frame-Options', 'SAMEORIGIN');
            $response->headers->set('X-Content-Type-Options', 'nosniff');
            $response->headers->set('X-XSS-Protection', '1; mode=block');
            $response->headers->set('Referrer-Policy', 'no-referrer, strict-origin-when-cross-origin');
            $response->headers->set('Permissions-Policy', 'geolocation=(), vibrate=(), payment=(), autoplay=(self)');
    
            return $response;
        }
    }
    
  3. Register Middleware:

    To apply this middleware globally, register it in the app/Http/Kernel.php file under the $middleware array:

    protected $middleware = [
        // Other middleware
        \App\Http\Middleware\SecureHeaders::class,
    ];
    

    If you want to apply it only to specific routes, you can register it under the $routeMiddleware array:

    protected $routeMiddleware = [
        // Other route middleware
        'secure.headers' => \App\Http/Middleware/SecureHeaders::class,
    ];
    

    Then, you can apply it to routes like this:

    Route::get('/example', function () {
        // Your route logic
    })->middleware('secure.headers');
    

Method 2: Add Headers in the Response Directly

If you only need to add headers for specific routes or controllers, you can add them directly in your controller methods:

public function index(Request $request)
{
    $response = response()->view('your.view');

    $response->headers->set('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https:; style-src 'self' 'unsafe-inline' https:; img-src 'self' data: https:; font-src 'self' data: https:; connect-src 'self' https:; frame-src 'self' https:; object-src 'none'; base-uri 'self'; form-action 'self'; upgrade-insecure-requests; block-all-mixed-content;");
    $response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
    $response->headers->set('X-Frame-Options', 'SAMEORIGIN');
    $response->headers->set('X-Content-Type-Options', 'nosniff');
    $response->headers->set('X-XSS-Protection', '1; mode=block');
    $response->headers->set('Referrer-Policy', 'no-referrer, strict-origin-when-cross-origin');
    $response->headers->set('Permissions-Policy', 'geolocation=(), vibrate=(), payment=(), autoplay=(self)');

    return $response;
}

Method 3: Use an Existing Package

You can also use a package like spatie/laravel-csp to manage CSP headers or bepsvpt/secure-headers for a broader range of security headers.

To install secure-headers, for example:

composer require bepsvpt/secure-headers

Then you can use it in your application:

use Bepsvpt\SecureHeaders\SecureHeaders;

public function index()
{
    SecureHeaders::fromConfig()->apply();

    return view('your.view');
}

Summary:

  • Method 1: Best for adding headers globally via middleware.
  • Method 2: Useful for specific routes or controller actions.
  • Method 3: Convenient if using third-party packages for comprehensive security headers.

Choose the method that best fits your application’s needs!

Related to: