我在访问注册链接后尝试对用户进行身份验证 (链接示例:http://127.0.0.1:8000/confirm-email?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9F)
我的代码:
A
但是每次我在尝试使用 @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"},
)
端点时失败(收到 401 错误,未经授权)。
也许我把令牌放在错误的地方或使用了错误的标题?
答案 0 :(得分:0)
如果使用 OAuth 2.0 并希望在请求中设置 access_token
,通常,它会像 RFC 中的示例一样进入 Authorization
标头:Authorization: Bearer mF_9.B5f-4.1JqM
-在示例中,mF_9.B5f-4.1JqM
将是令牌的值。
在我看来,您正在使用标头 users/me
和 access_token: [token value]
访问 token_type: "bearer"
端点。相反,我认为应该设置以下标题:Authorization: Bearer [token value]
答案 1 :(得分:0)
经过一番研究,我发现 redirection
的规范不能有授权标头(浏览器/客户端将主要忽略它)。所以即使标题是正确的 - 这也是无稽之谈。使用 URL 的一种可能解决方案。