0

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!

tabina
  • 1,095
  • 1
  • 14
  • 37
  • Does [this](https://stackoverflow.com/a/73662576/17865804) answer your question? – Chris Aug 30 '23 at 09:33
  • No, since the redirect happens within the same file and there is no APIRouter in use. – tabina Aug 30 '23 at 09:45
  • 1
    It did answer my question. Sorry, i did not see the difference in the RedirectResponse arguments when I first read it. I changed RedirectResponse(auth_router.url_path_for("/login")) to RedirectResponse(url = "/login") and it works. Thanks a lot! – tabina Aug 30 '23 at 12:48

0 Answers0