Skip to content

Commit ee67304

Browse files
committed
Document how to make AssetMapper work with a Content Security Policy
1 parent 455402b commit ee67304

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

frontend/asset_mapper.rst

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1011,6 +1011,26 @@ you pass to ``importmap()``.
10111011
because ``app`` appears in your ``importmap.php``, the browser will read ``app``
10121012
from the ``importmap`` on the page and ultimately load ``/assets/app-4e986c1a2318dd050b1d47.js``
10131013

1014+
Using a Content Security Policy (CSP)
1015+
-------------------------------------
1016+
1017+
If you're using a `Content Security Policy`_ (CSP) to prevent cross-site
1018+
scripting attacks, the inline ``<script>`` tags rendered by the ``importmap()``
1019+
function will likely violate that policy and will not be executed by the browser.
1020+
1021+
To allow these scripts to run without disabling the security provided by
1022+
the CSP, you can can generate a secure random string for every request (called
1023+
a *nonce*) and include it in the CSP header and in a ``nonce`` attribute on
1024+
the ``<script>`` tags.
1025+
The ``importmap()`` function accepts an optional second argument that can be
1026+
used to pass attributes to the rendered ``<script>`` tags.
1027+
You can use the `NelmioSecurityBundle`_ to generate the nonce and include
1028+
it in the CSP header, and then pass the same nonce to the Twig function:
1029+
1030+
.. code-block:: html+twig
1031+
1032+
{{ importmap('app', {'nonce': csp_nonce('script')}) }}
1033+
10141034
The AssetMapper Component Caching System in dev
10151035
-----------------------------------------------
10161036

@@ -1053,3 +1073,5 @@ This will force the AssetMapper component to re-calculate the content of all fil
10531073
.. _EasyAdminBundle: https://github.com/EasyCorp/EasyAdminBundle
10541074
.. _symfonycasts/tailwind-bundle: https://symfony.com/bundles/TailwindBundle/current/index.html
10551075
.. _symfonycasts/sass-bundle: https://symfony.com/bundles/SassBundle/current/index.html
1076+
.. _Content Security Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
1077+
.. _NelmioSecurityBundle: https://symfony.com/bundles/NelmioSecurityBundle/current/index.html#nonce-for-inline-script-handling

0 commit comments

Comments
 (0)