Cross Site Request Forgery protection(部分)

The CSRF middleware and template tag provides easy-to-use protection against Cross Site Request Forgeries. This type of attack occurs when a malicious Web site contains a link, a form button or some JavaScript that is intended to perform some action on your Web site, using the credentials of a logged-in user who visits the malicious site in their browser.

CSRF中间件以及木板标签可以很轻松的应对跨站点请求伪造攻击。这类攻击主要出现在一些恶意网站(比如B)通过链接、表单按钮或js代码借助已登陆网站A的用户的认证信息在B上所作的一些操作。

The first defense against CSRF attacks is to ensure that GET requests (and other‘safe’ methods, as defined by 9.1.1 Safe Methods, HTTP 1.1,RFC 2616) are side-effect free. Requests via ‘unsafe’ methods,such as POST, PUT and DELETE, can then be protected by following the steps below.

防御CSRF攻击首先要确保GET请求除了获取资源外,不要任何修改后台数据的操作,可以进行这些操作的方法(POST, PUT 与 DELETE)可以通过以下方法来防御。

How to use it

To take advantage of CSRF protection in your views, follow these steps:

防御CSRF攻击,请遵循以下步骤:

1、The CSRF middleware is activated by default in the MIDDLEWARE_CLASSES 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.

CSRF中间件默认是放在MIDDLEWARE_CLASSES中,已经被激活的,如果你把它改了,请确保django.middleware.csrf.CsrfViewMiddleware出现在任何可能被CSRF   攻击的中间件前面。

If you disabled it, which is not recommended, you can use csrf_protect() on particular views you want to protect (see below).

如果你把它禁止了(不推荐这么做),你可以用装饰器csrf_protect来保护指定的view。

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.:

在所有包含post表单的木板页面,确保csrf_token标签已被放在了标签内,如下所示:

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

加入csrf_token的表单不要指向其他网站,这有可能导致csrf token泄露,这样就不安全了。

3、In the corresponding view functions, ensure that the 'django.template.context_processors.csrf' context processor is being used. Usually, this can be done in one of two ways:

在相关的view函数中,确保'django.template.context_processors.csrf'被使用,通常,可以通过以下任意一种方式实现:

  • Use RequestContext, which always uses'django.template.context_processors.csrf' (no matter what templatecontext processors are configured in the TEMPLATES setting). If you are using generic views or contrib apps, you are covered already,since these apps use RequestContext throughout.

             使用RequestContext。RequestContext肯定会使用'django.template.context_processors.csrf'。如果你用了generic views或contrib apps,那么你已经使用到它了,因为这些app从头到尾都在使用RequestContext

  • Manually import and use the processor to generate the CSRF token and add it to the template context. e.g.:

             手动引入然后把产生的CSRF token加入到模板的context中,代码如下所示:

from django.shortcuts import render_to_response
from django.template.context_processors import csrf

def my_view(request):
    c = {}
    c.update(csrf(request))
    # ... view code here
    return render_to_response("a_template.html", c)

AJAX

While the above method can be used for AJAX POST requests, it has someinconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many JavaScript frameworks provide hooks that allow headers to be set on every request.

虽然以上方法也可以用在ajax的post请求上,但有很多不方便的地方:你需要手动在每个ajax请求里都放上csrf token。为了简化这个操作,可以在所有的XMLHttpRequest都加上一个X-CSRFToken头,并把其值设为CSRF token。这样的操作是比较容易实现的,因为很多js框架都提供了钩子函数来为suoyouderequest设置头部。

As a first step, you must get the CSRF token itself. The recommended source for the token is the csrf token cookie, which will be set if you’ve enabled CSRF protection for your views as outlined above.

首先,你需要手动把CSRF token提取出来。推荐的方法是从cookie中提取,如果你按上述方法设置了csrf保护,那么cookie中就包含了csrf token。

比如,通过jquery来获取csrf token的代码如下所示:

var csrftoken = $.cookie('csrftoken');
Finally, you’ll have to actually set the header on your AJAX request, while protecting the CSRF token from being sent to other domains using settings.crossDomain in jQuery 1.5.1 andnewer:

最后就是这是ajax请求头,为了防止csrf token影响正常跨域的使用,在代码里需要进行一下判断和处理:

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

原文:https://docs.djangoproject.com/en/1.8/ref/csrf/


你可能感兴趣的:(Python)