CSRF失败:Django Rest中缺少CSRF令牌。

huangapple go评论75阅读模式
英文:

CSRF Failed: CSRF token missing. in Django Rest

问题

I am really confused because I can't avoid this error. My previous projects were not engaged with this error. So anyways I hope you can find a solution.

here is my settings.py:

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-n^s54jl394v4!_#n^78&7o-9swqt*ckq1pcyx_g3@vhb$8gct5'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "rest_framework",
    "accounts",
    "contents",
]
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 = 'config.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',
            ],
        },
    },
]
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": [
        "rest_framework.authentication.SessionAuthentication"
    ]
}
WSGI_APPLICATION = 'config.wsgi.application'
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
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',
    },
]
LANGUAGE_CODE = 'en-us'
STATIC_ROOT = os.path.join("static")
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

and here is my urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("accounts/", include("accounts.urls")),
    path("contents/", include("contents.urls")),
]

here is accounts.views:

from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from rest_framework import status
from rest_framework.views import APIView
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate

from accounts.serializers import UserCreationSerializer, UserLoginSerializer

class RegisterAPIView(CreateAPIView):
    model = User
    queryset = User.objects.all()
    serializer_class = UserCreationSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        username = serializer.validated_data.get("username")
        password = serializer.validated_data.get("password")
        user = authenticate(username=username, password=password)
        if user:
            login(request, user)
            return Response(
                data={"msg": "User created successfully and logged in"},
                status=status.HTTP_201_CREATED
            )
        return Response(
            data={"msg": "User Creation process failed"}, status=status.HTTP_400_BAD_REQUEST
        )

    def perform_create(self, serializer):
        serializer.save()

class UserLoginView(APIView):
    def post(self, request):
        serializer = UserLoginSerializer(data=request.data)
        print(request.user.is_authenticated)
        if serializer.is_valid():
            username = serializer.validated_data['username']
            password = serializer.validated_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return Response({'message': 'User logged in successfully'}, status=status.HTTP_200_OK)
            else:
                return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class LogoutAPIView(APIView):
    model = User

    def get(self, request, *args, **kwargs):
        logout(request)
        return Response(data={"msg": "User logged out successfully!"}, status=status.HTTP_200_OK)

accounts.urls

from django.urls import path
from accounts import views

urlpatterns = [
    path("register/", views.RegisterAPIView.as_view(), name="register"),
    path("login/", views.UserLoginView.as_view(), name="login"),
    path("logout/", views.LogoutAPIView.as_view(), name="logout")
]

accounts.serializers

from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

class UserCreationSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ["username", "first_name", "last_name", "email", "password"]
        model = User

    def save(self, **kwargs):
        user = self.Meta.model
        return user.objects.create_user(
            username=self.validated_data.get("username"),
            email=self.validated_data.get("email"),
            password=self.validated_data.get("password"),
            first_name=self.validated_data.get("first_name"),
            last_name=self.validated_data.get("last_name"),
        )

class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=150)
    password = serializers.CharField(max_length=128, write_only=True)

    def validate(self, data):
        username = data.get('username')
        password = data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise serializers.ValidationError("Invalid username or password.")
        else:
            raise serializers.ValidationError("Both username and password are required.")

        data['user'] = user
        return data

here is a Postman snapshot. CSRF失败:Django Rest中缺少CSRF令牌。

These are all I can show as code, if this problem doesn't depend on my code, well, let me know, I don't know other possibilities that cause this error, but all configurations such as Google, Postman, Python, and the editor are perfect, like they are working well.

I am in production, so I hope you guys can find a proper solution for that. Thanks in advance.

Yours, Abdusamad.

英文:

I am really confused because I can't avoid this error. My previous projects were not engaged with this error. So anyways I hope you can find solution.

here is my settings.py:

import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = 'django-insecure-n^s54jl394v4!_#n^78&7o-9swqt*ckq1pcyx_g3@vhb$8gct5'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
"rest_framework",
"accounts",
"contents",
]
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 = 'config.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',
],
},
},
]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication"
]
}
WSGI_APPLICATION = 'config.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
STATIC_ROOT = os.path.join("static")
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
STATIC_URL = 'static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

and here is my urls.py:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("accounts/", include("accounts.urls")),
path("contents/", include("contents.urls")),
]

here is accounts.views:

from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from rest_framework import status
from rest_framework.views import APIView
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from accounts.serializers import UserCreationSerializer, UserLoginSerializer
class RegisterAPIView(CreateAPIView):
model = User
queryset = User.objects.all()
serializer_class = UserCreationSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
username = serializer.validated_data.get("username")
password = serializer.validated_data.get("password")
user = authenticate(username=username, password=password)
if user:
login(request, user)
return Response(
data={"msg": "User created successfully and logged in"},
status=status.HTTP_201_CREATED
)
return Response(
data={"msg": "User Creation process failed"}, status=status.HTTP_400_BAD_REQUEST
)
def perform_create(self, serializer):
serializer.save()
class UserLoginView(APIView):
def post(self, request):
serializer = UserLoginSerializer(data=request.data)
print(request.user.is_authenticated)
if serializer.is_valid():
username = serializer.validated_data['username']
password = serializer.validated_data['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
return Response({'message': 'User logged in successfully'}, status=status.HTTP_200_OK)
else:
return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class LogoutAPIView(APIView):
model = User
def get(self, request, *args, **kwargs):
logout(request)
return Response(data={"msg": "User logged out successfully!"}, status=status.HTTP_200_OK)

accounts.urls

from django.urls import path
from accounts import views
urlpatterns = [
path("register/", views.RegisterAPIView.as_view(), name="register"),
path("login/", views.UserLoginView.as_view(), name="login"),
path("logout/", views.LogoutAPIView.as_view(), name="logout")
]

accounts.serializers

from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
class UserCreationSerializer(serializers.ModelSerializer):
class Meta:
fields = ["username", "first_name", "last_name", "email", "password"]
model = User
def save(self, **kwargs):
user = self.Meta.model
return user.objects.create_user(
username=self.validated_data.get("username"),
email=self.validated_data.get("email"),
password=self.validated_data.get("password"),
first_name=self.validated_data.get("first_name"),
last_name=self.validated_data.get("last_name"),
)
class UserLoginSerializer(serializers.Serializer):
username = serializers.CharField(max_length=150)
password = serializers.CharField(max_length=128, write_only=True)
def validate(self, data):
username = data.get('username')
password = data.get('password')
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise serializers.ValidationError("Invalid username or password.")
else:
raise serializers.ValidationError("Both username and password are required.")
data['user'] = user
return data

here is postman snapshot.
CSRF失败:Django Rest中缺少CSRF令牌。

These are all I can show as code, if this propblem doesn't depend on my code, well, let me know, I don't know other possiblities that causes this error, but all configurations such as Google, postman, python and editor are perfect, like they are working well.

I am in production, so hope you guys can find proper solution for that.
Thanks from advance.

Yours, Abdusamad.

答案1

得分: 0

我进行了研究并找到了答案,那是一个愚蠢的错误,你应该将sessionauthentication更改为tokenauthentication或其他在settings.py的REST_FRAMEWORK变量中支持的类,多傻的情况,不是吗。

英文:

I researched and found an answer for that, that was a sily mistake, you should change sessionauthentication to tokenauthentication or other supported classes, in REST_FRAMEWORK variable in settings.py,
how silly situation it was, isnt it.

答案2

得分: 0

account.urls中出现了问题,使用以下代码:

path("register/", views.RegisterAPIView().as_view(), name="register"),
path("login/", views.UserLoginView().as_view(), name="login"),
path("logout/", views.LogoutAPIView().as_view(), name="logout")

因为RegisterAPIView()UserLoginView()LogoutAPIView()都是类。你也可以尝试以下代码:

class RegisterAPIView(CreateAPIView):
    model = User
    queryset = User.objects.all()
    serializer_class = UserCreationSerializer
    
    @staticmethod
    def post(self, request, *args, **kwargs):
        # 在此处添加你的代码

放在account.views中。

英文:

an issue is in account.urls,
use

path("register/", views.RegisterAPIView().as_view(), name="register"),
path("login/", views.UserLoginView().as_view(), name="login"),
path("logout/", views.LogoutAPIView().as_view(), name="logout")

since RegisterAPIView(), UserLoginView(), LogoutAPIView() are classes

you can also try

class RegisterAPIView(CreateAPIView):
model = User
queryset = User.objects.all()
serializer_class = UserCreationSerializer
@staticmethod
def post(self, request, *args, **kwargs):
....

in account.views

huangapple
  • 本文由 发表于 2023年6月12日 16:19:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定