CAS automated login

Does your application uses CAS for authentication? Unless your CAS server has already been configured to allow for scripted login, automating login for applications that use CAS could be tough.

One way we automated the login operation for an application that uses CAS for authentication was to mimic the browser. Python is the language of choice at Qxf2 Services. To mimic the browser we chose the Mechanize module.


Install Mechanize

Python Package Index aka pip is the easiest way to install most modules in Python. If you are on a Windows machine, you can get pip by following the instructions here. Once you have pip installed and in your path, you can install Mechanize by opening a command prompt and running the command:

pip install -U Mechanize

Code snippet

Here is the actual code snippet for you to login to an application that sits behind CAS:


import mechanize
url = "YOUR_URL"
br = mechanize.Browser()
br.set_handle_robots(False) #You may need to do this
br.open(url)
br.select_form(nr=0) #Choose the right form number. You can choose the form via the name attribute too select_form(name="YOUR_FORM_NAME")
br['username']="USERNAME"
br['password']="FILL_PASSWORD_HERE"
br.method = "POST"
response = br.submit() #At this point you should see the html for the page that loads after login
print response.read()

WARNING: Mechanize has its limitations as an automated testing tool. The biggest drawback for web testers is that Mechanize does not mimic rendering of executed JavaScript in the browser. So DOM elements that are rendered by executing JavaScript cannot be accessed by Mechanize.

Leave a Reply

Your email address will not be published. Required fields are marked *