In a FastAPI application, I want to use user authentication like described here: https://fastapi-login.readthedocs.io/advanced_usage/
The application uses an APIRouter for the user authentication part in a different file.
This is in my main.py:
app = FastAPI(title="Some API")
app.include_router(auth_router)
from starlette.responses import RedirectResponse
from routers.authenticate import NotAuthenticatedException
@app.exception_handler(NotAuthenticatedException)
def auth_exception_handler(request: Request, exc: NotAuthenticatedException):
# Redirect the user to the login page if not logged in
return RedirectResponse(auth_router.url_path_for("/login"))
and in authenticate.py
class NotAuthenticatedException(Exception):
pass
@auth_router.post('/login')
def login(...):
...
return response
@auth_router.get('/protected')
def protected_route(user=Depends(manager)):
return {"message":"You are an authenticated user!", "user":user.username}
I left some code out for brevity, since the user login itself works. When a user (that is not logged in) tries to access '/protected' the NotAuthenticationException is thrown as expected and the exception handler in main.py is called. But the redirect never gets to the '/login' in authenticate.py. I am pretty sure that this is because the RedirectResponse tries to redirect to a '/login' within the same file, which is main.py. Since there is no '/login' defined, nothing happens. So my question is, how do I set the url in the RedirectResponse correctly so that it targets '/login' in authenticate.py?
Thanks for your help!