且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何卷曲通过身份验证的Django应用程序?

更新时间:2023-12-02 10:25:34

下面是一个完全codeD的答案。该解决方案的想法是:

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


  1. 您必须先用GET来获得所产生的饼干文件访问登录页面,

  2. 然后解析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/^.*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.