question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] Returning a RedirectResponse in a dependency

See original GitHub issue

Description

How can I return a Redirect in a dependency to be executed in a conditional? In the example below, the code works, but I just get an exception. I want a redirect.:

def logged_in(user: models.User = Depends(current_user)):
    if not user.is_authenticated:
        raise HTTPException(status_code=303, detail="You need to login")

@users.get('/channel/{username}', dependencies=[Depends(logged_in)])
def channel(*, username: str,
            request: Request,
            current_user: models.User = Depends(current_user),
            db: Session = Depends(get_db))
    do_something()

Below is what I want, but when I use this dependency nothing happens because doesn’t use the return value. I can’t think of a way to do this without referencing the Dependency directly.

def logged_in(user: models.User = Depends(current_user)):
    if not user.is_authenticated:
        return RedirectResponse(url='/login')

@users.get('/channel/{username}', dependencies=[Depends(logged_in)])
def channel(*, username: str,
             request: Request,
            current_user: models.User = Depends(current_user),
            db: Session = Depends(get_db))
    do_something()

This works, but I have to put it in every single endpoint: @users.get(‘/channel/{username}’, dependencies=[Depends(logged_in)])

def channel(*, username: str,
             request: Request,
            current_user: models.User = Depends(current_user),
            db: Session = Depends(get_db)):
     
     if not user.is_authenticated:
            return RedirectResponse(url='/login')

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:13 (3 by maintainers)

github_iconTop GitHub Comments

13reactions
phy25commented, Feb 26, 2020

I doubt if this works at all. At least the following does not work for me.

from fastapi import FastAPI, Depends
from starlette.responses import RedirectResponse

app = FastAPI()

def redirect() -> bool:
    RedirectResponse(url='/login')
    return True

@app.get('/')
def index(should_redirect: bool = Depends(redirect)):
    return should_redirect

What I did before is to use custom exception handler:

from fastapi import FastAPI, Depends
from starlette.requests import Request
from starlette.responses import RedirectResponse, Response

app = FastAPI()

class RequiresLoginException(Exception):
    pass

async def redirect() -> bool:
    raise RequiresLoginException

@app.exception_handler(RequiresLoginException)
async def exception_handler(request: Request, exc: RequiresLoginException) -> Response:
    return RedirectResponse(url='/login')

@app.get('/')
async def index(should_redirect: bool = Depends(redirect)) -> bool:
    return should_redirect
2reactions
gavrilovnecommented, Feb 17, 2022

@NomeChomsky @eddyizm I would also like to know how I can implement this. I want my dependency to trigger a redirect when it cant find a certain cookie. I cant find in the docs a proper way to implement this without also thouching the main app source code.

@phy25 solution is therefor not possible for me

Hi! Try it


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)


async def check_auth(token: str = Depends(oauth2_scheme)):
    if not token:
        raise HTTPException(
            status_code=status.HTTP_307_TEMPORARY_REDIRECT,
            headers={'Location': '/login'})
    return True


@router.get("/login")
async def login(request: Request):
    return auth_template.TemplateResponse("login.html", {"request": request})


@router.get("/test")
async def test(auth: bool = Depends(check_auth)):
    return "OK"

screen

Read more comments on GitHub >

github_iconTop Results From Across the Web

tiangolo/fastapi - Gitter
it returns a redirect response object to the endpoint - I want the dependency to force a redirect if the user isn't logged...
Read more >
How to do a Post/Redirect/Get (PRG) in FastAPI?
I guess the RedirectResponse carries over the HTTP POST verb rather than becoming ... Implementation details ... return fastapi.responses.
Read more >
Custom Response - HTML, Stream, File, others - FastAPI
RedirectResponse ¶ ... Returns an HTTP redirect. Uses a 307 status code (Temporary Redirect) by default. ... If you do that, then you...
Read more >
Disabling Page Cache for Redirect Response - Drupal Answers
This doesn't exactly answer your question, but I feel it's relevant ... In your case you'd add cache dependencies relevant to determining ...
Read more >
Event Dispatcher and redirects | Drupal 9 Module Development
return new \Symfony\Component\HttpFoundation\RedirectResponse('/node/1'); ... The dependency is actually the service that points to the current user (either ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found