Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jonleverrier
Last active December 21, 2022 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonleverrier/6aa958a5a66a8b146e214e619578538f to your computer and use it in GitHub Desktop.
Save jonleverrier/6aa958a5a66a8b146e214e619578538f to your computer and use it in GitHub Desktop.
A way of setting the Content Security Policy header in Craft CMS
<?php
// https://jonleverrier.com/notes/weeknote-2
// - If the request is not from the control panel
// - If the request is not from the console
// - If a user is not logged in (for debug toolbar in the front-end)
if (
!Craft::$app->request->isCpRequest &&
!Craft::$app->request->isConsoleRequest &&
!Craft::$app->getUser()->getIdentity()
)
{
// Add CSP header
Craft::$app->response->headers->add("Content-Security-Policy", "<your_policy_goes_here>");
}
@jamesmacwhite
Copy link

jamesmacwhite commented Dec 21, 2022

Perhaps check if the request is a site request is a better cleaner condition. Not sure why you wouldn't want to set the policy on a logged in user. Just because they are logged in, doesn't mean they can be trusted and something like a CSP should apply regardless.

if (Craft::$app->getRequest()->getIsSiteRequest()) {
    Craft::$app->getResponse()->getHeaders()->add("Content-Security-Policy", "<your_policy_goes_here>");
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment