Skip to content

Commit 19e4f28

Browse files
nicwortelOskarStark
authored andcommitted
[AssetMapper] Document how to make it work with a Content Security Policy
1 parent db902d6 commit 19e4f28

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

frontend/asset_mapper.rst

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1061,6 +1061,27 @@ have *one* importmap, so ``importmap()`` must be called exactly once.
10611061
If, for some reason, you want to execute *only* ``checkout.js``
10621062
and *not* ``app.js``, pass only ``checkout`` to ``importmap()``.
10631063

1064+
Using a Content Security Policy (CSP)
1065+
-------------------------------------
1066+
1067+
If you're using a `Content Security Policy`_ (CSP) to prevent cross-site
1068+
scripting attacks, the inline ``<script>`` tags rendered by the ``importmap()``
1069+
function will likely violate that policy and will not be executed by the browser.
1070+
1071+
To allow these scripts to run without disabling the security provided by
1072+
the CSP, you can generate a secure random string for every request (called
1073+
a *nonce*) and include it in the CSP header and in a ``nonce`` attribute on
1074+
the ``<script>`` tags.
1075+
The ``importmap()`` function accepts an optional second argument that can be
1076+
used to pass attributes to the rendered ``<script>`` tags.
1077+
You can use the `NelmioSecurityBundle`_ to generate the nonce and include
1078+
it in the CSP header, and then pass the same nonce to the Twig function:
1079+
1080+
.. code-block:: twig
1081+
1082+
{# the csp_nonce() function is defined by the NelmioSecurityBundle #}
1083+
{{ importmap('app', {'nonce': csp_nonce('script')}) }}
1084+
10641085
The AssetMapper Component Caching System in dev
10651086
-----------------------------------------------
10661087

@@ -1143,3 +1164,5 @@ command as part of your CI to be warned anytime a new vulnerability is found.
11431164
.. _`dist/css/bootstrap.min.css file`: https://www.jsdelivr.com/package/npm/bootstrap?tab=files&path=dist%2Fcss#tabRouteFiles
11441165
.. _`dynamic import`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import
11451166
.. _`package.json configuration file`: https://docs.npmjs.com/creating-a-package-json-file
1167+
.. _Content Security Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
1168+
.. _NelmioSecurityBundle: https://symfony.com/bundles/NelmioSecurityBundle/current/index.html#nonce-for-inline-script-handling

0 commit comments

Comments
 (0)