It appears our use of document.write
in the ScriptTagHelper
to dynamically load JS files in to the browser (the CDN fallback feature) causes issues when trying to use Content Security Policy.
It appears this could be somewhat addressed by switching to dynamically creating and appending script
elements to the DOM (assuming the CSP policy that enables inline script blocks is enabled), however that results in the scripts being loaded asynchronously to the page rendering, which potentially causes errors in the page (e.g. if the scripts now run out of order to how they were declared).
This article is a good write-up of the various methods that can be used to load scripts while controlling (or not) their execution order and they're affect on rendering.
We should investigate whether we could enhance the ScriptTagHelper
to better support these techniques, along with CSP, e.g.:
async
attribute on the script
element when dynamically loading the fallback script, maybe even use it as part of the download method toggle (always use document.write
unless async
attribute is explicitly set, or something)Possible example that would render inline JS to do async downloads of the scripts while preserving their declared execution order:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"
asp-fallback-src="~/lib/jquery/jquery.min.js"
async asp-preserve-load-order></script>
<script src="~/js/needs-jquery.js" async asp-preserve-load-order></script>
@DamianEdwards I assume this isn't for RTW?
Ya.
Ideally, any possible solution that relies on inline scripts should discourage the use of the unsafe-
CSP directives by supporting either CSP script-src nonces or hashes or both.
Allowing the user to specify the nonce via an attribute (asp-fallback-nonce
maybe?) and rendering that attribute in the generated script would unblock the CSP use-case.
This is also an issue for the validation summary emitting style="display:none"
.
Hi,
What is the solution to validation summary emitting style="display:none"
that brock mentions above?
Thanks
Mike
Instead of document.write, could the tag helper emit document.body.insertAjacentHTML('beforeend', ... ) or similar, to allow the scenario where the script tag is contained within an Ajax response (e.g. when calling jQuery.load)?
Let's handle this as part of our broader CSP story tracked by https://github.com/aspnet/AspNetCore/issues/6001
Most helpful comment
This is also an issue for the validation summary emitting
style="display:none"
.