简体   繁体   English

未设置 csrf cookie django

[英]csrf cookie not set django

I have some problem for a while now, I'm experiencing CSRF Cookie not set.我有一段时间遇到了一些问题,我遇到了未设置 CSRF Cookie 的情况。 Please look at the codes below请看下面的代码

views.py视图.py

    from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
from django.conf.urls import patterns, url, include
from django.template.context_processors import csrf
def login_user(request):
    state = "Please log in below..."
    username = password = ''
    dic = {}
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('password')

        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                state = "You're successfully logged in!"
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."
        dic['state'] = state
        dic['username'] = username
        dic.update(csrf(request))

    return render_to_response('authen/auth.html',dic )

templates(authen.html)模板(authen.html)

 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Log in</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style>
body{
    font-family:Arial,Helvetica,sans-serif;
    font-size: 12px;
}
</style>
</head>
<body>
    {{ state }}
    <form action="/login/" method="post">{% csrf_token %}
        {% if next %}
        <input type="hidden" name="next" value="{{ next }}" />
        {% endif %}
        username: 
        <input type="text" name="username" value="{{ username}}" /><br />
        password:
        <input type="password" name="password" value="" /><br />

        <input type="submit" value="Log In" />
    </form>
</body>

urls.py网址.py

from django.conf.urls import include, url
    from . import views

     urlpatterns = [
       url(r'^$', views.login_user),
      ]

setting.py设置.py

  INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
 'authen')
MIDDLEWARE_CLASSES = (
    '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',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
)
ROOT_URLCONF = 'Auth.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.csrf'
            ],
        },
    },
]

WSGI_APPLICATION = 'Auth.wsgi.application'

Im stuck, I already cleared the cookie, used other browser but still csrf cookie not set.我卡住了,我已经清除了 cookie,使用了其他浏览器,但仍未设置 csrf cookie。

You are manually adding the CSRF token to the context, but you are only doing it after the POST. 您正在手动将CSRF令牌添加到上下文中,但是仅在POST 之后执行。 The whole point of a CSRF token is that it is set by the GET, and checked on POST. CSRF令牌的全部要点是它是由GET设置的,并在POST上进行了检查。 Since you are not setting it on GET, the POST will fail. 由于您未在GET上进行设置,因此POST将失败。

However you should not be setting it manually at all. 但是,您根本不应该手动设置它。 Django will do it for you, as long as you use a RequestContext. 只要您使用RequestContext,Django就会为您完成。 And the way to do that is to use the render shortcut, passing it the request, rather than the old render_to_response . 做到这一点的方法是使用render快捷方式,将请求传递给它,而不是旧的render_to_response

Remove the call to csrf(request) and replace your last line with: 删除对csrf(request)的调用, csrf(request)最后一行替换为:

return render(request, 'authen/auth.html', dic)

在您的view.py中,将RequestContext(request)添加到render_to_response:

return render_to_response('authen/auth.html',dic, context_instance = RequestContext(request))

I was receiving the Forbidden (403), CSRF cookie not set.我收到 Forbidden (403),未设置 CSRF cookie。 error.错误。 I thought it had something to do with ios.我认为它与ios有关。

I fixed this by adding an "s" to the end of http, FROM: htt p: //MYAPPNAME.herokuapp.com/ TO: htt ps: //MYAPPNAME.herokuapp.com/我通过在 http 的末尾添加一个“s”来解决这个问题,FROM: htt p: //MYAPPNAME.herokuapp.com/ TO: htt ps: //MYAPPNAME.herokuapp.com/

In

# settings.py
SESSION_COOKIE_SECURE = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM