我的站点上的 CSRF Django 中间件(来自 SVN 主干的版本)出现了许多故障。我得到的唯一错误是:CSRF 故障:原因 = CSRF 令牌丢失或不正确。
我如何诊断这些 CSRF 错误来自哪里?我自己不能导致 CSRF 错误,但我设置网站在触发 CSRF 错误视图时向我发送电子邮件,所以我知道它经常发生。
I really struggled to get it right, but eventually did. Here were my main issues (Django 1.2 beta):
Make sure that your settings emails are all the right ones. I had to do something like this:
EMAIL_HOST='mail.my-domain.com' EMAIL_HOST_USER='my user name on the server' EMAIL_HOST_PASSWORD='passwd' EMAIL_PORT= '26' # often seems to be 25 or 26 on many of the forum posts I read DEFAULT_FROM_EMAIL='noreply@domain.com' # on hosted domains, make sure it is set up and sending SERVER_EMAIL = 'noreply@domain.com' # Same email as above
return render_to_response('contact.htm',{'favicon':r'____.ico', 'more_stuff':"......" 'more_stuff':"......" 'more_stuff':"......" }, context_instance = RequestContext(request))
Make sure you have:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.csrf",
.....
)
in your settings.py file.
Note that this is really not a how to, this is just what I did to get mine working. The reason for posting it now is that I see so many people on forums discussing this topic resort to just turning the csrf_token off.
当中间件成功阻止跨站请求伪造攻击时,应该会发生 CSRF 错误。验证是否是这种情况的最佳方法可能是检查您的 Web 服务器日志,并且您应该看到与先前请求无关的请求。
MIDDLEWARE_CLASSES
您还应该检查settings.py
文件中的顺序。应该看起来像这样:
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.locale.LocaleMiddleware',
)
LocaleMiddleware
在最后。对我来说,解决方案是RequestContext
实例和排序。
确保 GET 请求的视图函数如下所示:
def login_view():
c = {}
c.update(csrf(request))
request.session.set_expiry(0)
if request.method == 'GET':
return render_to_response('newform.html',<b>c</b>)
然后检查 newform.html 的视图源,它必须有 Hidden 字段。
<`form action="" method="post" name="loginform"> <`div style='display:none'`><`input type='hidden' name='csrfmiddlewaretoken' value='6f4dee99ab2f5e7201e057cb63' />
在这里,action 可以引用同一个页面,action=""
.