Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run django api from postman: CSRF verification failed

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',
    )
}
like image 385
zinon Avatar asked Oct 25 '17 07:10

zinon


People also ask

How do I authenticate with postman in Django?

Next, you fill out your credentials and hit the log in button. Your browser sends your credentials in the HTTP POST request it makes and adds a special CSRF header with the csrf token it got from Django when it first landed on this page. Django will see this and allow the login. To authenticate in Postman, the same general steps apply.

How to get CSRF token from csrftoken in Django?

Django sets csrftoken cookie on login. After logging in, we can see the csrf token from cookies in the Postman. We can grab this token and set it in headers manually. But this token has to be manually changed when it expires. This process becomes tedious to do it on an expiration basis.

How to use CSRF token in Postman?

In Test section of the postman, add these lines. var xsrfCookie = postman.getResponseCookie ("csrftoken"); postman.setEnvironmentVariable ('csrftoken', xsrfCookie.value); This extracts csrf token and sets it to an environment variable called csrftoken in the current environment. Now in our requests, we can use this variable to set the header.

How to prevent cross site request forgery (CSRF) in Django?

Django has inbuilt CSRF protection mechanism for requests via unsafe methods to prevent Cross Site Request Forgeries. When CSRF protection is enabled on AJAX POST methods, X-CSRFToken header should be sent in the request.


1 Answers

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)
like image 125
python_user Avatar answered Nov 02 '22 08:11

python_user