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

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

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:

  1. import os
  2. from pathlib import Path
  3. BASE_DIR = Path(__file__).resolve().parent.parent
  4. SECRET_KEY = 'django-insecure-n^s54jl394v4!_#n^78&7o-9swqt*ckq1pcyx_g3@vhb$8gct5'
  5. DEBUG = True
  6. ALLOWED_HOSTS = []
  7. INSTALLED_APPS = [
  8. 'django.contrib.admin',
  9. 'django.contrib.auth',
  10. 'django.contrib.contenttypes',
  11. 'django.contrib.sessions',
  12. 'django.contrib.messages',
  13. 'django.contrib.staticfiles',
  14. "rest_framework",
  15. "accounts",
  16. "contents",
  17. ]
  18. MIDDLEWARE = [
  19. 'django.middleware.security.SecurityMiddleware',
  20. 'django.contrib.sessions.middleware.SessionMiddleware',
  21. 'django.middleware.common.CommonMiddleware',
  22. 'django.middleware.csrf.CsrfViewMiddleware',
  23. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  24. 'django.contrib.messages.middleware.MessageMiddleware',
  25. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  26. ]
  27. ROOT_URLCONF = 'config.urls'
  28. TEMPLATES = [
  29. {
  30. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  31. 'DIRS': [],
  32. 'APP_DIRS': True,
  33. 'OPTIONS': {
  34. 'context_processors': [
  35. 'django.template.context_processors.debug',
  36. 'django.template.context_processors.request',
  37. 'django.contrib.auth.context_processors.auth',
  38. 'django.contrib.messages.context_processors.messages',
  39. ],
  40. },
  41. },
  42. ]
  43. REST_FRAMEWORK = {
  44. "DEFAULT_AUTHENTICATION_CLASSES": [
  45. "rest_framework.authentication.SessionAuthentication"
  46. ]
  47. }
  48. WSGI_APPLICATION = 'config.wsgi.application'
  49. DATABASES = {
  50. 'default': {
  51. 'ENGINE': 'django.db.backends.sqlite3',
  52. 'NAME': BASE_DIR / 'db.sqlite3',
  53. }
  54. }
  55. AUTH_PASSWORD_VALIDATORS = [
  56. {
  57. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  58. },
  59. {
  60. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  61. },
  62. {
  63. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  64. },
  65. {
  66. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  67. },
  68. ]
  69. LANGUAGE_CODE = 'en-us'
  70. STATIC_ROOT = os.path.join("static")
  71. TIME_ZONE = 'UTC'
  72. USE_I18N = True
  73. USE_TZ = True
  74. STATIC_URL = 'static/'
  75. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

and here is my urls.py:

  1. from django.contrib import admin
  2. from django.urls import path, include
  3. urlpatterns = [
  4. path('admin/', admin.site.urls),
  5. path("accounts/", include("accounts.urls")),
  6. path("contents/", include("contents.urls")),
  7. ]

here is accounts.views:

  1. from rest_framework.response import Response
  2. from rest_framework.generics import CreateAPIView
  3. from rest_framework import status
  4. from rest_framework.views import APIView
  5. from django.contrib.auth.models import User
  6. from django.contrib.auth import login, logout, authenticate
  7. from accounts.serializers import UserCreationSerializer, UserLoginSerializer
  8. class RegisterAPIView(CreateAPIView):
  9. model = User
  10. queryset = User.objects.all()
  11. serializer_class = UserCreationSerializer
  12. def post(self, request, *args, **kwargs):
  13. serializer = self.serializer_class(data=request.data)
  14. serializer.is_valid(raise_exception=True)
  15. self.perform_create(serializer)
  16. username = serializer.validated_data.get("username")
  17. password = serializer.validated_data.get("password")
  18. user = authenticate(username=username, password=password)
  19. if user:
  20. login(request, user)
  21. return Response(
  22. data={"msg": "User created successfully and logged in"},
  23. status=status.HTTP_201_CREATED
  24. )
  25. return Response(
  26. data={"msg": "User Creation process failed"}, status=status.HTTP_400_BAD_REQUEST
  27. )
  28. def perform_create(self, serializer):
  29. serializer.save()
  30. class UserLoginView(APIView):
  31. def post(self, request):
  32. serializer = UserLoginSerializer(data=request.data)
  33. print(request.user.is_authenticated)
  34. if serializer.is_valid():
  35. username = serializer.validated_data['username']
  36. password = serializer.validated_data['password']
  37. user = authenticate(username=username, password=password)
  38. if user is not None:
  39. login(request, user)
  40. return Response({'message': 'User logged in successfully'}, status=status.HTTP_200_OK)
  41. else:
  42. return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
  43. else:
  44. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  45. class LogoutAPIView(APIView):
  46. model = User
  47. def get(self, request, *args, **kwargs):
  48. logout(request)
  49. return Response(data={"msg": "User logged out successfully!"}, status=status.HTTP_200_OK)

accounts.urls

  1. from django.urls import path
  2. from accounts import views
  3. urlpatterns = [
  4. path("register/", views.RegisterAPIView.as_view(), name="register"),
  5. path("login/", views.UserLoginView.as_view(), name="login"),
  6. path("logout/", views.LogoutAPIView.as_view(), name="logout")
  7. ]

accounts.serializers

  1. from rest_framework import serializers
  2. from django.contrib.auth.models import User
  3. from django.contrib.auth import authenticate
  4. class UserCreationSerializer(serializers.ModelSerializer):
  5. class Meta:
  6. fields = ["username", "first_name", "last_name", "email", "password"]
  7. model = User
  8. def save(self, **kwargs):
  9. user = self.Meta.model
  10. return user.objects.create_user(
  11. username=self.validated_data.get("username"),
  12. email=self.validated_data.get("email"),
  13. password=self.validated_data.get("password"),
  14. first_name=self.validated_data.get("first_name"),
  15. last_name=self.validated_data.get("last_name"),
  16. )
  17. class UserLoginSerializer(serializers.Serializer):
  18. username = serializers.CharField(max_length=150)
  19. password = serializers.CharField(max_length=128, write_only=True)
  20. def validate(self, data):
  21. username = data.get('username')
  22. password = data.get('password')
  23. if username and password:
  24. user = authenticate(username=username, password=password)
  25. if not user:
  26. raise serializers.ValidationError("Invalid username or password.")
  27. else:
  28. raise serializers.ValidationError("Both username and password are required.")
  29. data['user'] = user
  30. 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:

  1. import os
  2. from pathlib import Path
  3. BASE_DIR = Path(__file__).resolve().parent.parent
  4. SECRET_KEY = 'django-insecure-n^s54jl394v4!_#n^78&7o-9swqt*ckq1pcyx_g3@vhb$8gct5'
  5. DEBUG = True
  6. ALLOWED_HOSTS = []
  7. INSTALLED_APPS = [
  8. 'django.contrib.admin',
  9. 'django.contrib.auth',
  10. 'django.contrib.contenttypes',
  11. 'django.contrib.sessions',
  12. 'django.contrib.messages',
  13. 'django.contrib.staticfiles',
  14. "rest_framework",
  15. "accounts",
  16. "contents",
  17. ]
  18. MIDDLEWARE = [
  19. 'django.middleware.security.SecurityMiddleware',
  20. 'django.contrib.sessions.middleware.SessionMiddleware',
  21. 'django.middleware.common.CommonMiddleware',
  22. 'django.middleware.csrf.CsrfViewMiddleware',
  23. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  24. 'django.contrib.messages.middleware.MessageMiddleware',
  25. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  26. ]
  27. ROOT_URLCONF = 'config.urls'
  28. TEMPLATES = [
  29. {
  30. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  31. 'DIRS': [],
  32. 'APP_DIRS': True,
  33. 'OPTIONS': {
  34. 'context_processors': [
  35. 'django.template.context_processors.debug',
  36. 'django.template.context_processors.request',
  37. 'django.contrib.auth.context_processors.auth',
  38. 'django.contrib.messages.context_processors.messages',
  39. ],
  40. },
  41. },
  42. ]
  43. REST_FRAMEWORK = {
  44. "DEFAULT_AUTHENTICATION_CLASSES": [
  45. "rest_framework.authentication.SessionAuthentication"
  46. ]
  47. }
  48. WSGI_APPLICATION = 'config.wsgi.application'
  49. DATABASES = {
  50. 'default': {
  51. 'ENGINE': 'django.db.backends.sqlite3',
  52. 'NAME': BASE_DIR / 'db.sqlite3',
  53. }
  54. }
  55. AUTH_PASSWORD_VALIDATORS = [
  56. {
  57. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  58. },
  59. {
  60. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  61. },
  62. {
  63. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  64. },
  65. {
  66. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  67. },
  68. ]
  69. LANGUAGE_CODE = 'en-us'
  70. STATIC_ROOT = os.path.join("static")
  71. TIME_ZONE = 'UTC'
  72. USE_I18N = True
  73. USE_TZ = True
  74. STATIC_URL = 'static/'
  75. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

and here is my urls.py:

  1. from django.contrib import admin
  2. from django.urls import path, include
  3. urlpatterns = [
  4. path('admin/', admin.site.urls),
  5. path("accounts/", include("accounts.urls")),
  6. path("contents/", include("contents.urls")),
  7. ]

here is accounts.views:

  1. from rest_framework.response import Response
  2. from rest_framework.generics import CreateAPIView
  3. from rest_framework import status
  4. from rest_framework.views import APIView
  5. from django.contrib.auth.models import User
  6. from django.contrib.auth import login, logout, authenticate
  7. from accounts.serializers import UserCreationSerializer, UserLoginSerializer
  8. class RegisterAPIView(CreateAPIView):
  9. model = User
  10. queryset = User.objects.all()
  11. serializer_class = UserCreationSerializer
  12. def post(self, request, *args, **kwargs):
  13. serializer = self.serializer_class(data=request.data)
  14. serializer.is_valid(raise_exception=True)
  15. self.perform_create(serializer)
  16. username = serializer.validated_data.get("username")
  17. password = serializer.validated_data.get("password")
  18. user = authenticate(username=username, password=password)
  19. if user:
  20. login(request, user)
  21. return Response(
  22. data={"msg": "User created successfully and logged in"},
  23. status=status.HTTP_201_CREATED
  24. )
  25. return Response(
  26. data={"msg": "User Creation process failed"}, status=status.HTTP_400_BAD_REQUEST
  27. )
  28. def perform_create(self, serializer):
  29. serializer.save()
  30. class UserLoginView(APIView):
  31. def post(self, request):
  32. serializer = UserLoginSerializer(data=request.data)
  33. print(request.user.is_authenticated)
  34. if serializer.is_valid():
  35. username = serializer.validated_data['username']
  36. password = serializer.validated_data['password']
  37. user = authenticate(username=username, password=password)
  38. if user is not None:
  39. login(request, user)
  40. return Response({'message': 'User logged in successfully'}, status=status.HTTP_200_OK)
  41. else:
  42. return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
  43. else:
  44. return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  45. class LogoutAPIView(APIView):
  46. model = User
  47. def get(self, request, *args, **kwargs):
  48. logout(request)
  49. return Response(data={"msg": "User logged out successfully!"}, status=status.HTTP_200_OK)

accounts.urls

  1. from django.urls import path
  2. from accounts import views
  3. urlpatterns = [
  4. path("register/", views.RegisterAPIView.as_view(), name="register"),
  5. path("login/", views.UserLoginView.as_view(), name="login"),
  6. path("logout/", views.LogoutAPIView.as_view(), name="logout")
  7. ]

accounts.serializers

  1. from rest_framework import serializers
  2. from django.contrib.auth.models import User
  3. from django.contrib.auth import authenticate
  4. class UserCreationSerializer(serializers.ModelSerializer):
  5. class Meta:
  6. fields = ["username", "first_name", "last_name", "email", "password"]
  7. model = User
  8. def save(self, **kwargs):
  9. user = self.Meta.model
  10. return user.objects.create_user(
  11. username=self.validated_data.get("username"),
  12. email=self.validated_data.get("email"),
  13. password=self.validated_data.get("password"),
  14. first_name=self.validated_data.get("first_name"),
  15. last_name=self.validated_data.get("last_name"),
  16. )
  17. class UserLoginSerializer(serializers.Serializer):
  18. username = serializers.CharField(max_length=150)
  19. password = serializers.CharField(max_length=128, write_only=True)
  20. def validate(self, data):
  21. username = data.get('username')
  22. password = data.get('password')
  23. if username and password:
  24. user = authenticate(username=username, password=password)
  25. if not user:
  26. raise serializers.ValidationError("Invalid username or password.")
  27. else:
  28. raise serializers.ValidationError("Both username and password are required.")
  29. data['user'] = user
  30. 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中出现了问题,使用以下代码:

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

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

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

放在account.views中。

英文:

an issue is in account.urls,
use

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

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

you can also try

  1. class RegisterAPIView(CreateAPIView):
  2. model = User
  3. queryset = User.objects.all()
  4. serializer_class = UserCreationSerializer
  5. @staticmethod
  6. def post(self, request, *args, **kwargs):
  7. ....

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:

确定