Run django api from postman: CSRF verification failed

11,138

Solution 1

Try this.

from django.views.decorators.csrf import csrf_exempt
class ApiUserRegister(APIView):
permission_classes = ()
serializer_class = RegisterUserSerializer

    @csrf_exempt
    def post(self, request):
        serializer = RegisterUserSerializer(data=request.data)

Solution 2

To make AJAX requests, you need to include CSRF token in the HTTP header, as described in the Django documentation.

1st option

enter image description here

2nd option enter image description here

Share:
11,138
zinon
Author by

zinon

Ph.D. on adaptive video delivery for real-time applications and mHealth systems.

Updated on June 17, 2022

Comments

  • zinon
    zinon almost 2 years

    I'm trying to run an api using postman. My application is developed in django 1.11.6 using python 3.5.

    My app is installed on an ubuntu server. I have no login mechanism to create a csrf token.

    These are the steps that I follow:

    1. Click on "import" tab on the upper left side.
    2. Select the Raw Text option and paste my cURL command.
    3. Hit import and I have the command in your Postman builder
    4. Press send button.

    My curl command is:

    curl -i -H 'Accept: application/json; indent=4' -X POST  https://127.0.0.1/users/:register/ -d "id=111&firstname=zinonas&yearofbirth=2007&lastname=Antoniou&othernames="
    

    The error I get is Forbidden (403) - CSRF verification failed. Request aborted.

    When I run the curl command via cygwin, it's working properly.

    This is the view function that I'm using:

    class ApiUserRegister(APIView):
        permission_classes = ()
        serializer_class = RegisterUserSerializer
    
        def post(self, request):
            serializer = RegisterUserSerializer(data=request.data)
            # Check format and unique constraint
            serializer.is_valid(raise_exception=True)
            data = serializer.data
    
            if User.objects.filter(id=data['id']).exists():
                user = User.objects.get(id=data['id'])
                is_new = "false"
                resp_status = status.HTTP_200_OK
            else:
                user = User.objects.create(id=data['id'],
                                           firstname=data['firstname'],
                                           yearofbirth=data['yearofbirth'],
                                           lastname=data['lastname'],
                                           othernames=data['othernames'])
                user.save()
                is_new = "true"
                resp_status = status.HTTP_201_CREATED
            resp = {"user": serializer.get_serialized(user),
                    "isnew": is_new}
            return Response(resp, status=resp_status)
    

    In settings.py I have:

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        ),
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'rest_framework.authentication.SessionAuthentication',
            'rest_framework.authentication.TokenAuthentication',
            'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        )
    }
    
  • zinon
    zinon over 6 years
    Using this I get name 'csrf_exempt' is not defined error.
  • zinon
    zinon over 6 years
    I get error 'function' object has no attribute 'as_view'.In urls.py I have this line: url(r':register/$', views.ApiUserRegister.as_view(), name='register-user')
  • zinon
    zinon over 6 years
    No I get the error The keyword argument "name" must be the name of a method of the decorated class: <class 'users.views.ApiUserRegister'>. Got '' instead
  • zinon
    zinon over 6 years
    Unfortunately, no. I set @method_decorator(csrf_exempt, name="post") and now I get once again Forbidden (403) CSRF verification failed. Request aborted.
  • zinon
    zinon over 6 years
    I'm not using jQuery. I created an API to using via `android' app.
  • zinon
    zinon over 6 years
    Is braces a module that I can install using pip3?
  • mohammedgqudah
    mohammedgqudah over 6 years
    pip install django-braces
  • zinon
    zinon over 6 years
    Still no luck CSRF verification failed. Request aborted.
  • mohammedgqudah
    mohammedgqudah over 6 years
    csrfExpemntMixin should be the first then ApiView
  • zinon
    zinon over 6 years
    Yes, that's what I did.
  • zinon
    zinon over 6 years
    Can you please give me an example?
  • mohammedgqudah
    mohammedgqudah over 6 years
    try adding authentication_classes = [] to the class
  • LennyLip
    LennyLip over 6 years
    1. get csrftoken cookie with safe GET query (view can use ensure_csrf_cookie decorator) 2. use csrftoken in new POST query
  • python_user
    python_user over 6 years
  • zinon
    zinon over 6 years
    I'm not using any template.
  • Brian H.
    Brian H. over 5 years
    The answer does not address Postman, which is a key part of the question.
  • Mohammed Shareef C
    Mohammed Shareef C over 5 years
    This is about rest API. So, why bother about CSRF token?
  • LennyLip
    LennyLip over 5 years
    @MohammedShareefC yes, for android app we don't need CSRF, but security.stackexchange.com/questions/166724/…