我有一个运行Django 1.6.10的网站。最近我们的一些管理员无法登录并且收到了CSRF 403错误页面。他们必须删除该网站的所有Cookie才能再次登录。这让我想知道它是否更广泛,因为CSRF错误页面没有被记录。我启用了日志记录,我发现大约10%的帖子存在问题。
Settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.csrf',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
'django.core.context_processors.request',
'django.core.context_processors.static',
)
MIDDLEWARE_CLASSES = (
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.cache.UpdateCacheMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'linaro_django_pagination.middleware.PaginationMiddleware',
'django.middleware.cache.FetchFromCacheMiddleware',
)
导致此问题的视图是基于通用类的视图,其中包含评论发布表单。表单标签内包含{%csrf_token%}。触发的错误是来自csrf中间件的REASON_NO_CSRF。
<WSGIRequest
path:/accounts/login/,
GET:<QueryDict: {u'next': [u'/profile/edit/']}>,
POST:<QueryDict: {u'username': [REDACTED], u'csrfmiddlewaretoken':
[u'Ns42nlyOUgLRUatcjjr0cfpRYwVSDETk'], u'password': [u'REDACTED']}>,
COOKIES:{'HIRO_COOKIE':
'data=&newSession=false&id=REDACTED×tamp=1414023546237',
'OX_plg': 'swf|shk|pm',
'SS_ARE_Override.traceLevel': 'WARN',
'__gads':
'ID=b5f389086388b528:T=1413419752:S=ALNI_MaqCqguvaHWhG76FGjhHzPTieaGeA',
'__qca': 'P0-2120806691-1413419758360',
'__sonar': '749077714819215977',
'_bsef2f5b6aaad756f2445ed7606b648325': '1',
'acudeoSession.': '%7B%22time%22%3A1421376382060%2C%22adIndex%22%3A1%7D',
'ebNewBandWidth_.www.REDACTED.com': 'REDACTED',
'mlUserID': '9X8L0kMS8ypL',
'targus.BirthYear': '',
'targus.ap_seg': '',
'targus.gender': '',
'targus.matched': '1',
'targus.segment': '000',
'targus.zip': '',
'vsl_userid': 'c4ee281a94b19b5cb09d83ee93e98f55'},
META:{'CONTENT_LENGTH': '92',
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
u'CSRF_COOKIE': u'CV5Vh0mpa578LnKGK1Lfj6pRVB1cwc6E',
'DOCUMENT_ROOT': '/usr/local/apache2/htdocs',
'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTP_ACCEPT':
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;
q=0.8',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
'HTTP_ACCEPT_LANGUAGE': 'en,en-GB;q=0.8',
'HTTP_CACHE_CONTROL': 'max-age=0',
'HTTP_CONNECTION': 'close',
所有错误的共同点是Cookie部分缺少应该存在的csrftoken。我无法弄清楚为什么django并不总是在视图上推出cookie,因为它是一个基于类的视图,我在settings.py中设置了所有设置,就像django docs所说的那样。当人们尝试登录或基本上任何帖子时也会发生这种情况。