CSRF验证失败。请求中止。当我发送POST请求时 [英] CSRF verification failed. Request aborted. When I send POST request

查看:566
本文介绍了CSRF验证失败。请求中止。当我发送POST请求时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从android应用程序向我的服务器发送POST请求,但出现此错误:





POST看起来像:



如果您的POST不需要身份验证,则可以使用先前的GET请求中的 csrftoken


I am sending a POST request to my server from an android application, but I am getting this error:

The POST looks like: http://example/my_page_url/1000 Where the 1000 is an ID.

This is my views method:

def inventory(request, cross_id):

    text_file = open("test.txt", "w")
    text_file.write('POST Received')

    text_file.write(cross_id.__str__())
    text_file.close()

    return render(request, 'Inventory.html', {})

my template code:

<form action='' method="POST">

     <button type="submit" id="btn_save" name="btn_save">Save</button>

    {% csrf_token %}

</form>

Actually, I don't really need to call a template, because I want to perform something on the server only. But I am calling the template just to prevent any errors for now.

I have read the other answers for the same problem but all of them have missed the CSRF token in the template or something else in the views method, but I believe the case is different here.

解决方案

You need to add the X-CSRFToken header to all your POST requests.

You can get the appropriate value for this header from the cookie named csrftoken.

To test this in Postman, you need to enable the Interceptor plugin (top right corner).

Once you have it installed, make a GET request to /admin/login/ (make sure you are logged out from the site in the browser). In the cookies section you should see a cookie named csrftoken, copy its value.

Now, set the request type to POST for the same URL (/admin/login), add a header named X-CSRFToken with the value you copied earlier. Set the username and password fields in the Body section and hit send.

If your POST do not require authentication, you can use the csrftoken from an earlier GET request.

这篇关于CSRF验证失败。请求中止。当我发送POST请求时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆