I'm implementing Content Security Policy headers using the following policy
Content-Security-Policy: default-src 'self'
so will need to avoid inline script because it will not execute.
However, in the MVC application certain functionality such as editor templates use inline script. e.g. tinymce_jquery_full.cshtml
contains
$(function() {
$('#@ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)').tinymce({
...
What is a good way to include dynamic values in external .js
files when using a CSP?
My current thinking is one of two ways:
C# Generated JavaScript
Similar to the way JSONP works, except that in the URL I do not specify a call back - I simply pass the dynamic values. In each file that needs dynamic JavaScript I include a link such as
<script src="/script/Foo/bar"></script>
which hits ScriptController
's Foo
action which returns content of type text/javascript
inserting the dynamic value bar
. This strikes me as a reliable way, if a bit clunky and it kind of defeats some of the advantages of using a CSP in the first place (almost as easy to accidentally insert unencoded text and cause XSS as it is without a CSP).
Hidden Form Fields
Dynamic values are inserted into the page:
<input type="hidden" id="url" name="url" value"http:://www.example.com/" />
and these values are looked up in the external JavaScript files:
$('#url').val();
This will work, but it could be awkward if there are several dynamic controls on the page or if there are more than one control of the same type. The problem is how to efficiently match each .js
script to its hidden field(s).
Is there any better solution for this or are there any ready made frameworks I can make use of?