miguelgrinberg / Flask-HTTPAuth

Simple extension that provides Basic, Digest and Token HTTP authentication for Flask routes
MIT License
1.27k stars 228 forks source link

Integration with Flask-Login's current_user #88

Closed mfrlin closed 5 years ago

mfrlin commented 5 years ago

I'm using Flask-Login to do cookie based authentication and it works ok. Now I've added API that I authenticate via token with HTTPAuth. The problem I now have is that current_user is not set because I only do g.current_user = user and I don't know how to set the current_user that comes with Flask-Login. Any ideas?

miguelgrinberg commented 5 years ago

This may be a question for Flask-Login more than this extension, but really you have to consider that these two extensions do the same type of work for two different use cases. If you really want to use Flask-Login for your API routes, then why did you add Flask-HTTPAuth?

mfrlin commented 5 years ago

I started using Flask-Login to handle cookie based sessions, login, logout, etc. Then I added API routes and I needed token based auth on those routes only, but with Flask-Login is tricky to disable and enable different types of auth for specific routes and I need this because I want to mitigate XSS and CSRF attacks on API. So you get short lived token with cookie and use API with that token and not cookie. This is why I added HTTPAuth and I realize now it is more of a question for Flask-Login.

For a workaround I did something like this:

def get_current_user():
  # no error handling in this example
  if g.current_user:
    return g.current_user
  return current_user # from flask_login
miguelgrinberg commented 5 years ago

@mfrlin these days Flask-Login also supports token authentication, maybe that works better for you instead of Flask-HTTPAuth. See https://flask-login.readthedocs.io/en/latest/#custom-login-using-request-loader.