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?
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.
Flask-Security is now deprecated, so I wouldn't recommend using it in production.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With