Django CSRF cookie 设置不正确

Django CSRF cookie not set correctly

更新 7-18:

这是我的代理服务器 nginx 配置:

server {
    listen 80;
    server_name blah.com; # the blah is intentional

    access_log /home/cheng/logs/access.log;     
    error_log /home/cheng/logs/error.log;       

    location / {
        proxy_pass http://127.0.0.1:8001;         
    }

    location /static {
        alias /home/cheng/diandi/staticfiles;  
    }

    location /images {
        alias /home/cheng/diandi/images;
    }

    client_max_body_size 10M;
}

这里是nginx.conf:

user www-data;
worker_processes 4;
pid /var/run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        ##
        # Logging Settings
        ##

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        ##
        # Gzip Settings
        ##

        gzip_disable "msie6";

        # Enable Gzip compressed.
        gzip on;

        # Enable compression both for HTTP/1.0 and HTTP/1.1.
        gzip_http_version  1.1;

        # Compression level (1-9).
        # 5 is a perfect compromise between size and cpu usage, offering about
        # 75% reduction for most ascii files (almost identical to level 9).
        gzip_comp_level    5;

        # Don't compress anything that's already small and unlikely to shrink much
        # if at all (the default is 20 bytes, which is bad as that usually leads to
        # larger files after gzipping).
        gzip_min_length    256;

        # Compress data even for clients that are connecting to us via proxies,
        # identified by the "Via" header (required for CloudFront).
        gzip_proxied       any;

        # Tell proxies to cache both the gzipped and regular version of a resource
        # whenever the client's Accept-Encoding capabilities header varies;
        # Avoids the issue where a non-gzip capable client (which is extremely rare
        # today) would display gibberish if their proxy gave them the gzipped version.
        gzip_vary          on;

        # Compress all output labeled with one of the following MIME-types.
        gzip_types
                application/atom+xml
                application/javascript
                application/json
                application/rss+xml
                application/vnd.ms-fontobject
                application/x-font-ttf
                application/x-web-app-manifest+json
                application/xhtml+xml
                application/xml
                application/x-javascript
                font/opentype
                image/svg+xml
                image/x-icon
                text/css
                text/plain
                text/javascript
                text/js
                text/x-component;

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

更新 7-15:

复制代码到linux台机器时,我只是替换了原来的源代码文件,没有删除旧的.pyc文件,我认为这不会造成问题吧?


查看代码如下:

from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render

def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        next_url = request.POST['next']
        if user is not None:
            if user.is_active:
                login(request, user)
                if next_url:
                    return HttpResponseRedirect(next_url)
                return HttpResponseRedirect(reverse('diandi:list'))
        else:
            form = {'errors': True}
            return render(request, 'registration/login.html', {'form': form})

    else:
        form = {'errors': False}
        return render(request, 'registration/login.html', {'form': form})

我从 Django 得到了一个 CSRF cookie not set 错误,但这不是因为我忘记在我的模板中包含 {% csrf_token %}

这是我观察到的:

访问登录页面 #1 尝试

Request Header里面,cookie的值是:

csrftoken=yNG8ZmSI4tr2xTLoE9bys8JbSuu9SD34;

在模板中:

<input type="hidden" name="csrfmiddlewaretoken" value="9CVlFSxOo0xiYykIxRmvbWyN5iEUHnPB">

在我安装在 chrome 上的一个 cookie 插件中,实际的 csrf cookie 值设置为:

9CVlFSxOo0xiYykIxRmvbWyN5iEUHnPB

访问登录页面 #2 尝试:

Request Header里面,cookie的值是:

csrftoken=9CVlFSxOo0xiYykIxRmvbWyN5iEUHnPB;

在模板中:

<input type="hidden" name="csrfmiddlewaretoken" value="Y534sU40S8iTubSVGjjh9KQl0FXesVsC">

在我安装在 chrome 上的一个 cookie 插件中,实际的 csrf cookie 值设置为:

Y534sU40S8iTubSVGjjh9KQl0FXesVsC

模式

正如您从上面的示例中看到的,Request Header 中的 cookie 值与表单中的实际 csrfmiddlewaretoken 和设置的实际 cookie 值不同。

当前请求的 cookie 值匹配下一个 request header's cookie 值。


为了帮助调试,这里是我的 `settings.py:

的一部分
DJANGO_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
)

THIRD_PARTY_APPS = (
    'compressor',
    'crispy_forms',
    'django_extensions',
    'floppyforms',
    'multiselectfield',
    'admin_highcharts',
)

LOCAL_APPS = (
    'diandi_project',
    'uer_application',
)

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

MIDDLEWARE_CLASSES = (
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [str(ROOT_DIR.path('templates'))],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.media',
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

我正在使用 Django 1.9.5python 2.7.10

一个“解决方案”

我遇到了this problem before,我可以清除我所有的浏览器cookies,网站也能正常运行。但是这个问题最终会再次出现,所以我真的希望有人能帮助我(我可能只是在某个地方犯了一个非常愚蠢的错误)。

更新

最初,我认为我在覆盖 django.contrib.auth.view 页面时犯了一些错误,所以我编写了自己的登录页面处理程序,但它仍然导致了问题。

这是我的登录模板的核心部分:

{% block content %}
...

                <form method="post" action="{% url 'login' %}">
                    {% csrf_token %}

                    <div class="form-group">
                        <label for="username">username</label>
                        <input type="text" class="form-control" id="id_username" name="username">
                    </div>
                    <div class="form-group">
                        <label for="password">password</label>
                        <input type="password" class="form-control" id="id_password" name="password">
                    </div>

                    <input type="submit" class="btn btn-default" value="login" />
                    <input type="hidden" id="next" name="next" value="" />
                </form>

...

{% endblock %}

在 Linux 机器上,我有一个 nginx 服务器设置为反向代理,它将端口 80 上的请求定向到 8001,我 运行 服务器使用 ./manage runserver localhost:8001 这是我在设置方面能想到的唯一区别。否则,所有源代码和设置文件都是相同的。


我开始删除 cookie 但不是全部,这是我在删除它们之前看到的:

我删除了除 djdtcsrftoken 之外的所有 cookie,然后页面正常运行。删除的 cookie 是否会以某种方式超过某个限制,从而阻止设置列表下方的 csrftoken?

这里是上面图片在请求头中的cookie值:

Cookie:PSTM=1466561622; BIDUPSID=6D0DDB8084625F2CEB7B9D0F14F93391; BAIDUID=326150BF5A6DFC69B6CFEBD67CA7A18B:FG=1; BDSFRCVID=Fm8sJeC62leqR8bRqWS1u8KOKg9JUZOTH6ao6BQjXAcTew_mbPF_EG0PJOlQpYD-hEb5ogKK0mOTHvbP; H_BDCLCKID_SF=tJPqoCtKtCvbfP0k-tcH244HqxbXq-r8fT7Z0lOnMp05EnnjKl5M3qKOqJraJJ585Gbb5tOhaKj-VDO_e6u-e55LjaRh2PcM2TPXQ458K4__Hn7zep0aqJtpbt-qJjbOfmQBbfoDQCTDfho5b63JyTLqLq5nBT5Ka26WVpQEQM5c8hje-4bMXPkkQN3T-TJQL6RkKTCyyx3cDn3oyToVXp0njGoTqj-eJbA8_CtQbPoHHnvNKCTV-JDthlbLetJyaR3lWCnbWJ5TMCo1bJQCe-DwKJJgJRLOW2Oi0KTFQxccShPC-tP-Ll_qW-Q2LPQfXKjabpQ73l02VhcOhhQ2Wf3DM-oat4RMW20jWl7mWPQDVKcnK4-Xj533DHjP; BDUSS=5TNmRvZnh2eUFXZDA5WXI5UG1HaXYwbzItaWt3SW5adjE1Nn5XbUVoWHZuYXBYQVFBQUFBJCQAAAAAAAAAAAEAAAC0JtydAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAO8Qg1fvEINXSU; Hm_lvt_a7708f393bfa27123a1551fef4551f7a=1468229606; Hm_lpvt_a7708f393bfa27123a1551fef4551f7a=1468229739; BDRCVFR[feWj1Vr5u3D]=I67x6TjHwwYf0; BDRCVFR[dG2JNJb_ajR]=mk3SLVN4HKm; BDRCVFR[-pGxjrCMryR]=mk3SLVN4HKm; cflag=15%3A3; H_PS_PSSID=1424_20515_13289_20536_20416_19861_14994_11792; csrftoken=xUgSHybzHeIwusN0GvMgB1ATeRrPgcV1

由于网站现在可以正常运行,我只有五个 cookie,而不是上图中的 14 个:

这是问题所在:您的 cookie 不能包含字符“[”或“]”

我发现了@Todor link, then I found out about this SO post 之后的解决方案。基本上 python 2.7.x 中存在一个错误,它不解析值中带有“]”的 cookie。该错误已在 2.7.10 中修复。

我认为只要确认这个问题就好了。所以我翻遍了所有的饼干,发现了一个 key/value:

key: BDRCVFR[feWj1Vr5u3D]
val: I67x6TjHwwYf0

所以我在本地插入了以下cookie并提交给服务器:

key: test
val: BDRCVFR[feWj1Vr5u3D]

登录页面有效,这意味着 2.7.10 确实修复了该错误。

但后来我意识到方括号实际上是在键名中而不是在值中,所以我做了以下测试:

key: [
val: I67x6TjHwwYf0

key:]
val: I67x6TjHwwYf0

两个 cookie 都中断了登录过程,django 显示:

CSRF cookie not set

因此,无论是 django 还是它所依赖的 python 库都无法正确解析名称中带有方括号的 cookie。如果有人知道我应该在哪里提交这个错误,请告诉我(django 或 python)。

我要感谢在 OP 中发表评论的所有人:@raphv、@trincchet、@Phillip、@YPCrumble、@PeterBrittain 和@Todor。非常感谢你们和我一起调试!


更新:2016 年 7 月 20 日

此bug已在Django 1.10中修复,只需要等待发布

更新:2016 年 7 月 19 日

filed a bug report把Django作为这个post的结果。我们将看看它是否会在未来的版本中得到修复。