如何卷曲通过身份验证的Django应用程序? [英] How to cURL an Authenticated Django App?
问题描述
我有几个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包含用户名=用户名和放大器;密码=密码&安培; this_is_the_login_form = 1。不工作。不会产生cookie.txt的文件。而没有登录发生。你能告诉我使用卷曲你如何实现登录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?
推荐答案
下面是一个完全codeD的答案。该解决方案的想法是:
Here is a fully coded answer. The idea of the solution is:
- 您必须先用GET来获得所产生的饼干文件访问登录页面,
- 然后解析CSRF令牌出来的饼干文件
- 和使用做一个POST请求,传递数据与
-d
登录。
- you have to first visit the login page with GET to get the cookies file generated,
- then parse the CSRF token out of the cookies file
- and do the login using a POST request, passing the data with
-d
.
之后,您可以用执行总的要求,即CSRF令牌中的数据( 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/^.*csrftoken\s*//')"
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
我有这样的code,它使用一个文件提交的POST数据略微更安全的版本,因为在GitHub上一个要点是:的 Django的csrftoken登录-demo.bash
有趣的背景阅读Django的CSRF令牌是 docs.djangoproject.com 。
Interesting background reading on Django's CSRF token is on docs.djangoproject.com.
这篇关于如何卷曲通过身份验证的Django应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!