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

Redirects issues on NotAuthenticatedException #16

Closed DevilWarrior closed 4 years ago

DevilWarrior commented 4 years ago

Hi, I'm having issues with the redirects on NotAuthenticatedException. Here's how I have things currently setup:

class NotAuthenticatedException(Exception):
    pass

# these two argument are mandatory
def exc_handler(request, exc):
    return RedirectResponse(url='/login')

manager = LoginManager(SECRET, tokenUrl='/auth/token', use_cookie=True)
manager.cookie_name = 'oversight_token'
manager.not_authenticated_exception = NotAuthenticatedException
app.add_exception_handler(NotAuthenticatedException, exc_handler)

This works for me but only on routes with GET methods. On routes with POST I get the result below on the browser but no redirects. The problem is, I can only get the login redirects with POST routes as stated here.

{"detail":"Could not validate credentials"}

MushroomMaula commented 4 years ago

I'm not quite sure what you mean exactly. If you try to POST to a route without the access_token no redirect happens? An example of the unexpected behaviour would help me immensly to debug whats going wrong

DevilWarrior commented 4 years ago

Alright, I'll put something together.

MushroomMaula commented 4 years ago

I tried myself and it seems to be working fine

from fastapi import FastAPI, Depends
from starlette.testclient import TestClient

from fastapi_login import LoginManager
from starlette.responses import RedirectResponse

SECRET = 'secret'

app = FastAPI()

class NotAuthenticatedException(Exception):
    pass

# these two argument are mandatory
def exc_handler(request, exc):
    return RedirectResponse(url='/login')

manager = LoginManager(SECRET, tokenUrl='/auth/token', use_cookie=True)
manager.cookie_name = 'oversight_token'
manager.not_authenticated_exception = NotAuthenticatedException
app.add_exception_handler(NotAuthenticatedException, exc_handler)

@app.post('/login')
def login():
    return {'status': 'login'}

@app.post('/test')
def test(_=Depends(manager)):
    return {'status': 'test'}

if __name__ == '__main__':
    client = TestClient(app)
    resp = client.post(
        '/test'
    )
    assert resp.is_redirect
    assert resp.next.path_url == '/login'
DevilWarrior commented 4 years ago

Hi, I can confirm is working now. Thank you!!!

Edit: It worked after I fixed the other issue with the redirect status.