import requests

target_url = ""
data_dict = {"csrfmiddlewaretoken": "bbbfeed6e1aea50f14a51a331054022c", "username": "admin", "password": "password", "Login": "Submit"}
response = requests.post(target_url, data=data_dict)

I am using the code above to log in into here: After doing some reading, I saw it was because it failed at the CSRF check, so I implemented it to my data_dict.

Here's the problem: now, even with the CSRF check added it's giving me the same

invalid CRSF token

problem as before.

Whats happening? Thanks in advanced.


In order to login you need to also submit a hidden field called user_token which looks like this:

<input type='hidden' name='user_token' value='random_value_here' />

The value changes every time you refresh the page, so you need a little web-scraping to do what you are looking for. The following code uses bs4 to scrape the page and get the correct user_token value and then logs in successfully to the application:

import requests
from bs4 import BeautifulSoup

url = ""

def get_token(source):
    soup = BeautifulSoup(source, "html.parser")
    return soup.find('input', { "type" : "hidden" })['value']

with requests.Session() as s:
    src = s.get(url).text
    creds = {
        "username"   : "admin",
        "password"   : "password",
        "Login"      : "Submit",
        "user_token" : get_token(src)
    r = s.post(url, data = creds)
    print r.text

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.