Blog

Solved: Content Security Policy Warnings in Magento 2

Sample Issue:

 

Solution:-

To resolve the we need to override the csp_whitelist.xml file present in the module_csp module.

To override, we need to create the custom module.

So let’s start creating it,

Step 1: Create Magento 2 Module Structure

1. Create the following folders in the magento project root directory (ex. – C:\xampp\htdocs\magento2):

  • app/code/Thecoachsmb
  • app/code/Thecoachsmb/Cspmodule

The Thecoachsmb folder is the module’s VendorName, and Cspmodule is the ModuleName.

Note: If you don’t have the code folder in your app directory, create it manually.

Now, create app/code/Thecoachsmb/Cspmodule/composer.json:

Contents would be:

{}

This file will be loaded by Composer every-time you run it even though we are not actually using Composer with our module.

Step 2: Declaration of Module

It is necessary to create etc folder and add the module.xml file in it

  app/code/Thecoachsmb/Cspmodule/etc/module.xml

Contents would be:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Thecoachsmb_Cspmodule" setup_version="1.0.0"> 
 </module> 
</config>

Step 3: Registration of Module

To register the module, create a registration.php file in the app/code/Thecoachsmb/Cspmodule/registration.php

Contents would be:

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
	\Magento\Framework\Component\ComponentRegistrar::MODULE,
	'Thecoachsmb_Cspmodule',
	__DIR__
);

Step 4: Activate the Module

Now its time to enable our module.

So lets run the command to enable our module:

php bin/magento module:enable Thecoachsmb_Cspmodule

Now that you have enabled the module first time, so you have to upgrade the database of the module by using this command line:

php bin/magento setup:upgrade

Step 5: Create csp_whitelist.xml to whitelist properties

In the file  app/code/Thecoachsmb/Cspmodule/etc/csp_whitelist.xml , write the content as below…

If you have error in the third party assets like css, js then add that domain name here. In my case, I am getting error in the third part css – https://cdnjs.cloudfare.com/ as sown in the above error.

 

Like this, you can add your third party urls / domains to csp_whitelist.xml.

Here are some of the third party urls for your reference…

After this, clear cache of magento2 by running below command.

php bin/magento cache:flush

That’s it..

Hope this helped, do comment below giving feedback.

Happy Learning !!

Thank You !!

Leave a Reply

Your email address will not be published. Required fields are marked *