Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-login token loader

I'm setting up a Flask app with the flask-login extension. The flask-login documentation recommends setting up an alternative token generator that does not simply use the user ID and app secret to create the session token (which is the default method). But it doesn't provide any clear recommendations for how to do this.

So, for User.get_auth_token(), I'm using the make_secure_token function with the user email and password as parameters (so I get a hash of these parameters + app secret).

Next, I need to be able to get the user from the token with the token_loader callback. The default method for generating tokens in flask-login is to include both the raw user ID and a hash of the user ID + app secret. That makes finding the user from the token pretty simple - just grab the ID and look up the user.

But should I be exposing the user ID in the session token at all? If I don't, should I store the session token in the database or somewhere else with the user ID to make a lookup possible?

In short: does anyone know what the best practice is for creating a secure token & corresponding token_loader callback?

like image 237
bjudson Avatar asked Sep 25 '12 16:09

bjudson


People also ask

What is LoginManager in Flask?

from flask_login import LoginManager login_manager = LoginManager() The login manager contains the code that lets your application and Flask-Login work together, such as how to load a user from an ID, where to send users when they need to log in, and the like.

Is Flask user deprecated?

Flask-Security is now deprecated, so I wouldn't recommend using it in production.


1 Answers

On the Flask mailing list, Matt Wright pointed me to his implementation in the flask-security extension. He uses itsdangerous to create a signed token which encodes a serialized (via URLSafeTimedSerializer()) list consisting of the user ID and the password hash. The token can then be decoded to grab the user ID.

like image 61
bjudson Avatar answered Nov 10 '22 06:11

bjudson