Friday, December 10, 2010

Getting authenticated programmatically in a form based authenticated webpage


Most of the websites have form based authentication. You must enter your credentials in a form to see your data. Did a hacker in you ever wished to log in this website through a script, so that you can download all your data or make changes or post some data to your account? Well, here is a simple way to achieve it using python.

 

import urllib, urllib2

# Create a opendirector instance to manage your cookie handlers
urlopener=urllib2.build_opener(urllib2.HTTPCookieProcessor())

# Let us add chrome user agent to header to fool the website. Some website may deny access to non browser user-agent.
urlopener.addheaders = [('User-agent','Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.12 (KHTML, like Gecko) Chrome/9.0.576.0 Safari/534.12')]

# Let install the instance of opendirector
urllib2.install_opener(urlopener)

# Let us prepare the credentials. It may be important to find all possible hidden fields and fill it appropriately
credentials = {'email/userid':'yourUserId', 'password':'yourPassword', '_hiddenfield1' :'hiddenValue1', '_hiddenField2': 'hiddenValue2'}

# Let us post the urlencoded credentials to the credential check page (may or may not be same as login page)

# Note we are using installed urlopener to access this. This will automatically manage cookies
f=urlopener.open('http://secureWeb.site/login',urllib.urlencode(credentials))
s=f.read()

###### Process 's' - http response body as you want. ####
f.close()

# Access protected page with same urlopener
f=urlopener.open('http://secureWeb.site/ProtectedPage')
s=f.read()

##### Process 's' - http response body as you want. Check if you could really access protected page here #####
f.close()


I hope it helps and you enjoy accessing your favourite website through your script.