django中404错误CSRF verification failed. Request aborted

在Django项目中遇到404错误:CSRF verification failed. Request aborted。问题原因包括浏览器未启用cookies、视图函数使用RequestContext、模板中缺少{% csrf_token %}标签、未使用@csrf_protect装饰器等。解决方法包括检查浏览器cookies设置、更改views.py中上下文处理、添加csrf_token到表单、以及正确使用@csrf_protect。此外,可以在settings.py中关闭CSRF验证功能。

在页面中提示:

Reason given for failure:

    CSRF token missing or incorrect.

接着给出解决方案:

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function uses RequestContext for the template, instead of Context.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.


第一点,你的浏览器是否支持cookies,我开始调试用的谷歌浏览器是没有开启cookie的,调试了半天功夫,换了火狐浏览器就好了。

第二点,在views.py中使用RequestContext方法而取代Context,格式大致是:

return render_to_response('login.html', {'username': username}, context_instance=RequestContext(request))

也可以这样:

c = RequestContext(request, {'foo': 'bar',}, [ip_address_processor])

return HttpResponse(t.render(c))

第三点,templates中需要提交的form表单加入{% csrf_token %},如下:

<form method="post" action="/logout/">
    {% csrf_token %}
    <input type="submit" value="Logout">
</form>

第四点,如果不使用CsrfViewMiddleware,则需要用@csrf_token标注View.py中接受POST数据的方法,格式如下:

@csrf_protect
def login(request):
    username = request.POST.get('username', None)
    password = request.POST.get('password', None)


    if username:
        ac_list = Account.objects.all()
        for ac in ac_list:
            if ac.username == username and ac.password == password:
                request.session['username'] = username
                return render_to_response('login.html', {'username': username},
                                          context_instance=RequestContext(request))
    return render_to_response('login.html', context_instance=RequestContext(request))

注意:有的建议是在setting.py中加入 'django.middleware.csrf.CsrfResponseMiddleware', 可是1.4版的django已经不支持这种做法了,会提示找不到csrf.CsrfResponseMiddleware

什么是CSRF

问题是解决了,但我不禁回想为什么在Django里提交POST表单要配置那么麻烦(其实也不麻烦,但对新手来说就不一样了),于是搜索关键字看看,得知它是一种跨站请求伪造,黑客可以利用这个攻击站点。而Django里的使用这个机制就是防止CSRF模式攻击,原理大致是当你打开页面的时候产生一个csrftokey种下cookie,然后当你提交表单时会把本地cookie里的csrftokey值给提交服务器,服务器判断只有有效的csrftokey值才处理请求。

既然这样,我就查看了一下cookie信息,发现果真种了一个csrftokey值

Django表单

右键HTML页面查看源代码,发现{% csrf_token %}位置替换成了一个input隐藏值

Django表单

input隐藏标签值与cookie里的csrftoken值一致。

于是我做了一个测试,在from表单里把{% csrftoken %}标签直接替换成如上图的input标签,name与value保持一致,提交留言的时候服务器正常处理,测试成功。

不使用CSRF验证

Django提供了POST表单使用CSRF验证功能,感觉还是挺不错的。但在Django里能不能像普通的Form表单一样不使用CSRF验证功能呢?答案是肯定可以的。

1、我在settings.py的MIDDLEWARE_CLASSES'django.middleware.csrf.CsrfViewMiddleware'注释

2、移出FROM表单里的{% csrf_token %}标记

3、不导入RequestContext模块,并把render_to_response()里的context_instance=RequestContext(request)去掉

重新运行网页测试提交留言正常。至此,应该可以判断出上边1步骤里的'django.middleware.csrf.CsrfViewMiddleware'语句开启了CSRF验证功能,默认是开启的,注释以后就关闭CSRF验证POST表单提交功能了。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值