The Python Oracle

Flask-login with static user always yielding 401- Unauthorized

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 Flask-Login With Static User Always Yielding 401- Unauthorized
01:20 Accepted Answer Score 4
02:33 Thank you

--

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

--

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")