Using Flask-Security to authenticate REST API
Asked Answered
T

2

7

I am using Flask-Security to build a web app that has a public REST API. I am trying to figure out how to add user registration and login using REST calls only. It is fairly easy to create a user using user_datastore.create_user. But how can I then login the user, using a REST call?
If flask_security.utils.login_user took username+password or a token as an argument, it would be easy, but it takes a user object instead? The documentation shows how to register and login using forms and views, but I need to be able to register and login from an IOS device (using RESTkit).

Thenar answered 29/5, 2014 at 21:9 Comment(2)
possible duplicate of Security of REST authentication schemesBrominate
the examples seem quite simple. create a user, add the @login_required to your methods, then you can customize flask-login to suit your needs flask-login.readthedocs.org/en/latest/…Beachcomber
P
7

You will either want to use flask_security.decorators.auth_token_required along with SECURITY_TOKEN_AUTHENTICATION_KEY or SECURITY_TOKEN_AUTHENTICATION_HEADER (depending on whether you want to pass the token in the URL or in a header) or you can override flask_security.core.UserMixin.get_auth_token for your User class and Flask-Security will do the right thing.

Posada answered 29/5, 2014 at 22:4 Comment(0)
B
2

[Writing an answer since I do not have enough credentials to comment on answer provided by Sean Vieira]

I looked a bit of Flask-Security code - it uses Flask-Login's LoginManager for this. Flask-Login in turn expects the user to define token_loader (as well as implement get_auth_token in User class)

Does Flask-Security provide "default" token_loader functionality ? Otherwise - it is same as Flask-Login

Edit: It turns out Flask-Security works just fine. I do not need to write my own token_loader. I had security code in a separate file, and that is how "magic" broke. I brought back the security code into myapp/init.py - and documented code "works"

Edit 2: Refering to answer provided by Sean above. I don't think it is one or the other. One must use auth_token_required decorator. Overriding get_auth_token in User class is optional, in case you want different implementation for token generation (I think) Overriding get_auth_token in User class is not sufficient.

Bialystok answered 12/1, 2015 at 12:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.