I'm trying to use python to login to a site and then make a POST request to add an ID to a database. However, I can't seem to even login. The 'r.text' just returns the same login page. If I can get this to work, I will also need to make multiple requests, so I assume I need to maintain a persistent session. I've tried some things from what I've researched, such as using requests.Session(). However, I still get the same page returned, and I really can't figure out how to handle the csrf_token. I have included the code that I am trying and the forms involved. How do I properly login to this site and keep the session open? I'd greatly appreciate any guidance you'd be willing to provide.

*Side note: If I was authenticated in my browser, I could add the ID by using something like the following URL (not sure if this is helpful): https://admin.example.com/cot/a_file.cmp?add=1&some_id=1234567

I have tried working with the requests library for python, but I'm not sure how to handle the csrf_token that changes each time.

This is what I am working with so far...

import requests

payloadLogin = {'username':'MYusername','password':'MYpassword','login':'Submit'}
#no idea how to deal with csrf_token, as it changes each time.                      

s=requests.Session()

r = s.post('https://admin.example.com/somtin/login',data=payloadLogin)
#if I print the response at this point, I just get the same login page.


#I'd like to make the following request after authenticating
payloadAddSite = {'add':'Add ID to DB','some_id':'1234567'}

q = s.post('https://admin.example.com/cot/a_file.cmp',data=payloadAddSite)
print(q.text)

These are the forms-

The form for the login page:

<form class="form-signin" method="post" action="//admin.example.com/somtin/login/attempt">

        <h2 class="form-signin-heading">Login</h2>


        <label for="inputUser" class="sr-only">Username</label>
        <input type="text" id="inputEmail" class="form-control" placeholder="Username" name="username" required autofocus>

        <label for="inputPassword" class="sr-only">Password</label>
        <input type="password" id="inputPassword" class="form-control" placeholder="Password" name="password" required>


        <input class="btn btn-lg btn-primary btn-block" type="submit" name="login" value="Submit" />
        <p><br /><a href="//admin.example.com/somtin/login/forgot">Forgot password</a></p>

        <input type="hidden" class="csrf_token" name="csrf_token" value="6vv2iaan7g9333f5hfutr51zrlglrad5zjotidh0jdktp3zrure48p80zec13wjdd" />  </form>

The form to add the ID after logging in:

<form action="/cot/a_file.cmp" method="POST">
<input size="10" type="text" name="some_id" value="" />
<input type="submit" name="add" value="Add ID to DB" />
</form>

0 Answers