如何从命令行获取CSRF令牌?

编程入门 行业动态 更新时间:2024-10-25 16:19:53
本文介绍了如何从命令行获取CSRF令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我经常使用 curl 来测试我的应用程序,过去我不得不用 csrf_exempt 。我真的不想这样做,因为我有一种讨厌的感觉,我会忘记在部署中这样做,并享受一生的CSRF地狱。

I'm frequently testing my application using curl and in the past I've had to simply wrap my views with csrf_exempt. I really don't want to do this, as I have a nasty feeling that I'll forget to do this in deployment and enjoy a lifetime of CSRF hell.

是有一种方法可以使用Django的shell命令请求一个CSRF令牌?我想得到一个令牌,我可以用我的 curl 请求来安全地测试事情。

Is there a way for me to request a CSRF token using Django's shell commands? I'd like to get a token I could send with my curl requests to test things safely.

推荐答案

向表单URL发出初始GET请求,以填充cookie jar:

Make an initial GET request to the form URL in order to fill the cookie jar:

$ curl example/some-form/ -o /dev/null -c cookies.txt -s

获取 csrftoken cookie的值:

Get the value of the csrftoken cookie:

$ grep csrftoken cookies.txt | cut -f 7 YQkfXZCKtPP0hC30NmH10jSWuf6yJA5E

发行POST时,只需添加一个 csrfmiddlewaretoken 字段与此值(并使用相同的cookie jar)。

When issuing a POST, just include a csrfmiddlewaretoken field with this value (and use the same cookie jar).

我使用相同的技巧来写端到端使用请求库进行测试。

I use the same trick to write end-to-end tests using the requests library.

更多推荐

如何从命令行获取CSRF令牌?

本文发布于:2023-10-29 09:43:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539369.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   命令行   CSRF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!