Content Security Policy problem when changing store views in Magento

I recently came across a problem with the store view switch caused by the default content security policies used by default.

When using different domains on store views you might notice that the redirect will not work when you chose a different store view in the language dropdown. This is caused by the content security policies that magento, by default, imposes when submitting a form.
To overcome this problem you have configure specific CSPs in your theme or module. For this, create file csp_whitelist.xml in your /etc folder.

Add all domains that you use on your store view to this whitelist like the example below:

<?xml version="1.0"?>
<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="form-action">
            <values>
                <value id="site-1" type="host">*.domain1.com</value>
                <value id="site-2" type="host">*.domain2.com</value>
                <value id="site-3" type="host">*.domain3.com</value>
            </values>
        </policy>
    </policies>
</csp_whitelist>

Note that the policy id in line 4 is set to form-action because this is actually how magento implements the store switch.

If you face this type of problem on other context you can refer to https://developer.adobe.com/commerce/php/development/security/content-security-policies/ where you see a list of all type of CSPs accepted by magento in the whitelist.

Leave a Reply

Your email address will not be published.