CSRF usage of Django framework
Table of contents
Introduce the csrf class library
Set individual exemption from csrf
global use
The csrf middleware is used globally by default in the Django project configuration, and it can no longer be used if it is commented out.
However, it is not recommended to be so unsafe.
set csrf token
form use
Use the csrf token template tag directly in the form form, and automatically verify the csrf when submitting.
{% csrf_token %}
script use
In the project, many operations require ajax to operate and submit.
By viewing the source code, you can see that the csrf token tag creates a hidden input box named csrfmiddlewaretoken (default) in the form.
Js gets and sets token
let csrf = $('input[name="csrfmiddlewaretoken"]').val()
$.ajax({
type: 'POST',
url: "/media_list",
data: {csrfmiddlewaretoken:csrf},
dataType: 'json',
success: function (data) {
// 将mp3list赋值给this.songs
this.songs = data.list;
// 调用渲染歌曲列表的方法
this.renderSongList();
}.bind(this),
error: function (e) {
console.log("ERROR : ", e);
}
});
separate exemption
Sometimes the method does not want to set csrf protection, then you can use the csrf decorator.
Introduce the csrf class library
from django.views.decorators.csrf import csrf_exempt
Set individual exemption from csrf
Use csrf_exempt to individually exempt this method from csrf verification
@csrf_exempt
def upload_music(request):
separate protection
More suitable, most functions and methods do not need to verify csrf, only a few cases require verification.
Turn off global csrf
Modify the middleware in settings.py and comment out the csrf middleware.
Introduce the csrf library
from django.views.decorators.csrf import csrf_protect
Set function protection
Set the method in the view and use the csrf_protect decorator to perform csrf verification on the upload_music method separately.
@csrf_protect
def upload_music(request):
csrf token configuration
The csrf attribute can be set in settings.py, and the attribute can be set as:
CSRF_HEADER_NAME = 'HTTP_X_CSRF_AARONTOKEN'
CSRF_COOKIE_SAMESITE = 'Strict'
CSRF_COOKIE_NAME = 'MyCookie'
CSRF_COOKIE_HTTPONLY = False
CSRF_COOKIE_SECURE = False
CSRF_TRUSTED_ORIGINS = []
Summarize
Csrf verification is very important for security in the project. Through the above-mentioned csrf setting and use, I have gained some understanding of the django framework and can be more flexible in use.