Bird
0
0

You want to protect an AJAX POST request in Django from CSRF attacks. Which approach correctly includes the CSRF token in the request headers?

hard📝 Application Q15 of 15
Django - Security Best Practices
You want to protect an AJAX POST request in Django from CSRF attacks. Which approach correctly includes the CSRF token in the request headers?
ADisable CSRF middleware for AJAX requests
BInclude {% csrf_token %} inside the AJAX data payload as a form field
CAdd the CSRF token value from the cookie to the 'X-CSRFToken' header in the AJAX request
DSend the CSRF token as a URL query parameter
Step-by-Step Solution
Solution:
  1. Step 1: Understand CSRF protection for AJAX

    Django expects the CSRF token in the 'X-CSRFToken' header for AJAX POST requests, usually read from the CSRF cookie.
  2. Step 2: Evaluate options for AJAX token inclusion

    Add the CSRF token value from the cookie to the 'X-CSRFToken' header in the AJAX request correctly adds the token from the cookie to the header. Include {% csrf_token %} inside the AJAX data payload as a form field is incorrect because {% csrf_token %} is a template tag, not usable in JS. Disable CSRF middleware for AJAX requests disables protection (unsafe). Send the CSRF token as a URL query parameter is insecure and not recommended.
  3. Final Answer:

    Add the CSRF token value from the cookie to the 'X-CSRFToken' header in the AJAX request -> Option C
  4. Quick Check:

    AJAX CSRF token goes in 'X-CSRFToken' header [OK]
Quick Trick: Send CSRF token in 'X-CSRFToken' header for AJAX POST [OK]
Common Mistakes:
MISTAKES
  • Trying to use {% csrf_token %} in JavaScript
  • Disabling CSRF middleware instead of fixing token
  • Sending token in URL query parameters

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes