Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions cheatsheets/Django_Security_Cheat_Sheet.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,45 @@ It is advisable to modify the default URL leading to the admin panel (example.co

In the default app folder within your project, locate the `urls.py` file managing the top-level URLs. Within the file, modify the `urlpatterns` variable, a list, so that the URL leading to `admin.site.urls` is different from "admin/". This approach adds an extra layer of security by obscuring the common endpoint used for administrative access.

## Content Security Policy

- Include the `django.middleware.csp.ContentSecurityPolicyMiddleware` module in the `MIDDLEWARE` setting in your project's `settings.py` to add CSP-related header to your responses ([documentation](https://docs.djangoproject.com/en/6.0/howto/csp/#basic-config)).
- Configure the CSP policies in settings.py using the `SECURE_CSP` parameter, for example:

```py
from django.utils.csp import CSP

SECURE_CSP = {
"default-src": [CSP.SELF],
"script-src": [CSP.SELF, CSP.NONCE],
"style-src": [CSP.SELF],
}
```

- Add the CSP context processor to your TEMPLATES setting. This will add the nonce to the context of all your Django templates:

```py
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {
"context_processors": [
# ...
"django.template.context_processors.csp",
],
},
},
]
```

- In your templates, add the [nonce](https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html#nonce-based) where it is needed:

```html
<script nonce="{{ csp_nonce }}">
// This JavaScript code will be allowed.
</script>
```

## Django's built-in command `check --deploy`

Django has built-in command [`check --deploy`](https://docs.djangoproject.com/en/stable/ref/django-admin/#cmdoption-check-deploy) for security checks. Example:
Expand Down