📅  最后修改于: 2023-12-03 15:30:07.788000             🧑  作者: Mango
When developing web applications, protecting against CSRF (Cross-Site Request Forgery) attacks is an important security concern. Django provides built-in middleware that generates a CSRF token when a user logs in or visits a page with a form, and ensures that the token is included in any subsequent POST requests.
To include the CSRF token in a Django form, use the {% csrf_token %}
template tag:
<form method="post">
{% csrf_token %}
...
</form>
This will include a hidden input field with the CSRF token, which Django will validate on form submission.
When making an AJAX request with jQuery, you can include the CSRF token in the headers
option:
$.ajax({
url: '/path/to/endpoint/',
method: 'POST',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {'key': 'value'},
success: function(response) {
...
}
});
This will include the CSRF token in the X-CSRFToken
header, which Django will validate before processing the request.
When making HTTP requests in a React application, you can include the CSRF token in a csrfmiddlewaretoken
header:
fetch('/path/to/endpoint/', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}', 'csrfmiddlewaretoken': '{{ csrf_token }}'},
body: JSON.stringify({'key': 'value'})
})
.then(response => response.json())
.then(data => {
...
});
This will include the CSRF token in both the X-CSRFToken
header and a csrfmiddlewaretoken
header, which Django will validate before processing the request.
By fetching and including the CSRF token in your web applications according to the recommended methods, you can help protect against CSRF attacks and ensure the security of your users' data.