Explore how to add CSP configuration to a custom Magento 2 module, including whitelisting external scripts and securing your storefront.
What is CSP in Magento 2?
CSP in module 2, i.e., Content Security Policy is a robust tool introduced to prevent attacks on your Magento 2 store that aims to offer an additional layer of Magento 2 security to detect and fight against Cross-Site Scripting (XSS) and related attacks, including card skimmers, session hijacking, clickjacking, and more.
Once configured, the application can enforce policies like these:
- Any resource, such as .js, .css, .jpg, or .ttf files, can only be loaded from the store’s domain
- Iframes can only include pages from the store itself
- Magento 2 AJAX requests can only be sent to the store
- Forms can only be sent to the store
- Only whitelisted inline scripts and styles can be compiled by the browser
Some domains have already been whitelisted for modules that require it. For instance if the Magento_Paypal the module is installed, www.paypal.com is already whitelisted for the script-src policy.
You can add a domain to the whitelist for a policy (like script-src, style-src, font-src and others) by adding a csp_whitelist.xml to your custom Magento 2 modules etc folder.
If you don’t know how to create a custom module so you can refer to this blog for a custom module.
1. CSP in module 2 Create a csp_whitelist.xml file in Vendor\Extension\etc
<?xml version="1.0"?>
<!--
/**
* Webkul_Tabs
* @category Webkul
* @package Webkul_Tabs
* @author Webkul
* @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
* @license https://store.webkul.com/license.html
*/
-->
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp:etc/csp_whitelist.xsd">
<policies>
<policy id="script-src">
<values>
<value id="stripe" type="host">js.stripe.com</value>
</values>
</policy>
<policy id="frame-src">
<values>
<value id="stripe" type="host">js.stripe.com</value>
</values>
</policy>
<policy id="connect-src">
<values>
<value id="purechat" type="host">api.purechat.com</value>
</values>
</policy>
</policies>
</csp_whitelist>
You may also check our Magento 2 tutorials and other Magento 2 security modules e.g Magento 2 Two Factor Authentication and Magento 2 Ddos
Happy Coding!

Be the first to comment.