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

DjangoCurlDjango FormsCsrfDjango Csrf

Django Problem Overview


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 "{\"email\":\"test@test.com\"}"
--header "X-CSRFToken: [triple checked value from the source code of a page I already loaded from my Django app]"
--cookie "csrftoken=[same csrf value as above]"
http://127.0.0.1:8083/registrations/register/

(with http header and csrftoken in cookie) results in a 400 error with no data returned.

(2):

curl
-d "{a:1}"
--header "X-CSRFToken:[as above]"
--cookie "csrftoken=[as above];sessionid=[from header inspection in Chrome]"
http://127.0.0.1:8083/registrations/register/

(as in (1) but no spaces in header property declaration, and with sessionid in cookie too) results in the same 400 error with no data returned.

(3):

curl
-d "{a:1}"
--header "X-CSRFToken:[as above]"
http://127.0.0.1:8083/registrations/register/

(only http header with X-CSRFToken, no cookie) results in error code 403, with message: CSRF cookie not set.

How can I test my form with curl? What factors am I not considering besides cookie values and http headers?

Django Solutions


Solution 1 - Django

A mixture of Damien's response and your example number 2 worked for me. I used a simple login page to test, I expect that your registration view is similar. Damien's response almost works, but is missing the sessionid cookie.

I recommend a more robust approach. Rather than manually entering the cookies from other requests, try using curl's built in cookie management system to simulate a complete user interaction. That way, you reduce the chance of making an error:

$ curl -v -c cookies.txt -b cookies.txt host.com/registrations/register/
$ curl -v -c cookies.txt -b cookies.txt -d "[email protected]&a=1&csrfmiddlewaretoken=<token from cookies.txt>" host.com/registrations/register/

The first curl simulates the user first arriving at the page with a GET request, and all the necessary cookies are saved. The second curl simulates filling in the form fields and sending them as a POST. Note that you have to include the csrfmiddlewaretoken field in the POST data, as suggested by Damien.

Solution 2 - Django

Try:

curl
 -d "[email protected]&a=1"
 http://127.0.0.1:8083/registrations/register/

Notice especially the format of the -d argument.

However, this probably won't work, as your view likely needs a POST request instead of a GET request. Since it will be modifying data, not just returning information.

CSRF protection is only required for 'unsafe' requests (POST, PUT, DELETE). It works by checking the 'csrftoken' cookie against either the 'csrfmiddlewaretoken' form field or the 'X-CSRFToken' http header.

So:

curl
 -X POST
 -d "[email protected]&a=1&csrfmiddlewaretoken={inserttoken}"
 --cookie "csrftoken=[as above]"
 http://127.0.0.1:8083/registrations/register/

It's also possible to use --header "X-CSRFToken: {token}" instead of including it in the form data.

Solution 3 - Django

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/

Solution 4 - Django

Here is how i did it, using the rest framework tutorial

open a browser e.g. chrome then pressing F12 open the developer tab and monitor the Network, login using your user credentials and get your CRSF token from monitoring the POST

then in curl execute:

curl http://127.0.0.1:8000/snippets/ \
 -X POST \
 -H "Content-Type: application/json" \
 -H "Accept: text/html,application/json" \
 -H "X-CSRFToken: the_token_value" \
 -H "Cookie: csrftoken=the_token_value" \
 -u your_user_name:your_password \
 -d '{"title": "first cookie post","code": "print hello world"}' 

I think its cleaner to not put the token in the body but rather the header using X-CSRFToken

Solution 5 - Django

curl-auth-csrf is a Python-based open-source tool capable of doing this for you: "Python tool that mimics cURL, but performs a login and handles any Cross-Site Request Forgery (CSRF) tokens. Useful for scraping HTML normally only accessible when logged in."

This would be your syntax:

echo -n YourPasswordHere | ./curl-auth-csrf.py -i http://127.0.0.1:8083/registrations/register/ -d '[email protected]&a=1' http://127.0.0.1:8083/registrations/register/

This will pass along the POST data as listed, but also to include the password passed via stdin. I assume that the page you visit after "login" is the same page.

Full disclosure: I'm the author of curl-auth-csrf.

Solution 6 - Django

X-CSRFToken in headers just need be the same with csrftoken in cookie.

Example:

curl -v http://www.markjour.com/login/ -H "X-CSRFToken: 123" -b "csrftoken=123" -d "username=admin&password=admin"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTrindazView Question on Stackoverflow
Solution 1 - DjangoKevin S.View Answer on Stackoverflow
Solution 2 - DjangoDamien AyersView Answer on Stackoverflow
Solution 3 - DjangoNetroView Answer on Stackoverflow
Solution 4 - DjangoDr ManhattanView Answer on Stackoverflow
Solution 5 - Djangoj0nam1elView Answer on Stackoverflow
Solution 6 - DjangomarkjourView Answer on Stackoverflow