Last active
December 21, 2022 13:44
-
-
Save jonleverrier/6aa958a5a66a8b146e214e619578538f to your computer and use it in GitHub Desktop.
A way of setting the Content Security Policy header in Craft CMS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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>"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.