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/
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?
Edit: I tried:
curl -c cookies.txt -b cookies.txt -L -d @login_form.txt http://my_domain/login/
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?
Passing username:password in a curl request is only good for HTTP Authentication, which isn't how most websites do auth these days. Instead, you'll have to post to the login page, get the cookie, then pass it back when requesting your desired page.
Here is a fully coded answer. The idea of the solution is:
-d
.Afterwards you can perform any request always using that CSRF token in the data (
$DJANGO_TOKEN
) or with a customX-CSRFToken
header. To log out simply delete the cookies file.Note that you need a referer (
-e
) to make Django's CSRF checks happy.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
Interesting background reading on Django's CSRF token is on docs.djangoproject.com.
Actually @Paterino answer is correct but it will not work on every implementation of sed. Instead
sed 's/^.*csrftoken\s*//')
we can usesed 's/^.*csrftoken[[:blank:]]*//')
which is more old fashioned. MacOSXs curl doesn't use escaping, so\n\t\s
don't work at all.