2

enter image description here

hello guys . I try to register a new Product in my app using DRF and Postman. when I send a request I get this error. the problem is just about my csrf_token. I'll be thankfull if you help me.....

this is my view

class ProductViewSet(viewsets.ModelViewSet):
    authentication_classes = (SessionAuthentication,TokenAuthentication) 
    permission_classes = [IsAdminUser]
    queryset = ProductInfo.objects.all().order_by('-id')
    serializer_class = ProductSerializer
    filter_backends = (filters.SearchFilter,)
    search_fields = ['title','code','owner__username']

I don't have any problem for GET request.

Brian Destura
  • 11,487
  • 3
  • 18
  • 34

2 Answers2

3

Django requires CSRF token in POST request by default. to avoid CSRF tokens.

Don't use SessionAuthentication as authentication class, coz, it will force you to add CSRF token.

If you still want to use SessionAuthentication then You can use it overrideing

def enforce_csrf(self, request): method

Try below this:

from rest_framework.authentication import SessionAuthentication

class CsrfExemptSessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        pass

and use it in your views:

authentication_classes = (CsrfExemptSessionAuthentication ,TokenAuthentication) 

If you want to use it globally, you can place it in your REST_FRAMEWORK settings.py file like this:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'myapp.path-to-file.CsrfExemptSessionAuthentication'
    ],
}

Please make sure you add correct file path in the REST_FRAMEWORK settings

To authenticate with the token.

You must request like this:

curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b'

Also make sure you added this in your INSTALLED_APP:

INSTALLED_APPS = [
    ''''
    'rest_framework',
    'rest_framework.authtoken',
]

More details can be found here: https://www.django-rest-framework.org/api-guide/authentication/

1

Because you don't need csrf_token for GET method.

you can set your csrf_token in header like this:

X-CSRFToken: your_csrf_value  

so instead of using Cookie add X-CSRFToken to your header in POSTMAN.

Mojtaba Arezoomand
  • 2,140
  • 8
  • 23