Django - CSRF 验证失败 [英] Django - CSRF verification failed

查看:41
本文介绍了Django - CSRF 验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试从教程中制作简单表单时收到 CSRF 验证失败消息.我对 CSRF 验证实际上是什么进行了一些研究,据我所知,为了使用它,您需要在您的 html 中使用这些 csrf_token 标签之一,但我没有那个

I'm getting a CSRF verification failed message when trying to make a simple form from a tutorial. I did a little research into what CSRF verification actually is, and to my knowledge, in order to use it you need one of those csrf_token tags in your html, but I don't have that

这是我的模板:

<form action="/testapp1/contact/" method="post">
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>

相当简单,位于contact.html

Fairly straightforward, located at contact.html

这是我的 urlconf:从 django.conf.urls.defaults 导入 *

Here's my urlconf: from django.conf.urls.defaults import *

urlpatterns=patterns('testapp1.views',
    (r'^$', 'index'),
    (r'^contact/$','contact')
)

应用名称是 testapp1.当我输入我的 url (http://localhost:8000/testapp1/contact) 时,我正确地转到了表单.然后当我提交表单时,我收到验证错误.

The app name is testapp1. When I type my url (http://localhost:8000/testapp1/contact), I correctly go to the form. Then when I submit the form, I get the verification error.

以下是我的观点,虽然我认为它不相关:

Here's my view although I don't think it's relevant:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            subject = form.cleaned_data['subject']
            message = form.cleaned_data['message']
            sender = form.cleaned_data['sender']
            cc_myself = form.cleaned_data['cc_myself']
            recipients = ['info@example.com']
            if cc_myself:
                recipients.append(sender)
            print 'Sending Mail:'+subject+','+message+','+sender+','+recipients
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

推荐答案

修复

1.在模板中包含 {% csrf_token %} inside 表单标签.

The fix

1. include {% csrf_token %} inside the form tag in the template.

2.如果出于任何原因您在 Django 1.3 及更高版本上使用 render_to_response,请将其替换为 render 函数.替换这个:

2. if for any reason you are using render_to_response on Django 1.3 and above replace it with the render function. Replace this:

# Don't use this on Django 1.3 and above
return render_to_response('contact.html', {'form': form})

有了这个:

return render(request, 'contact.html', {form: form})

渲染函数是在 Django 1.3 版中引入的 - 如果你使用的是旧版本 像 1.2 或更低版本 你必须使用 render_to_response 和 aa RequestContext:

The render function was introduced in Django version 1.3 - if you are using an ancient version like 1.2 or below you must use render_to_response with a a RequestContext:

# Deprecated since version 2.0
return render_to_response('contact.html', {'form': form},
                   context_instance=RequestContext(request))

什么是 CSRF 保护,我为什么需要它?

在这种攻击中,敌人可以迫使您的用户做一些令人讨厌的事情,例如转移资金、更改他们的电子邮件地址等:

What is CSRF protection and why would I want it?

It is an attack where an enemy can force your users to do nasty things like transferring funds, changing their email address, and so forth:

跨站点请求伪造 (CSRF) 是一种攻击,它迫使最终用户在当前已通过身份验证的 Web 应用程序上执行不需要的操作.CSRF 攻击专门针对改变状态的请求,而不是窃取数据,因为攻击者无法看到对伪造请求的响应.借助社交工程的一点帮助(例如通过电子邮件或聊天发送链接),攻击者可能会诱使 Web 应用程序的用户执行攻击者选择的操作.如果受害者是普通用户,成功的 CSRF 攻击可以迫使用户执行状态更改请求,例如转移资金、更改他们的电子邮件地址等.如果受害者是管理帐户,CSRF 可以危害整个 Web 应用程序.来源:开放网络应用安全项目

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application. Source: The Open Web Application Security Project

即使您现在不关心这类事情,应用程序可能会增长,因此最佳做法是保持 CSRF 保护.

Even if you don't care about this kind of thing now the application may grow so the best practice is to keep CSRF protection on.

它是可选的,但默认开启(默认包含CSRF中间件).您可以将其关闭:

It is optional but turned on by default (the CSRF middleware is included by default). You can turn it off:

  • 通过使用 csrf_exempt 装饰器装饰特定视图.
  • 通过从 settings.py
  • 的中间件列表中删除 CSRF 中间件来针对每个视图
  • for a particular view by decorating it with the csrf_exempt decorator.
  • for every view by removing the CSRF middleware from the middleware list at settings.py

如果您在系统范围内关闭它,您可以通过使用 csrf_protect 装饰器对其进行装饰来为特定视图打开它.

If you turn it off system-wide you can turn it on for a particular view by decorating it with the csrf_protect decorator.

这篇关于Django - CSRF 验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆