0

{"detail": "CSRF Failed: CSRF cookie not set."} error in postman , i am using django rest_framework for developing ios android backend .

when i first time clear all cookies and use my login api is working fine enter image description here this will give me all info about user as per my code but after that when i try to hit any api using post method its always give crsf failed. enter image description here i also use csrf_exempt decorator in view and urls.py and also tried CsrfExemptMixin from brace package. my login code is

from django.contrib.auth import login,logout
from django.shortcuts import render,redirect
# local py files
from .models import *
from .serializers import *
from app_apis.models import *
# third party
from rest_framework import (generics,
permissions)
from knox.views import LoginView as KnoxLoginView
from rest_framework.response import Response
from rest_framework.authtoken.serializers import AuthTokenSerializer
from knox.models import AuthToken
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from braces.views import CsrfExemptMixin
from django.middleware.csrf import get_token
# Register API

class RegisterView(CsrfExemptMixin,generics.GenericAPIView):
    serializer_class=RegisterUserSerializer
    @method_decorator(csrf_exempt)
    def post(self,request,*args, **kwargs):
        serializer=self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        print
        logout(request)
        return Response({
        "user": UserSerializer(user, context=self.get_serializer_context()).data,
        "token": AuthToken.objects.create(user)[1]
        })


class LoginAPI(CsrfExemptMixin,KnoxLoginView):
    permission_classes = (permissions.AllowAny,)
    def get(self,request):
        example={
    "username":"user_name",
    "password":"Your Password" 
    }
        return Response(example)
    @method_decorator(csrf_exempt)
    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        user_id_main=user.id
        user_name=user.username
        user_data=[user_id_main,user_name]
        print(user_data)
        projects=ProjectTable.objects.filter(created_by_id=user_id_main).values_list('name')
        project_names=projects
        login(request, user)
        temp_list=super(LoginAPI, self).post(request, format=None)
        temp_list.data["project_list"]=project_names
        temp_list.data["user_data"]=user_data
        temp_list.data['csrf_token']=get_token(request)
        return Response({"data":temp_list.data})

# logout
def logout_view(request):
    logout(request)
    return redirect("user_profile:login")

please guide me . thanks in advance

pysaundary
  • 166
  • 2
  • 13
  • from what I can tell the issue is postman isn't getting the CSRF token. I believe there is a setting to disable CSRF tokens during test. The other option to to do a `GET` call then parse out the CSRF token. Best bet is the first option. This might help: https://stackoverflow.com/questions/28983158/how-to-disable-csrf-in-testing-django – Daniel Butler Oct 15 '20 at 17:31
  • thanks for your comment but in my case 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.SessionAuthentication', ] now it is working but i don't know how . – pysaundary Oct 15 '20 at 17:59

2 Answers2

1

Do not use rest_framework.authentication.SessionAuthentication in DEFAULT_AUTHENTICATION_CLASSES

Reference link: https://stackoverflow.com/a/56101653/217586

Devarshi
  • 16,440
  • 13
  • 72
  • 125
0

use corsheaders in installed app https://pypi.org/project/django-cors-headers/ use and follow the documentation

pysaundary
  • 166
  • 2
  • 13