The Python Oracle

Flask-login with static user always yielding 401- Unauthorized

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles

--

Chapters
00:00 Question
01:59 Accepted answer (Score 4)
03:37 Thank you

--

Full question
https://stackoverflow.com/questions/1662...

Accepted answer links:
[this]: https://github.com/maxcountryman/flask-l...
[following lines]: https://github.com/maxcountryman/flask-l...
[this]: https://stackoverflow.com/a/4954900/7205...
[SharedDataMiddleWare]: http://werkzeug.pocoo.org/docs/middlewar...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #flask #flasklogin

#avk47



ACCEPTED ANSWER

Score 4


Update:

Since a newer version(0.2.2) of Flask-Login this is no more an issue. Check out the changes in this commit.

If you are using an older version, read on.


The problem here is static_url_path="". For Flask-Login to work you can not have an empty string static_url_path.

The following lines in the Flask-Login source(older version) reveal this:

if (current_app.static_url_path is not None and
    request.path.startswith(current_app.static_url_path)
):
    # load up an anonymous user for static pages
    _request_ctx_stack.top.user = self.anonymous_user()
    return

Since your static_url_path is "" the if condition evaluates to True, because of which every page you visit acts like a static page, and hence Flask-Login always loads an anonymous user, instead of continuing to load the actual user(using the load_user callback).


Also do not forget to uncomment #login_manager.login_view = "login"


If you still want to use the root folder of the app itself as the static folder, take a look at this solution, using SharedDataMiddleWare:

app.debug = True
if app.config['DEBUG']:
    from werkzeug import SharedDataMiddleware
    import os
    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {
      '/': os.path.dirname(__file__)
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0")