MushroomMaula / fastapi_login

FastAPI-Login tries to provide similar functionality as Flask-Login does.
https://pypi.org/project/fastapi-login
MIT License
639 stars 58 forks source link

Cookie support #9

Closed SelfhostedPro closed 4 years ago

SelfhostedPro commented 4 years ago

I was wondering if you had any plans to add refresh token support?

I would like to have a short time which the access token is valid and have the ability to refresh the access token once it expires.

I was also wondering if you've thought about adding cookie support so that cookies would be set by FastAPI in a similar way to how flask-jwt-extended does things: https://flask-jwt-extended.readthedocs.io/en/stable/tokens_in_cookies/

MushroomMaula commented 4 years ago

How exactly would you like to see refresh token supported? The only way to refresh the access token would be to add an endpoint to your api, which checks the provided refresh token against your database, so I dont quite see how fastapi-login would help here.

Regarding the cookie support you mean I should provide a way to return the jwt as a cookie instead of the string?

SelfhostedPro commented 4 years ago

For the refresh token, you don't need to check against a database. I believe it's just a separate token with a longer expiration that can only access routes that have something like refresh_token_required (can't access standard authentication required routed).

For cookies, yes, that would be ideal but you'd want to have them be httponly for the tokens and then also have csrf cookies as well.

I'll take a look later today and see if I can't get a PR going with some of this if you're interested?

SelfhostedPro commented 4 years ago

It looks like it's easy enough to implement refresh tokens myself: https://github.com/frankie567/fastapi-users/issues/253

It may be worth looking at how they set cookies in that project.

MushroomMaula commented 4 years ago

I just added basic cookie support in the development branch. Now you can set use_cookie=True when initialising LoginManager and it will check the requests cookies for the access token. However I do not plan to support for setting the cookie on the response on authentication, I want everyone to be able to customize their login procedure as much as they can. However its easy to return a httponly cookie with the access token as value. More information on how to return cookies can be found in the FastAPI docs

@app.post('/login')
def login(response: Response, login_data):
   ... # normal login procedure
   access_token = manager.create_access_token(data=logged_in_user)
   response.set_cookie(
       key=manager.cookie_name, value=f"Bearer {access_token}", httponly=True
   )
   return # your response
SelfhostedPro commented 4 years ago

Perfect! Thank you!