【问题标题】:csrf cookie not set django restcsrf cookie 未设置 django rest
【发布时间】:2017-05-05 00:18:12
【问题描述】:

在使用 REST 可浏览 API 时,响应工作正常,但当我开始使用邮递员与另一端的前端集成时,响应变为:

 {
  "detail": "CSRF Failed: CSRF cookie not set."
}

我尝试了一切来解决这个错误,但没有任何改变,并检查了这里关于 CSRF 令牌的每个问题,但仍然没有工作

这些是我的代码: 视图.py:

from django.shortcuts import render

from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework import status
from User.serializers import UserDataSerializer, ImageSerializer
from rest_framework.views import APIView
from rest_framework import generics
from User.models import UserData,Image
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from rest_framework.renderers import TemplateHTMLRenderer
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
class Signup(APIView):
    def post(self, request, format = None):
       serializer = UserDataSerializer(data = request.data)
       if(serializer.is_valid()):
           user = User.objects.create_user(
               username = serializer.data['username'],
               first_name = serializer.data['first_name'],
               last_name = serializer.data['last_name'],
               email = serializer.data['email'],
               password = serializer.data['password'],
               )
        #add the name because it is not with create_user method
        # user.name = serializer.data['name']
        # user.save()
        login(request, user)
        print ("logged")
        text = {'valid' : True , 'errors' :"ur password"+serializer.data['password']}
        return JsonResponse(serializer.data)
    else:
        return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class Login(APIView):
   def post(self, request):
       username = request.data.get('username')
       password = request.data.get('password')
       user = authenticate(username=username, password=password)

       if user is not None:
           login(request, user)
           serializer = UserDataSerializer(user)
           return JsonResponse(serializer.data, status=status.HTTP_302_FOUND)
       else:
           text = {'valid' : False , 'errors' : "Invalid Username or Password"}
           return Response(text, status=status.HTTP_401_UNAUTHORIZED)

class Logout(APIView):
    def get(self, request):
        logout(request)
        return Response({"valid": True}, status=status.HTTP_200_OK)

class ImageUpload(generics.CreateAPIView):

    queryset = Image.objects.all()
    serializer_class = ImageSerializer

settings.py:

"""
Django settings for app project.

Generated by 'django-admin startproject' using Django 1.10.3.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'baz^+ip1ik4_fla*zg$9q#37e(5jg6tmnwzj4btqw@nw=si)+('

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
CSRF_COOKIE_SECURE = False
ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'User.apps.UserConfig',
    'rest_framework',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'app.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.core.context_processors.csrf',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'app.wsgi.application'

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),
}
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'ImageSearchDB',
        'USER': 'root',
        'PASSWORD': '1234',
        'HOST': 'localhost',
        'PORT': '',
        'OPTIONS': {
        'init_command': 'SET default_storage_engine=INNODB',
        }
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# AUTHENTICATION_BACKENDS = (
#     'app.User.backends.EmailOrUsernameModelBackend',
#     'django.contrib.auth.backends.ModelBackend'
# )
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = 'media/'

urls.py

from django.conf.urls import url
from User import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [

    url(r'^login/?$', views.Login().as_view()),
    url(r'^signup/?$', views.Signup().as_view()),
    url(r'^logout/?$', views.Logout().as_view()),
    url(r'^trail/?$', views.ImageUpload().as_view())

]
urlpatterns = format_suffix_patterns(urlpatterns)   #no need

【问题讨论】:

  • 欢迎来到 Stack Overflow。写文章时,请使用段落(双回)来分隔文章的不同部分。错误日志可以在代码块中呈现,就像您对实际代码所做的那样。最后,请尽量使用真实的文字 - 为 Facebook 保存 plz 等!谢谢。

标签: django cookies django-views csrf


【解决方案1】:

你必须像这样在 url 中使用 ensure_csrf_cookie 装饰器

from django.views.decorators.csrf import ensure_csrf_cookie
urlpatterns = [
    url(r'^login/?$', ensure_csrf_cookie(views.Login().as_view())),
]

您还需要添加所有 CORS 设置

【讨论】:

    猜你喜欢
    • 2013-05-12
    • 2017-12-06
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2013-03-28
    • 2012-05-03
    • 2016-11-26
    相关资源
    最近更新 更多