Cause
In Adobe Commerce and Magento Open Source version 2.4.7 and later, CSP is configured in restrict-mode
, by default, for payment pages in the storefront and admin areas, and in report-only
mode for all other pages.
The corresponding CSP header does not contain the unsafe-inline
keyword inside the script-src
directive for payment pages. Also, only whitelisted inline scripts are allowed.
Solution
Users might see browser errors due to certain scripts being blocked because of CSP:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src
To fix this issue, you must either:
-
Whitelist the blocked scripts using the
SecureHtmlRenderer
class. -
Use the
CSPNonceProvider
class to allow scripts to be executed.
Adobe Commerce and Magento Open Source 2.4.7 and later include a Content Security Policy (CSP) nonce provider to facilitate the generation of unique nonce strings for each request. These nonce strings are then attached to the CSP header.Use the
generateNonce
function inMagento\Csp\Helper\CspNonceProvider
to obtain a nonce string.use Magento\Csp\Helper\CspNonceProvider; class MyClass { /** * @var CspNonceProvider */ private $cspNonceProvider; /** * @param CspNonceProvider $cspNonceProvider */ public function __construct(CspNonceProvider $cspNonceProvider) { $this->cspNonceProvider = $cspNonceProvider } /** * Get CSP Nonce * * @return String */ public function getNonce(): string { return $this->cspNonceProvider->generateNonce(); } }
-
Add a hash to your module’s
csp_whitelist.xml
file.