Is there any way for using csrf_token in django_rest_framework without using front end in django?

I am using django framework for making a rest api for registration but when i do that csrf_token is not set since front end is not set.

So it causes post request not to execute in POSTMAN. I want some way to make my rest api without disabling the csrf in my program.

I tried to copy the csrf token into cookie and access that cookie to verify from POSTMAN that but it is not working for POST request also.

I tried to set the header in postman but it also turns up to be GET request only.

from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
@csrf_exempt
def addToTable(request):
    response = HttpResponse('blah')
    response.set_cookie('csrftoken', get_token(request))
    c = get_token(request)
    response.set_cookie('csrftoken', c)
    d = request.COOKIES['csrftoken']
    if request.method == 'POST':
        row_data = request.read()
        data = json.loads(row_data)
        a = data['MyName']
        b = data['MyPassword']
        post = Post()
        post.MyName = a
        post.MyPassword = b
        post.save()
        response.delete_cookie('csrftoken')
        return JsonResponse({'My Name ':a+ "and " + c + " is added to database and it is a post request."})
    else:
        response.delete_cookie('csrftoken')
        return JsonResponse({'username ': d + " Data is not added to database and it is a get request." + c}) 
    return 0

i want my rest api work for registration when i pass json data to it from POSTMAN without disabling the csrf.

1 answer

  • answered 2019-07-09 05:26 sachin mathew

    You need to send CSRF token in the headers of postman.X-CSRFToken is the key and the value is CSRF token from the cookie.