I would like to use Content Security Policy and make my Django web application safe without any unsafe inline code. But while it is easy to move most of the JavaScript code to external files, I also have a segment of inline code which I do not know fix. I am using Django and I have some variables in Django template context which I want to pqww to JavaScript. So currently I simply output that as inline JavaScript. But this does not work because of CSP.
<script type="text/javascript">
/* <![CDATA[ */
var documentURL = '{% filter escapejs %}{{ document.get_document_url }}{% endfilter %}';
/* ]]> */
</script>
To put the comments in answer form and add a little...
The easiest way to do this is generate a tag with an attribute set. I don't know django so I'll just leave it in plain html:
<input type="hidden" id="mything" value="<MY VALUE>">
When I have multiple, related values I might throw them into the same element:
<span class="hidden" data-attribute1="<VALUE1>" data-attribute2="<VALUE2>">
<!-- rename 'attributeN' to something meaningful obviously -->
In either case, just read the values with JS (using jquery for brevity)
$('#mything').data("attribute1")
Or if you need a complex object, throw it in a span as html entity escaped data:
<span class="hidden" id="data-container">
<your html-escaped JSON>
</span>
And read it in the external file with:
var myObject = JSON.parse($('#data-container').html());
This is also describe at https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.233.1_-_HTML_escape_JSON_values_in_an_HTML_context_and_read_the_data_with_JSON.parse
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With