我经常使用 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令牌?
发布评论