How to use curl with Django, csrf tokens and POST requests

前端 未结 6 2049
一个人的身影
一个人的身影 2020-12-07 13:10

I\'m using curl to test one of my Django forms. The calls I\'ve tried (with errors from each, and over multiple lines for readability):

(1):

curl
-d          


        
6条回答
  •  误落风尘
    2020-12-07 14:02

    I worked with curl like this

    • You have to submit csrftoken in header as X-CSRFToken.
    • You have to submit form data in JSON format. Demo,

    First we will fetch csrf_token & store in cookie.txt (or cookie.jar as they call it)

    $ curl -c cookie.txt http://localhost.com:8000/ 
    

    cookie.txt content

    # Netscape HTTP Cookie File
    # http://curl.haxx.se/docs/http-cookies.html
    # This file was generated by libcurl! Edit at your own risk.
    localhost.com  FALSE   /   FALSE   1463117016  csrftoken   vGpifQR12BxT07moOohREGmuKp8HjxaE
    

    Next we resend the username, password in json format. (you may send it in normal way). Check the json data escape.

    $curl --cookie cookie.txt http://localhost.com:8000/login/   -H "Content-Type: application/json" -H "X-CSRFToken: vGpifQR12BxT07moOohREGmuKp8HjxaE" -X POST -d "{\"username\":\"username\",\"password\":\"password\"}" 
    {"status": "success", "response_msg": "/"}
    $
    

    you can store the returns new csrf_token session cookie in same file or new file (I have stored in same file using option -c.)

    $curl --cookie cookie.txt http://localhost.com:8000/login/   -H "Content-Type: application/json" -H "X-CSRFToken: kVgzzB6MJk1RtlVnyzegEiUs5Fo3VRqF" -X POST -d "{\"username\":\"username\",\"password\":\"password\"}" -c cookie.txt
    

    -Content of cookie.txt

    # Netscape HTTP Cookie File
    # http://curl.haxx.se/docs/http-cookies.html
    # This file was generated by libcurl! Edit at your own risk.
    
    localhost.com  FALSE   /   FALSE   1463117016  csrftoken   vGpifQR12BxT07moOohREGmuKp8HjxaE
    #HttpOnly_localhost.com    FALSE   /   FALSE   1432877016  sessionid   cg4ooly1f4kkd0ifb6sm9p
    

    When you store new csrf_token & session id cookie in cookie.txt, you can use same cookie.txt across the website.

    You am reading cookies from previous request from cookie.txt (--cookie) and writing new cookies from response in same cookie.txt (-c).

    Reading & submitting form now works with csrf_token & session id.

    $curl --cookie cookie.txt http://localhost.com:8000/home/
    

提交回复
热议问题