Django2.1.4中CSRF注意事项

一、环境

python3.7.1
django2.1.4

二、注意事项

  1. 确定项目的setting.py文件中存在django.middleware.csrf.CsrfViewMiddleware。
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
  1. 在模板文件(.html)的post表单中,加入{% csrf_token %}。
{% csrf_token %} Title:
Body:
  1. 在视图函数中使用render函数。
def archive(request):
    posts = BlogPost.objects.all()[:10]
    return render(request, 'archive.html', {'posts': posts})

特别说明:不要使用render_to_response(),会出错

django2.1官方文档:
To take advantage of CSRF protection in your views, follow these steps:
1.The CSRF middleware is activated by default in the MIDDLEWARE setting. If you override that setting, remember that ‘django.middleware.csrf.CsrfViewMiddleware’ should come before any view middleware that assume that CSRF attacks have been dealt with.
If you disabled it, which is not recommended, you can use csrf_protect() on particular views you want to protect (see below).

2.In any template that uses a POST form, use the csrf_token tag inside the element if the form is for an internal URL, e.g.:

{% csrf_token %} This should not be done for POST forms that target external URLs, since that would cause the CSRF token to be leaked, leading to a vulnerability.

3.In the corresponding view functions, ensure that RequestContext is used to render the response so that {% csrf_token %} will work properly. If you’re using the render() function, generic views, or contrib apps, you are covered already since these all use RequestContext.

三、一些相关知识点

  1. setting.py文件中的django.middleware.csrf.CsrfViewMiddleware,说明在项目中使用了CsrfViewMiddleware中间件,用来在全局防止跨站点请求伪装CSRF攻击,即所有视图函数都启用了防CSRF攻击。
  2. 在1的前提下,如果在某视图函数中使用了装饰器csrf.exempt,则防CSRF攻击对此视图函数失效。
  3. 如果setting.py文件中没有部署django.middleware.csrf.CsrfViewMiddleware,那么在某视图函数中使用装饰器csrf_protect,则这个视图函数能够防CSRF攻击。

你可能感兴趣的:(python框架)