Logging Into Website Using Python Requests With Sessions

Viewed 60

I am looking into a website and am collecting the token for the cookie, but I am still not getting status as logged in.

Here is my code:

headers = {'Referer': 'https://www..com/accounts/login/'}

s = requests.Session()
# Get cookie
s.get('https://www..com/accounts/login/')
csrftoken = s.cookies['csrftoken']

payload = {
    'id_username': 'my_username',
    'id_password': 'my_password',
    'csrfmiddlewaretoken': csrftoken
}

p = s.post('https://www..com/accounts/login/', data=payload, headers=headers)
print(p.text)

I do not see an obvious error when printing p.text, however, the printed HTML still shows 'Log In' rather than my username in its place which is what happens when I log in using a browser.

Can you see what I might be missing? My thought is that the csrf token was reset again after login, but how can I capture that when it is passed in the login call?

Thank you.

1 Answers

here to take the bounty :P

Your code is just fine. Even the referer-header is well formed.

But this is how your payload should look like:

payload = {
    'username': 'my_username',
    'password': 'my_password',
    'csrfmiddlewaretoken': csrftoken
}

You always go by the name of the field with these requests, not by the id. I just logged in successfully.

Good luck with the project and remember to implement safeguards, when playing with anything but toy-money.

ps.: the only other missing payload would be "next" but is apparently not necessary.

Related