menu

Managing Content Security Policies Through the Craft CMS Admin

Feb 03, 2022 by Jason McKinney

Tips


There are many ways to implement a content security policy on sites you develop. We were looking for a way that we could respond quickly when things change - like a client's marketing department decides to add a script to GTM in the middle of the night (it happens).

Leveraging Craft's fields and globals, we created a Matrix field with a block for each CSP parameter that was needed as well as a switch to toggle the policy:


along with the code below to deploy the inputs to the meta tag:

                    
                    .
{% if csp.cspEnable %}
    <meta http-equiv="Content-Security-Policy" content="
        {% set blocks = contentSecurityPolicy.contentSecurityPolicy.all() %}
        {% for block in blocks %}
             {% set name = block.type.name %}
             {{ name }} {{ block.sources }}; 
        {% endfor %}
    ">
{% endif %}
                    
                    


Or, you can deploy this code using the Craft header tag like so:

                    
                    .
{% if csp.cspEnable %}
    {% set cspArray = [] %}
    {% set blocks = csp.contentSecurityPolicy.all() %}
    {% for block in blocks %}
        {% set name = block.type.name %}
        {% set cspArray = cspArray|merge([name, block.sources ~ ";"]) %}
    {% endfor %}
    {% header "Content-Security-Policy: " ~ cspArray|join(' ') %}
{% endif %}
                    
                    

Hope this helps. As with all content in our "Tips" series, we invite you to share any ideas you have about this method so we can all help each other become better developers.