This post will give a basic discussion on securing authentication tokens that can be used with Flask-Login.
The article Minimal Flask Login Example provided an introduction to token based authentication using the Flask-Login extension for the Flask web framework. The focus of that article was to highlight the crux of authentication logic. One glaring omission was that the token itself was nothing but the username and password passed as clear text. This clearly will not work!
The high level control flow involving token based authentication is as follows:
In the Minimal Flask Login Example, we skipped the serialization part for simplicity. A more rigorous way of doing this would be to use JSONWebSignatureSerializer in the itsdangerous package to serialize the authentication credentials.
from itsdangerous import JSONWebSignatureSerializer s = JSONWebSignatureSerializer('secret-key') token = s.dumps({'username': JaneDoe, 'password' : 'secret'})
The token in the above code can be used to pass from the server side. Validating a token is simple as well.
from itsdangerous import JSONWebSignatureSerializer s = JSONWebSignatureSerializer('secret-key') credential = s.loads(token)
The above code will get the credential corresponding to the user which can then be checked against what is stored in the database.