I would like to have the following authentication scheme
- a login page where the user login with email and password, the flask server then returns a JWT token
- for later API access, the user has to provide the JWT token in the authorization header
However, I don't fully understand the inner working of flask-login. My preliminary understanding is that
- After user submits the password, we call
login_userand flask-login creates a session to store user information (maybeuser_id?) - Next time a request comes, authentication is done before processing the request if
login_requireddecorator is used
I thought only request_loader would be needed if JWT authentication is used because all we need to do is check every request header. But if only the request_loader function is provided (see code below), exception is thrown.
Exception: No user_loader has been installed for this LoginManager. Add one with the 'LoginManager.user_loader' decorator.
More specifically, my questions are
- what are the roles played by
user_loaderandrequest_loaderif we are to use JWT authentication? - when are
user_loaderandrequest_loaderbeing called, if both of them are provided? - why do we still need
user_loaderifrequest_loaderis provided?
Here are my implementation of these two loaders
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
@login_manager.request_loader
def load_user_from_request(request):
auth_str = request.headers.get('Authorization')
token = auth_str.split(' ')[1] if auth_str else ''
if token:
user_id = User.decode_token(token)
user = User.query.get(int(user_id))
if user:
return user
return None