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).
-
possible duplicate of Security of REST authentication schemesJan Vlcinsky– Jan Vlcinsky2014-05-29 21:22:44 +00:00Commented May 29, 2014 at 21:22
-
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/…njzk2– njzk22014-05-29 21:35:10 +00:00Commented May 29, 2014 at 21:35
2 Answers
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.
Comments
[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.