Django, CSP: How to activate Nonce in scripts for Admin pages

Viewed 27

At my page scripts are only executed, when the nonce tag is included (because of CSP settings).

That causes at the admin pages, that scripts are not working.

Therefore I am overwriting now all the admin templates, for example from:

<script src="{% static 'admin/js/nav_sidebar.js' %}" defer></script>

to

<script src="{% static 'admin/js/nav_sidebar.js' %}" nonce="{{request.csp_nonce}}" defer></script>

Is there an easier way to do this? Deactivate CSP on the admin pages or somehow tell Django to add Nonce to all scripts?

Thanks

2 Answers

Ok I could also add all script hashes to CSP, that is also working. But maybe there is also another solution?

Here's a quickie I just figured out that may help you. It doesn't fix the root problem in the original which is resources missing a nonce, but you can add a second reference to the resource that includes the nonce (assumes all your CSP setup is working). Given the example below of calendar.js, it'll be referenced in the HTML twice. The first will generate the CSP error, but the second will work. Your console will be a bit messy but all your nonce'd stuff will work again.

  1. In your base templates directory, add another directory called admin
  2. There, create a file called base.html, i.e. templates/admin/base.html. It is in here you'll add additional stuff.

That's it.

The additional stuff inside your local templates/admin/base.html:

{% extends "admin/base.html" %}
{% load static %}

{% block extrastyle %}
<script nonce="{{request.csp_nonce}}" src="/static/admin/js/calendar.js"></script>

<!-- whatever else you need with a nonce -->

{% endblock %}
Related