Search code examples
pythonflaskflask-restfulflask-security

How to make a login to a rest api with flask-security using requests


I have disabled CSRF but I can't get to login to a REST API using Flask-Security with roles based authorization, from a local front-end server. I do make the login but, I think, no cookies are stored on the request so I keep getting the login page on the front-end server. This is the code I am using:

 payload = {'username': request.form['username'], 'password': request.form['password']}
    with requests.Session() as s:
        r = s.post('http://localhost:5002/login', data=payload)
        print(s.cookies)
        if r.ok:
            r2 = s.get('http://localhost:5002/protected', cookies=s.cookies)

Is there a way to maintain the session to the front-end client that is logged in to show the protected content?


Solution

  • The Flask-Security LoginForm does not accept 'username' - the field is called 'email'. Now - you CAN send in a username in that field, and if you have configured SECURITY_IDENTITY_ATTRIBUTES correctly - it should look up the column 'username' in the DB.

    Second - I want to point out that just because you are using requests doesn't mean you are sending JSON - in fact you are sending a form input. So Flask-Security always responds with a form - you will basically never see anything other than a 200 - with the response body containing a 'form' that has the various error messages.

    So - 2 things - if you want REST - do that - new versions of requests take an argument json= and will do the right thing. If you do that - you will start to get 400 responses I believe.