Question: Log in with Python requests and csrf token

Question

Log in with Python requests and csrf token

Answers 0
Added at 2016-12-20 00:12
Tags
Question

So here is what I have:

 with requests.Session() as s:
    # 1) get the csrf
    start_page = s.get(login_url)
    matchme = r'meta name="csrf-token" content="(.*)"/'
    csrf = re.search(matchme, str(start_page.text))
    csrf = csrf.group(1)
    csrf = csrf[:csrf.find('"')]
    print csrf

    # 2) post user/pw/csrf
    signin = dict(_csrf=csrf, username='user', password='pw')
    r = s.post(login_url, data=signin)
    print(r.text)

First part is to open the login page and get the csrf from header. Second part is to post the username, password, and _csrf. And I'm unable to login. It stays at the login page.

The form data when I inspect the login on the browser looks like:

Form Data
 _csrf: .......
 _LoginForm[username]:user
 _LoginForm[password]:pw

Problem is the csrf form the first part is always different from the csrf (print r.text) on the second part. Seems like the post starts a different session and csrf gets a refresh.

How do I fix this? Thanks

Answers to

Log in with Python requests and csrf token

Source Show
◀ Wstecz