Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Implementing Content Security Policy in Django
📖 Scenario: You are building a Django web application that needs to be secure against common web attacks like cross-site scripting (XSS). To do this, you want to add a Content Security Policy (CSP) header to your HTTP responses.This policy will control which sources of content the browser is allowed to load, helping protect your users.
🎯 Goal: Learn how to set up a basic Content Security Policy in a Django project by adding middleware that sets the CSP header.You will create a simple CSP that allows content only from your own site and trusted sources.
📋 What You'll Learn
Create a Django middleware class that adds a Content-Security-Policy header
Define a CSP policy string that allows scripts and styles only from the same origin
Add the middleware to the Django settings
Verify the CSP header is included in HTTP responses
💡 Why This Matters
🌍 Real World
Content Security Policy helps protect websites from attacks like cross-site scripting by controlling which sources the browser can load content from.
💼 Career
Understanding how to implement CSP in Django is important for web developers focused on security and compliance with best practices.
Progress0 / 4 steps
1
Create a basic Django middleware class
Create a Django middleware class called ContentSecurityPolicyMiddleware in a file named middleware.py. The class should have an __init__ method that takes get_response and a __call__ method that returns the response unchanged.
Django
Hint
Remember, Django middleware classes have an __init__ method that takes get_response and a __call__ method that takes request and returns a response.
2
Define the Content Security Policy string
Inside the ContentSecurityPolicyMiddleware class, add a class variable called csp_policy and set it to the string "default-src 'self'; script-src 'self'; style-src 'self'".
Django
Hint
The CSP string controls which sources are allowed. Use default-src 'self' to allow content only from your own site.
3
Add the CSP header to the response
Modify the __call__ method in ContentSecurityPolicyMiddleware to add a header named Content-Security-Policy with the value of self.csp_policy to the response before returning it.
Django
Hint
Use response["Content-Security-Policy"] = self.csp_policy to set the header.
4
Add the middleware to Django settings
In your Django settings.py file, add the string 'yourapp.middleware.ContentSecurityPolicyMiddleware' to the MIDDLEWARE list. Place it near the top, after 'django.middleware.security.SecurityMiddleware'.
Django
Hint
Insert your middleware string into the MIDDLEWARE list in settings.py.
Practice
(1/5)
1. What is the main purpose of Content Security Policy (CSP) in a Django application?
easy
A. To handle database migrations automatically
B. To speed up the loading time of the website
C. To control which external resources can be loaded by the browser
D. To manage user authentication and sessions
Solution
Step 1: Understand CSP's role in security
CSP is designed to restrict what content the browser can load, preventing harmful scripts or resources.
Step 2: Identify the correct purpose among options
Only To control which external resources can be loaded by the browser describes controlling external resource loading, which matches CSP's function.
Final Answer:
To control which external resources can be loaded by the browser -> Option C
Quick Check:
CSP purpose = control resource loading [OK]
Hint: CSP controls resource loading to improve security [OK]
Common Mistakes:
Confusing CSP with performance optimization
Thinking CSP manages user sessions
Assuming CSP handles database tasks
2. Which of the following is the correct way to add a CSP header in a Django view?
easy
A. response.setHeader('Content-Security-Policy', "default-src 'self'")
B. response['headers']['Content-Security-Policy'] = "default-src 'self'"
C. response.set_header('Content-Security-Policy', "default-src 'self'")
D. response['Content-Security-Policy'] = "default-src 'self'"
Solution
Step 1: Recall Django HttpResponse header syntax
In Django, headers are set by assigning to response['Header-Name'].
Step 2: Match the correct syntax
response['Content-Security-Policy'] = "default-src 'self'" uses response['Content-Security-Policy'] = "default-src 'self'", which is correct Django syntax.
Final Answer:
response['Content-Security-Policy'] = "default-src 'self'" -> Option D
Quick Check:
Django header set = response['Header'] = value [OK]
Hint: Use response['Header-Name'] = value to set headers in Django [OK]
Common Mistakes:
Using JavaScript or Flask header syntax in Django
Calling non-existent methods like setHeader
Trying to set headers via response.headers dictionary
3. Given this Django middleware snippet, what CSP header will be sent in the response?
A. Inline scripts blocked; add 'unsafe-inline' to script-src directive
B. Header syntax error; remove quotes around 'self'
C. Missing HTTPS; change 'self' to https://self
D. No fix needed; inline scripts should work by default
Solution
Step 1: Understand CSP default-src effect on scripts
default-src 'self' blocks inline scripts by default because inline scripts are unsafe.
Step 2: Fix by allowing inline scripts explicitly
Adding 'unsafe-inline' to script-src directive allows inline scripts to run.
Final Answer:
Inline scripts blocked; add 'unsafe-inline' to script-src directive -> Option A
Quick Check:
Inline scripts need 'unsafe-inline' in CSP [OK]
Hint: Add 'unsafe-inline' to allow inline scripts in CSP [OK]
Common Mistakes:
Removing quotes around 'self' breaks CSP syntax
Changing 'self' to https://self is invalid
Assuming inline scripts work without explicit permission
5. You want to allow images from your own site and from https://images.example.com but block all other sources. Which CSP header directive is correct in Django?
hard
A. response['Content-Security-Policy'] = "img-src 'self' https://images.example.com; default-src 'none'"
B. response['Content-Security-Policy'] = "default-src 'self' https://images.example.com"
C. response['Content-Security-Policy'] = "img-src *; default-src 'self'"
D. response['Content-Security-Policy'] = "img-src 'none'; default-src https://images.example.com"
Solution
Step 1: Identify directives to allow images only from specific sources
img-src directive controls image sources; 'self' allows own site, plus https://images.example.com.
Step 2: Block all other sources by setting default-src to 'none'
default-src 'none' blocks everything else not explicitly allowed.
Final Answer:
response['Content-Security-Policy'] = "img-src 'self' https://images.example.com; default-src 'none'" -> Option A
Quick Check:
Allow images from self and example.com, block others [OK]
Hint: Use img-src for images and default-src 'none' to block others [OK]
Common Mistakes:
Using default-src for images allows too many sources