0

I have this view that is set to handle a POST request which will carry a formData with user authentication data.

@app.post("/token", response_model=Token)
async def login_for_access_token(request: Request,
                                 form_data: Annotated[OAuth2PasswordRequestForm, Depends(
                                 )]
                                 ):
    user = authenticate_user(USERS, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )

    rr = RedirectResponse('/home', status_code=303)
    rr.set_cookie(key="session_token", value=access_token)
    return rr

As you can see I am trying to verify if the user exists. If so I will redirect the user to the "/home" route. I ran the server and do the authentication process, this is what the server logs:

INFO:     127.0.0.1:44354 - "POST /token HTTP/1.1" 302 Found
INFO:     127.0.0.1:44354 - "GET /home HTTP/1.1" 200 OK

Which is a confirmation that everything worked fine I suposse. But then again, the user wasn't really redirected, because when I click in the "submit" button inside the login.html template, I still continue in the same view I was before.

I have tried getting ride of the Jinja2Templates template and return a json object instead inside the home view to see if the rendering of the template was the problem, and it was not. Apart from that I haven't really tried anything because I have no idea what to try, since it seems that the server side part of the code has no visible bug.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • You'll have to add a minimal (complete) verifiable example, as the log seems to show that everything works as it should. Since you didn't include the `/home` route in your example either, it's hard to say why it shows the same content as your login route. – MatsLindh Jul 14 '23 at 21:53
  • Related answers can be found [here](https://stackoverflow.com/a/70693108/17865804), [here](https://stackoverflow.com/a/70777217/17865804), as well as [here](https://stackoverflow.com/a/73662576/17865804), [here](https://stackoverflow.com/a/75188418/17865804) and [here](https://stackoverflow.com/a/73599289/17865804) – Chris Jul 15 '23 at 05:26

0 Answers0