Maintaining authentification with python requests

Viewed 132

Trying to stay logged in this website using the request package but failing:

import requests

# Test account
payload = {"email": "ozeifaze@gmail.com", "password": "testpassword0?"}

with requests.Session() as s:
    log = s.post("https://www.doctrine.fr/api/login", json=payload)
    print(log) # <Response [200]> or <Response [422]> if wrong payload
    print(log.text) # {"ok":true,"mfa_required":false}

    page = s.get("https://www.doctrine.fr/dashboard")
    print(page) # <Response [200]> but not authentified and redirected

The POST requests works and return what is expected. However, when I try to reach the second page, I'm not authentified anymore and I'm redirected to another page.

What am I doing wrong ?

1 Answers

This is probably as a result of the cookies not being sent in the second call.

For example

>>> import requests
>>> login_data =  {'formPosted':'1', 'login_email':'me@example.com', 'password':'pw'}
>>> r = requests.post('https://localhost/login.py', login_data)
>>> 
>>> r.text
u'You are being redirected <a href="profilePage?_ck=1349394964">here</a>'
>>> r.cookies
{'session_id_myapp': '127-0-0-1-825ff22a-6ed1-453b-aebc-5d3cf2987065'}
>>> 
>>> r2 = requests.get('https://localhost/profile_data.json', ...)

If you are able to verify that your cookies are saved for future reference and it's a persistent session, you should be able to make the request without any errors.

Pass the payload without a kwarg since json is the wrong one, and add the second parameter in the second call.

log = s.post("https://www.doctrine.fr/api/login", payload)
page = s.get("https://www.doctrine.fr/dashboard", ...)
Related