Wednesday, September 2, 2015

How to access a django python rest service that uses a login page for authentication

Today we bumped into a little challenge at work where we had to document a REST API in the portal we're developing.

The main problem was that this REST API did not authenticate with http auth. Instead, it relied on authenticating against the portal's (html based) login page, getting the cookie and consuming the REST API from there.

Here's how we solved the problem:
step 1- check the login page's html to see what the username and password form fields are called
(in our  case, they were called uName and pwd)

step2- customize the following bash script with your username, password and form fields
[root@userportal ~]# cat templates.sh
LOGIN_URL=http://localhost:8081/login/
YOUR_USER='username'
YOUR_PASS='password'
COOKIES=cookies.txt
CURL_BIN="curl -s -c $COOKIES -b $COOKIES -e $LOGIN_URL"

echo "Django Auth: get csrftoken ..."
$CURL_BIN $LOGIN_URL > /dev/null
DJANGO_TOKEN="csrfmiddlewaretoken=$(grep cid $COOKIES | sed 's/^.*cid\s*//')"
echo "DJANGO TOKEN is $DJANGO_TOKEN"

echo "######################################################"
echo "Performing login..."
$CURL_BIN \
    -d "$DJANGO_TOKEN&uName=$YOUR_USER&pwd=$YOUR_PASS" \
    -X POST $LOGIN_URL
echo "######################################################"

echo "Getting all templates..."
$CURL_BIN \
    -d "$DJANGO_TOKEN&..." \
    -X GET http://localhost:8081/api/templates/ | python -m json.tool
rm $COOKIES

[root@userportal ~]#

What this script basically does is:
- it connects to the login page and saves its cookies into cookies.txt
- then it reads that file and extracts cookie "cid" to get the value of the "csrfmiddlewaretoken" 
- and authenticates against the login page passing your username, password and the csrfmiddlewaretoken variables

At this point you'll be authenticated and the session will be saved in cookies.txt so all there's left to do is call out your REST web service! :o)

Hope this can be of help to someone else!

No comments:

Post a Comment