How to Whitelist Inline Script for CSP | Content Security Policies

Content Security Policy is an extra layer of security to reduce attacks of Cross-Site Scripting. Magento supports CSP from Magento 2.3.5 version. Magento_Csp native module has logic in Magento to manage the CSP. In Magento, if you want to whitelist any script and style then you can easily do it by creating one file csp_whitelist.xml under your custom module’s \etc directory and then you can add any script and style to that file and that script and style which will be bypassed from CSP. Click here to check the csp_whitelist.xml sample file.

But what to do if you want to whitelist any inline or custom script, which will be added from the Magento admin or any dynamic URL which you can not add directly under the csp_whitelist.xml file? For that, Magento provides a way to whitelist the script from the PHTML file. here we show you how to do this.

How to whitelist dynamic URL of script for CSP in Magento 2

//inline_js.phtm
<?php
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>

<?= /* @noEscape */ $secureRenderer->renderTag('script', ['scr' => 'https://YOUR_SCRIPT_URL_HERE.JS'], false) ?>

Now you can simply call the above phtml file to any front-end page and that will include that script on that page. For example, if you want to add this script to the checkout page then you can do something like the below.

Create checkout_index_index.xml file under your custom modules /view/frontend/layout/ directory and then add the below code.

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
		<referenceBlock name="head.additional">
			<block name="vish.inline.script.test" template="Dhairvi_Test::inline_js.phtml" before="-"/>
		</referenceBlock>
    </body>
</page>

Using this trick, you can add any script or style. You can also fetch any JavaScript URL from the Magento admin system configuration values or you can also fetch URL value from any custom code or file. So I think using this way you can whitelist any script.