【问题标题】:python fastapi redirect and authenticatepython fastapi重定向和身份验证
【发布时间】:2021-04-14 20:06:45
【问题描述】:

访问注册链接后,我正在尝试对用户进行身份验证 (链接示例:http://127.0.0.1:8000/confirm-email?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9F

我的代码:

@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"},
        )

但每次尝试使用/users/me 端点时都会失败(出现 401 错误,未经授权)。 也许我将令牌放在错误的位置或使用了错误的标头?

【问题讨论】:

    标签: fastapi


    【解决方案1】:

    如果使用 OAuth 2.0 并希望在请求中设置 access_token,通常会像 RFC 中的示例一样进入 Authorization 标头:Authorization: Bearer mF_9.B5f-4.1JqM - 在示例中,mF_9.B5f-4.1JqM 会是令牌的值。

    在我看来,您正在使用标头access_token: [token value]token_type: "bearer" 访问users/me 端点。相反,我认为应该设置以下标题:Authorization: Bearer [token value]

    【讨论】:

    • @N Pinheiro 感谢您的回答,但我目前无法接受您的回答,因为我无法对其进行测试,因为该框架有额外的限制并且需要获得授权 - 您无论如何都要填写电子邮件密码表格(我不确定!)
    【解决方案2】:

    经过一番研究,我发现redirection 按规范不能有授权标头(浏览器/客户端将主要忽略它)。因此,即使标题是正确的 - 这也是无稽之谈。一种使用 URL 的可能解决方案。

    【讨论】:

    • 我不明白您所说的“使用 URL 的一种可能解决方案”是什么意思
    猜你喜欢
    • 2021-02-06
    • 2021-01-16
    • 2021-11-27
    • 2012-05-01
    • 2019-01-25
    • 2017-06-06
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多