There was some discussion previously (see 
https://code.djangoproject.com/ticket/17419) of adding a JSON encoding 
filter to Django. This was rejected as being impossible (or very difficult) 
to do securely. However the requirement to embed JSON in an HTML page is 
quite a common one, and it's easy to get wrong and create XSS 
vulnerabilities. We should make it easy for people to do the right thing.

I propose a ``json`` tag (implementation 
here<https://gist.github.com/evansd/41ea9dfc90d87f6afde1>) 
which outputs the entire script element as well as the JSON data. By 
enforcing the context in which in the JSON is output, it's possible to 
escape it securely.

It would have two basic modes of operation. The first, and recommended, one 
would look like this:

{% json data id="initial-data" %}


and would produce HTML like this:

<script type="application/json" id="initial-data">
  {"foo": "bar"}
</script>


The resulting data would be accessed in JavaScript like this:

var el = document.getElementById('initial-data');
var initialData = JSON.parse(el.textContent || el.innerText);


This is compatible with a strict Content Security Policy which prohibits 
all in-page script execution and maintains a clean separation between 
passive data and executable code.

The second mode of operation would look like this:

{% json data var="initialData" %}


and would produce HTML like this:


<script type="application/javascript">
  var initialData = {"foo": "bar"};
</script>


This isn't compatible with strict CSP but it is perhaps simpler and more 
familiar to many developers, and not fundamentally insecure, so it should 
still be supported.

Of course, the key issue is whether this can be done securely. In the gist 
below is a proposed implementation with links to the sources I've used to 
ensure I'm escaping things correctly: 
https://gist.github.com/evansd/41ea9dfc90d87f6afde1

If people are happy with it then I can create a proper pull request with 
docs etc.

Thanks,

Dave

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at http://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/187d31c1-6b47-4fc5-adc0-1d93bf4d53fd%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to