Junior — Middle
Can you explain what middleware that protects against cross-site requests CSRF is?
sobes.tech AI
Answer from AI
Middleware that protects against CSRF (Cross-Site Request Forgery) is a software component that verifies that requests changing the server state genuinely originate from a trusted user, not an attacker.
The main protection mechanism is the CSRF token check. When generating a form, the server creates a unique token and inserts it into the form. When the form is submitted, the middleware checks that the token from the request matches the one stored on the server (for example, in the session).
Example in Django:
from django.middleware.csrf import CsrfViewMiddleware
# Django's built-in middleware automatically checks CSRF tokens in POST requests
Thus, the middleware prevents the execution of unwanted actions initiated from other sites, protecting both the user and the server.