Set content security policy headers in a Laravel app
Set content security policy headers in a Laravel app
By default, all scripts on a webpage are allowed to send and fetch data to any site they want. This can be a security problem. Imagine one of your JavaScript dependencies sends all keystrokes, including passwords, to a third party website.
It's very easy for someone to hide this malicious behaviour, making it nearly impossible for you to detect it (unless you manually read all the JavaScript code on your site). For a better idea of why you really need to set content security policy headers, read this excellent blog post by David Gilbertson.
Setting Content Security Policy headers helps solve this problem. These headers dictate which sites your site is allowed to contact. This package makes it easy for you to set the right headers.
This readme does not aim to fully explain all the possible usages of CSP and its directives. We highly recommend that you read Mozilla's documentation on the Content Security Policy before using this package. Another good resource to learn about CSP, is this edition of the Larasec newsletter by Stephen Rees-Carter.
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
You can install the package via composer:
composer require spatie/laravel-cspYou can publish the config-file with:
php artisan vendor:publish --tag=csp-configThis is the contents of the file which will be published at config/csp.php:
…You can add CSP headers to all responses of your app by registering Spatie\Csp\AddCspHeaders::class as global middleware in bootstrap/app.php.
use Spatie\Csp\AddCspHeaders;
->withMiddleware(function (Middleware $middleware) {
$middleware->append(AddCspHeaders::class);
})Alternatively you can apply the middleware on the route or route group level.
// In your routes file
Route::get('my-page', 'MyController')
->middleware(AddCspHeaders::class);You can also pass a preset class as a parameter to the middleware:
// In your routes file
Route::get('my-page', 'MyController')
->middleware(AddCspHeaders::class . ':' . MyPreset::class);The given preset will override the ones configured in the config/csp.php config file for that specific route or group of routes.
Alternatively, you can register your CSP policies as a meta tag using our Blade directives.
{{-- app/layout.blade.php --}}
@cspMetaTag
This package ships with a few commonly used presets to get your started. We're happy to receive PRs for more services!
| Policy | Services |
|---|---|
Basic |
Allow requests to scripts, images… within the application |
AdobeFonts |
fonts.adobe.com (previously typekit.com) |
Alchemer Survey |
alchemer.com |
Algolia |
algolia.com |
Bootstrap |
getbootstrap.com |
Bunny Fonts |
fonts.bunny.net |
Chargebee |
chargebee.com |
Cloudflare Cdn |
cloudflare.com |
Cloudflare Turnstile |
cloudflare.com |
Cloudflare Web Analytics |
cloudflare.com |
Fathom |
usefathom.com |
Firebase |
firebase.google.com |
Google TLD's |
Allow all Google Top Level Domains for 'connect' and 'image' |
Google |
Google Analytics & Tag Manager |
GoogleAds |
ads.google.com |
GoogleFonts |
fonts.google.com |
GoogleLookerStudio |
lookerstudio.google.com |
GoogleMaps |
maps.google.com |
GoogleRecaptcha |
developers.google.com |
Hcaptcha |
hcaptcha.com |
Heap Analytics |
heap.io |
Hireroad |
hireroad.com |
Hotjar |
hotjar.com |
HubSpot |
hubspot.com (full suite) |
Intercom |
intercom.com |
JsDelivr |
jsdelivr.com |
JQuery |
jquery.com |
Maze |
maze.co |
Meta Pixel |
facebook.com |
Microsoft Clarity |
clarity.microsoft.com |
Plain |
plain.com |
Plausible Analytics |
plausible.io |
Posthog |
posthog.com |
Rollbar |
posthog.com |
Sentry |
sentry.io |
Stripe |
stripe.com |
SurveyMonkey |
surveymonkey.com |
ThereThere |
there-there.app (support bubble widget) |
TicketTailor |
tickettailor.com |
Tolt |
tolt.io |
TrackJS |
trackjs.com |
Vimeo |
vimeo.com |
Visual Website Optimizer |
vwo.com |
Whereby |
whereby.com |
Register the presets you want to use for your application in config/csp.php under the presets or report_only_presets key.
If you have app-specific needs or the service you're integrated isn't included in this package, you can create your own preset as explained below. You can also register global directives in the configuration file using a tuple notation.
'directives' => [
[Directive::SCRIPT, Keyword::UNSAFE_EVAL],
],
'report_only_directives' => [
[Directive::SCRIPT, Keyword::UNSAFE_INLINE],
],Here you may also create multiple directive & value combinations by padding multiple values in the tuple.
'directives' => [
[[Directive::SCRIPT, Directive::STYLE], [Keyword::UNSAFE_EVAL, Keyword::UNSAFE_INLINE]],
],An example of a CSP directive is script-src. If this has the value 'self' www.google.com then your site can only load scripts from its own domain or www.google.com. You'll find a list with all CSP directives at Mozilla's excellent developer site.
According to the spec certain directive values need to be surrounded by quotes. Examples of this are 'self', 'none' and 'unsafe-inline'. When using add function you're not required to surround the directive value with quotes manually. We will automatically add quotes. Script/style hashes, as well, will be auto-detected and surrounded with quotes.
public function configure(Policy $policy): void
{
$policy
// Will output `'self'` when outputting headers
->add(Directive::SCRIPT, Keyword::SELF)
// Will output `'sha256-hash'` when outputting headers
->add(Directive::STYLE, 'sha256-hash');
}You may also use the same keywords for multiple directives by passing an array of directives.
public function configure(Policy $policy): void
{
$policy->add([Directive::SCRIPT, DIRECTIVE::STYLE], 'www.google.com');
}Or multiple keywords for one or more directives.
public function configure(Policy $policy): void
{
$policy
->add(Directive::SCRIPT, [Keyword::UNSAFE_EVAL, Keyword::UNSAFE_INLINE])
->add([Directive::SCRIPT, DIRECTIVE::STYLE], ['www.google.com', 'analytics.google.com']);
}There are also a few cases where you don't have to or don't need to specify a value, eg. upgrade-insecure-requests, ... In this case you can use the following value:
public function configure(Policy $policy): void
{
$policy
->add(Directive::UPGRADE_INSECURE_REQUESTS, Value::NO_VALUE);
}This will output a CSP like this:
Content-Security-Policy: upNo open issues yet, or sync has not completed.