有什么方法可以在django_rest_framework中使用csrf_token而无需在django中使用前端?

时间:2019-07-09 04:36:22

标签: python django django-rest-framework django-authentication django-csrf

我正在使用django框架制作用于注册的rest api,但是当我这样做时,csrf_token尚未设置,因为未设置前端。

因此它导致发布请求不在POSTMAN中执行。我想要某种方法来制作我的rest api,而无需在程序中禁用csrf。

我试图将csrf令牌复制到cookie中,并访问该cookie以从POSTMAN进行验证,但它也不适用于POST请求。

我试图在邮递员中设置标题,但它也变成了仅GET请求。

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

当我从POSTMAN传递json数据而不禁用csrf时,我希望我的其余api用于注册。

1 个答案:

答案 0 :(得分:0)

您需要在邮递员的标头中发送CSRF tokenX-CSRFToken是密钥,值是cookie中的CSRF令牌。

相关问题