Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Adding WYSIWYG editor to Django Project
Next article icon

Adding CSP headers in Django Project

Last Updated : 31 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Website security has been an important factor while developing websites and web applications. Many frameworks come with their own security policies and developers also try to implement the utmost security policies while developing their applications. Still even after this much hard work hackers will find new ways to penetrate into our app, exploit our code to vulnerabilities. In this article, we are going to implement a security header often referred to as CSP headers to a Django application.

Terminology

  • CSP: Content-Security-Policy is an HTTP response header that modern browsers use to enhance the security of the web page by allowing you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads.
  • HTTP header: HTTP headers let the client and the server pass additional information with an HTTP request or response like MIME type, request status code, cookie, and proxy information, and more
  • XSS: Also abbreviated as Cross Side Scripting, XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users in simple words if exploited can change the look and behavior of the webpage
  • Django: Django is a python based web application framework used to build a variety of web apps

What is Content Security Policy?

Content-Security-Policy is an HTTP response header that modern browsers use to enhance the security of the web page by allowing you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads are designed to prevent XSS attacks which enable attackers to inject client-side scripts into web pages viewed by other users in simple words if exploited can change look and behavior of webpage. It is also called the successor of X-Content-Security-Policy or X-Webkit-CSP headers. CSP can also be implemented using the meta tag.

Some CSP header terminology is

  • default-src: the default source to load everything
  • style-src: source to load styles
  • script-src: source to load javascript or generally scripts
  • img-src: source to load images
  • object-src: source to load media
  • report-to: URI to send reports for violating CSP
  • 'self': load from the same host
  • 'unsafe-inline': allow inline styles and scripts
  • 'unsafe-eval': allows eval() and similar methods for creating code from strings
  • 'nonce': a random string that should be unique per request

How does the Content Security policy work?

CSP works by blocking the execution of styles, scripts, and other things unless they are allowed in the policy. CSP doesn't allow execution of inline scripts and styles which means we can't use <script/> and <style/> tags for javascript and styling.

An example of CSP headers is

Content-Security-Policy: default-src 'self'; style-src: 'self' stakpath.bootstrapcdn.com; script 'self' *.cloudflare.com; img-src 'self' imgur.com;

In this CSP header, we are telling the browser that the default source for all the styles, scripts, images, objects should be the domain that is passed in the header, along with that we are also allowing stylesheet from stackpath.bootstrapcdn.com which is CDN for bootstrap styles. We are also allowing scripts to be loaded from all Cloudflare subdomains using wildcard subdomain and for images, the browser can allow loading from imgur.com. Apart from these if the webpage tries to load from other domains like twitter the browser will block the requests.

Implementing CSP headers in Django

Django doesn't come with CSP headers in its core but thanks to Mozilla, they have created a package Django-CSP to add CSP headers.

# installing django-csp pip3 install django-csp

add CSP to middleware in our setting.py file of the Django project and then we will configure our headers

Python3
MIDDLEWARE = (     # ...     'csp.middleware.CSPMiddleware',     # ... ) 

Configuring CSP headers

Go to the settings file of the Django project and add the following in the last or anywhere you want

Python3
# uri to report policy violations # uri to report policy violations CSP_REPORT_URI = '<add your reporting uri>'   # default source as self CSP_DEFAULT_SRC = ("'self'", )   # style from our domain and bootstrapcdn CSP_STYLE_SRC = ("'self'",       "stackpath.bootstrapcdn.com")   # scripts from our domain and other domains CSP_SCRIPT_SRC = ("'self'",      "ajax.cloudflare.com",      "static.cloudflareinsights.com",      "www.google-analytics.com",      "ssl.google-analytics.com",      "cdn.ampproject.org",      "www.googletagservices.com",      "pagead2.googlesyndication.com")   # images from our domain and other domains CSP_IMG_SRC = ("'self'",      "www.google-analytics.com",      "raw.githubusercontent.com",      "googleads.g.doubleclick.net")   # loading manifest, workers, frames, etc CSP_FONT_SRC = ("'self'", ) CSP_CONNECT_SRC = ("'self'",       "www.google-analytics.com" ) CSP_OBJECT_SRC = ("'self'", ) CSP_BASE_URI = ("'self'", ) CSP_FRAME_ANCESTORS = ("'self'", ) CSP_FORM_ACTION = ("'self'", ) CSP_INCLUDE_NONCE_IN = ('script-src', ) CSP_MANIFEST_SRC = ("'self'", ) CSP_WORKER_SRC = ("'self'", ) CSP_MEDIA_SRC = ("'self'", ) 

You can add the required hostname according to your needs

Instructions to add CSP Header settings in Django Project

Here are some instructions to perfectly implement CSP in your web apps

  • Try to avoid adding unnecessary hostnames
  • Check as many times as possible while adding or removing hostnames
  • Until absolutely necessary don't add 'unsafe-inline', it will weaken our security policy
  • Try to avoid inline style and scripts
  • It is better not to use CSP in the development server right from the start
  • Always try to use HTTPS while loading scripts, styles, images.

Next Article
Adding WYSIWYG editor to Django Project
author
kushwanthreddy
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Web Technologies
  • Technical Scripter 2020
  • Python Django
Practice Tags :
  • python

Similar Reads

  • Adding Permission in API - Django REST Framework
    There are many different scenarios to consider when it comes to access control. Allowing unauthorized access to risky operations or restricted areas results in a massive vulnerability. This highlights the importance of adding permissions in APIs.   Django REST framework allows us to leverage permiss
    7 min read
  • Adding WYSIWYG editor to Django Project
    Often, to manage content efficiently we use WYSIWYG (What You See Is What You Get) editor which stores our content in html and is also helpful to upload images, creating links, lists and works almost like Wordpress editor. This article is in continuation of Blog CMS Project in Django. Check this out
    3 min read
  • How to enable CORS headers in your Django Project?
    When site A wants to access content from another site B, it is called a Cross-Origin request. As it is disabled for security reasons, B sends an Access-Control-Allow-Origin header in the response. By default, a domain is not allowed to access an API hosted on another domain. If we want to allow our
    1 min read
  • How to Override CSS in Django Admin?
    Django's admin interface is a powerful tool for managing application data. It comes with a default styling that may not always fit the visual identity of your project. Customizing the admin interface can help create a more cohesive user experience. In this article, we'll walk you through the process
    3 min read
  • How to add AMP to Django Project?
    A blog mostly needs content but that doesn't mean, your blog will be on top of Google search. For this you will need Speed, Security, user base and first of all search engines need to know that your blog exists. We will add AMP for speed.  This article is in continuation of Blog CMS Project in Djang
    4 min read
  • Adding Pagination in APIs - Django REST Framework
    Imagine you have huge amount of details in your database. Do you think that it is wise to retrieve all at once while making an HTTP GET request? Here comes the importance of the Django REST framework pagination feature. It facilitates splitting the large result set into individual pages of data for
    8 min read
  • How to create a Django project?
    Dive into the world of web development with Python by exploring the versatile Django framework. Django is a go-to for many developers due to its popularity, open-source license, and robust security features. It enables fast and efficient project development. In this tutorial, we will guide you throu
    5 min read
  • How to add Pagination in Django Project?
    Pagination system is one of the most common features in  blogs, search engine , list of result etc. Seeing the popularity of pagination system django developers have build a Paginator class so that web developers do not have to think of the logic to make paginators.  Paginator Class live in django/c
    5 min read
  • Clone and Run a Django Project from Github
    In this article, we will learn how to download any project from GitHub and deploy it to our local machine. You can clone any code or project from GitHub but for this article, we are cloning our Django project. What is GitHub?GitHub is an online platform where we can share our codes(or projects) onli
    2 min read
  • Django Introduction | Set 2 (Creating a Project)
    Note- This article is in continuation of Django introduction.  Popularity of Django Django is used in many popular sites like as: Disqus, Instagram, Knight Foundation, MacArthur Foundation, Mozilla, National Geographic etc. There are more than 5k online sites based on Django framework. ( Source ) Si
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences