0

I have written a python script which uses the requests library in order to test a Flask application.

While testing the login mechanism, the script isn't able to distinguish succesful login attempts from failed ones. HTTP POST requests always return a 200 HTTP status code.

On the server end insted, succesfull user login attempts are logged with status code 302, since I redirect the user to the homepage after login.

Tester code (with correct user credentials):

>>> import requests
>>> from utils import retrieve_csrf_token
>>> url = 'http://localhost:5000/login'
>>> token = retrieve_csrf_token(url)
>>> session = requests.Session()
>>> r = session.post(url, data={'email':'admin@test.com','password':'123456','csrf_token':token})
>>> r.status_code
>>> 200

Server log:

Valid form submitted
127.0.0.1 - - [29/Dec/2018 17:33:32] "POST /login HTTP/1.1" 302 -
127.0.0.1 - - [29/Dec/2018 17:33:32] "GET /home HTTP/1.1" 200 -
127.0.0.1 - - [29/Dec/2018 17:33:32] "GET /favicon.ico HTTP/1.1" 404 -

EDIT:

After further inspection I noticed that, after sending the POST request, the response in r.text is the homepage source code.

Following the same steps using a proxy or inspecting the requests using Chrome Developer tools I see the correct codes.

fbid
  • 1,570
  • 2
  • 18
  • 29
  • 302 is a redirect status code. Your client will follow the redirect. – nos Dec 29 '18 at 19:41
  • @nos yes I know that. 302 is the default code returned by Flask's `redirect()` function in the server code – fbid Dec 29 '18 at 19:43

1 Answers1

2

I'm not sure what the "session" object in your test code does, but if you wan't requests to not follow redirects (so that it gives you the actual status code) you'd generally do it like this:

r = requests.get('http://github.com', allow_redirects=False)

Documentation: http://docs.python-requests.org/en/latest/user/quickstart/#redirection-and-history

Trondh
  • 3,221
  • 1
  • 25
  • 34
  • session was just an instance of requests.Session(). I forgot to paste that in the code in my original post (now edited). I didn't know that the allow_redirect parameter needed to be explicitly set to False to stop the redirection, I thought it was the default behaviour. That solved my issue though. Thanks! – fbid Dec 29 '18 at 19:47
  • nice, glad to help – Trondh Dec 29 '18 at 20:09