0
0
Djangoframework~5 mins

Content Security Policy in Django

Choose your learning style9 modes available
Introduction

Content Security Policy (CSP) helps keep your Django website safe by controlling what content can load. It stops bad scripts or files from running.

When you want to stop hackers from injecting harmful scripts into your site.
When you want to control which external resources like images or fonts your site can use.
When you want to improve your site's security by reducing risks of cross-site scripting (XSS).
When you want to report violations of your content rules to monitor attacks.
When you want to make sure only trusted sources provide content to your users.
Syntax
Django
Content-Security-Policy: <directive> <source-list>; <directive> <source-list>; ...

Directives define types of content like scripts, images, styles.

Source lists specify allowed URLs or keywords like 'self' or 'none'.

Examples
This policy allows content only from your own site, images from a specific domain, and blocks all scripts.
Django
Content-Security-Policy: default-src 'self'; img-src https://images.example.com; script-src 'none';
This allows styles from your site and inline styles (needed for some CSS frameworks).
Django
Content-Security-Policy: default-src 'self'; style-src 'self' 'unsafe-inline';
This blocks all content except connections to your site and a trusted API.
Django
Content-Security-Policy: default-src 'none'; connect-src 'self' https://api.example.com;
Sample Program

This Django view sends a simple HTML response with a Content Security Policy header. It allows content only from the same site, images from a trusted domain, and blocks all scripts.

Django
from django.http import HttpResponse

def my_view(request):
    response = HttpResponse("<h1>Hello, secure world!</h1>")
    csp_policy = "default-src 'self'; img-src https://images.example.com; script-src 'none';"
    response['Content-Security-Policy'] = csp_policy
    return response
OutputSuccess
Important Notes

Always test your CSP carefully to avoid blocking needed content.

You can use browser developer tools to see CSP violations and fix them.

Use 'report-uri' or 'report-to' directives to get reports about policy violations.

Summary

CSP helps protect your Django site by controlling what content loads.

Set CSP headers in your views or middleware to enforce rules.

Use clear directives and test to keep your site secure and working well.