Skip to content Skip to sidebar Skip to footer

Python Requests Module Login Using Session

I have a intranet application which i'm able to login using username/password. Im trying to access the same application using python requests passing my username/password but that

Solution 1:

You may need to send data among username and password (usually this data is generated randomly by the server and are inside <input type="hidden"> form elements) which we prevent the CSRF (cross-site request forgery) attack. You may also need to send cookies the Web server send to you.

So, to solve your problem you need to:

  1. Create a requests session to handle cookies;
  2. Request the login page (where the form is) and extract CSRF data;
  3. Post CSRF data among your credentials to the form action URL.

The code will be like this:

import requests

LOGIN_URL = '...' # put URL here # replace 'user' and 'pass' with form field names for credentials 
CREDENTIALS = {'user': '...', 'pass': '...'} 

session = requests.session() 

# get cookies and CSRF data
response = session.get(LOGIN_URL) 
csrf_data = ... # extract data from response.text in a dict# post data
csrf_data.update(CREDENTIALS) 
# you may change LOGIN_URL below with form's 'action' URL if they differ 
response = session.post(LOGIN_URL, data=csrf_data) 
# now check response.text to see if you're logged in 

There are many ways to extract CSRF data, such as: simple string manipulation, regular expressions or more specialized libraries such as lxml and BeautifulSoup (it depends on your input HTML and familiarity with the methods).

Post a Comment for "Python Requests Module Login Using Session"