To set a Content Security Policy (CSP) header in a Laravel application, you can use middleware. Middleware allows you to modify the HTTP response before it is sent to the browser. Here's how you can create a middleware to set the Content-Security-Policy header:
-
Create a Middleware:
You can create a new middleware using the Artisan command:
php artisan make:middleware ContentSecurityPolicy -
Edit the Middleware:
Open the newly created middleware file located at
app/Http/Middleware/ContentSecurityPolicy.phpand modify thehandlemethod to add the CSP header:<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class ContentSecurityPolicy { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle(Request $request, Closure $next) { $response = $next($request); $response->headers->set('Content-Security-Policy', "frame-ancestors 'self' https://*.capgemini.com/;"); return $response; } } -
Register the Middleware:
You need to register your middleware in the
app/Http/Kernel.phpfile. You can add it to the$middlewarearray if you want it to apply to all requests, or to the$routeMiddlewarearray if you want to apply it to specific routes.For global application, add it to the
$middlewarearray:protected $middleware = [ // Other middleware \App\Http\Middleware\ContentSecurityPolicy::class, ];For specific routes, add it to the
$routeMiddlewarearray:protected $routeMiddleware = [ // Other route middleware 'csp' => \App\Http\Middleware\ContentSecurityPolicy::class, ];Then, apply it to routes in your
routes/web.phporroutes/api.php:Route::get('/example', function () { // Your route logic })->middleware('csp');
By following these steps, you will have successfully added a Content-Security-Policy header to your Laravel application. This header will instruct the browser to only allow framing from the specified sources.