如何卷曲经过身份验证的 Django 应用程序? [英] How to cURL an Authenticated Django App?

查看:22
本文介绍了如何卷曲经过身份验证的 Django 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 cURL 测试一些 API.我尝试按如下方式执行 GET:

I've a few APIs I'd like to test with cURL. I tried doing a GET as follows:

curl --user username:password --request GET http://my_domain/get_result/52d6428f3ea9a008358ad2d8/

在服务器上,它显示了一个302"(这意味着重定向,对吧?).我猜它被重定向到登录/"页面.

On the server, it showed a '302' (which means redirection, right?). I'm guessing it redirected to the 'login/' page.

完成这项工作的正确方法是什么?

What is the proper way of getting this done?

编辑:我试过:

curl -c cookies.txt -b cookies.txt -L -d @login_form.txt http://my_domain/login/

其中 login_form.txt 包含username=username&password=password&this_is_the_login_form=1".不起作用.没有生成 cookies.txt 文件.并且没有登录发生.你能告诉我你是如何使用 cURL 登录 Django 的吗?

where login_form.txt contains "username=username&password=password&this_is_the_login_form=1". Doesn't work. No cookies.txt files generated. And no login happening. Can you tell me how you achieve login to Django using cURL?

推荐答案

这是一个完全编码的答案.解决思路是:

Here is a fully coded answer. The idea of the solution is:

  1. 您必须首先使用 GET 访问登录页面以获取生成的 cookie 文件,
  2. 然后从 cookie 文件中解析 CSRF 令牌
  3. 并使用 POST 请求进行登录,使用 -d 传递数据.
  1. you have to first visit the login page with GET to get the cookies file generated,
  2. then parse the CSRF token out of the cookies file
  3. and do the login using a POST request, passing the data with -d.

之后,您可以始终使用数据中的 CSRF 令牌 ($DJANGO_TOKEN) 或使用自定义 X-CSRFToken 标头执行任何请求.要注销,只需删除 cookie 文件.

Afterwards you can perform any request always using that CSRF token in the data ($DJANGO_TOKEN) or with a custom X-CSRFToken header. To log out simply delete the cookies file.

请注意,您需要一个引用 (-e) 才能使 Django 的 CSRF 检查满意.

Note that you need a referer (-e) to make Django's CSRF checks happy.

LOGIN_URL=https://yourdjangowebsite.com/login/
YOUR_USER='username'
YOUR_PASS='password'
COOKIES=cookies.txt
CURL_BIN="curl -s -c $COOKIES -b $COOKIES -e $LOGIN_URL"

echo -n "Django Auth: get csrftoken ..."
$CURL_BIN $LOGIN_URL > /dev/null
DJANGO_TOKEN="csrfmiddlewaretoken=$(grep csrftoken $COOKIES | sed 's/^.*csrftokens*//')"

echo -n " perform login ..."
$CURL_BIN 
    -d "$DJANGO_TOKEN&username=$YOUR_USER&password=$YOUR_PASS" 
    -X POST $LOGIN_URL

echo -n " do something while logged in ..."
$CURL_BIN 
    -d "$DJANGO_TOKEN&..." 
    -X POST https://yourdjangowebsite.com/whatever/

echo " logout"
rm $COOKIES

我有一个稍微更安全的代码版本,它使用一个文件来提交 POST 数据,作为 GitHub 上的 Gist:django-csrftoken-login-demo.bash

I have a slightly more secure version of this code, which uses a file for submitting the POST data, as a Gist on GitHub: django-csrftoken-login-demo.bash

有关 Django CSRF 令牌的有趣背景阅读位于 docs.djangoproject.com.

Interesting background reading on Django's CSRF token is on docs.djangoproject.com.

这篇关于如何卷曲经过身份验证的 Django 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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