MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
CSRF Protection0%
Study Materials
Django for Backend DevelopmentProgress 0%
1.1Installing Django & Environment Setup1.2Django Project Structure1.3Creating First Django App
7.1Custom Middleware7.2CSRF Protection7.3Security Best Practices
HomeTutorialsDjango for Backend DevelopmentCSRF Protection
Security Best Practices

CSRF Protection

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Cross-Site Request Forgery (CSRF) is a critical web security vulnerability where a malicious third-party site tricks an authenticated user's browser into executing unauthorized mutations (e.g. changing passwords, transferring funds, or updating records) on a trusted application. Django includes an industry-leading, built-in CSRF defense framework.


1. How CSRF Attacks Work

11. User logs into https://bank.enterprise.com (Session cookie is set in browser)
22. In another tab, user visits https://malicious-site.com
33. Malicious site automatically submits hidden form:
4 <form action="https://bank.enterprise.com/transfer" method="POST">
5 <input name="amount" value="5000" />
6 <input name="to_account" value="attacker_id" />
7 </form>
84. Browser automatically attaches bank.enterprise.com cookies!
95. Without CSRF tokens: Bank executes unauthorized transfer!

2. Django's Defense: Synchronizer Token Pattern

Django stops CSRF using cryptographically secure Synchronizer Tokens:

  • The server generates a unique secret token bound to the user's session or cookie.
  • Every mutating HTML form must embed this token.
  • CsrfViewMiddleware verifies that the submitted token matches the secret cookie. An attacker on an external domain cannot read or forge the token!

In HTML Templates:

Every <form method="POST"> must include {% csrf_token %}:

1<form method="POST" action="{% url 'articles:create' %}">
2 {% csrf_token %} {# Injects hidden <input type="hidden" name="csrfmiddlewaretoken" value="..." /> #}
3 <input type="text" name="title" required />
4 <button type="submit">Publish</button>
5</form>

If the token is missing or invalid on a POST request, Django immediately aborts and returns 403 Forbidden (CSRF verification failed).


3. Handling CSRF in AJAX & SPA Frontends (React / Axios)

Single Page Applications (React, Vue) sending JSON requests (application/json) cannot use HTML form inputs. Instead, Django places the CSRF token in a readable cookie (csrftoken), which the frontend sends in the X-CSRFToken HTTP header:

1# config/settings.py
2# Set cookie to be accessible by client JavaScript for AJAX/React:
3CSRF_COOKIE_HTTPONLY = False
4CSRF_COOKIE_SAMESITE = "Lax"

In React / Axios:

1import axios from "axios";
2 
3// Helper to extract cookie value
4function getCookie(name: string): string | null {
5 const match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
6 return match ? decodeURIComponent(match[2]) : null;
7}
8 
9// Global Axios configuration: automatically attaches Django CSRF token
10axios.interceptors.request.use((config) => {
11 const csrfToken = getCookie("csrftoken");
12 if (csrfToken && config.headers) {
13 config.headers["X-CSRFToken"] = csrfToken;
14 }
15 return config;
16});

4. Exempting Webhooks with @csrf_exempt

External incoming webhooks (e.g. Stripe, GitHub, Twilio) originate from third-party servers that do not possess browser sessions or CSRF tokens. Exempt these specific endpoints defensively:

1from django.views.decorators.csrf import csrf_exempt
2from django.http import HttpResponse
3 
4@csrf_exempt
5def stripe_webhook_view(request):
6 # Verify cryptographic signature using Stripe SDK instead of CSRF!
7 ...

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does the {% csrf_token %} template tag render inside an HTML <form>?
Question 2
Why does an attacker's website fail to send a valid CSRF token on behalf of a victim?
Question 3
Which HTTP header does Django inspect when receiving AJAX / React POST requests containing a CSRF token?
Question 4
When is it safe and acceptable to use the @csrf_exempt decorator?
Question 5
What setting determines whether the CSRF cookie can be read by JavaScript via document.cookie?
Next Lesson

Security Best Practices

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Custom MiddlewareSecurity Best Practices

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Django for Backend Development with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext