python fastapi redirect and authenticate

Viewed 2076

I'm trying to authenticate the user after visiting the registration link (link example: http://127.0.0.1:8000/confirm-email?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9F)

My code:

@app.get("/confirm-email", status_code=200, )
def confirm_email(
        token: str = fastapi.Query(..., min_length=64, max_length=256,
        db: Session = fastapi.Depends(database.get_db)):
    if user := crud.read_user_by(db, column='current_token', value=token):
        if user.created_datetime + timedelta(minutes=30) > datetime.now():  # TODO change minutes to days
            return fastapi.responses.RedirectResponse(
                url="http://127.0.0.1:8000/users/me",
                headers={"access_token": token, "token_type": "bearer"})
        else:
            raise fastapi.HTTPException(
                status_code=fastapi.status.HTTP_410_GONE,
                detail="Confirmation link is expired")
    else:
        raise fastapi.HTTPException(
            status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
            detail="Wrong token")


@app.get("/users/me") 
def read_users_me(token: str = fastapi.Depends(oauth2_scheme),
                  db: Session = fastapi.Depends(database.get_db)):
    try:
        return services.get_user_by_token(db=db, token=token)
    except Exception as e:
        raise fastapi.HTTPException(
            status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )

But every time I'm failing when trying to use /users/me endpoint (getting 401 error, UNAUTHORIZED). Maybe I put the token in the wrong place or using wrong headers?

2 Answers

If using OAuth 2.0 and wanting to set the access_token in a request, tipically, it goes into the Authorization header like the example in the RFC: Authorization: Bearer mF_9.B5f-4.1JqM - in the example, mF_9.B5f-4.1JqM would be the value of the token.

It seems to me that you are accessing the users/me endpoint with the headers access_token: [token value] and token_type: "bearer". Instead, I believe the following header should be set: Authorization: Bearer [token value]

After a little researching, I figured out that redirection by specification can't have authorization headers (browser/client will just ignore it mainly). So even if headers are correct - it's nonsense. One possible solution to use URL.

Related