2
votes

For some time I've used Flask-Login to handle traditional username/password authentication requests and Flask-Principal to handle authorization checks against routes on subsequent requests. All has been well.

I'm now trying to leverage Flask-Login's "request_loader" decorator to handle header-based authentication within the same request that hits protected endpoints.

The problem I'm having is that Flask-Principal's "require" decorators seem to be executing before Flask-Login's "request_loader". In the below example, I'm having a 403 Unauthorized HTTP Exception fire before the code even tries to authenticate the user.

I must be missing something silly given the point of header-based authentication -- I believe -- is for it execute prior to any endpoint authorization checks...

Flask-Login Use:

login_manager = LoginManager(app)
login_manager.anonymous_user = User
login_manager.session_protection = 'strong'
@login_manager.request_loader
def load_user_from_request(request):
    # do stuff, return User if found

Flask-Principal Use:

@blueprint.route('/some/endpoint', methods=['GET'])   
@read_permission.require(http_exception=403)
def some_function():
    # Do stuff

Edit:

As a side note, Flask's "before_request" function seems to be called before any of these others so, in theory, I might be able to handle header-based authentication from there, but it seems dirty not to be using the Flask-Login function designed for this purpose...

1

1 Answers

0
votes

I finally moved the authentication logic into an @app.before_request function and that has indeed worked, so I'll mark this as the answer until something better comes along.