我正在制作一个用于注册、身份验证和授权的模块。注册过程分为 2 个阶段(2 个处理函数)。我在第二阶段遇到的问题是,通过“Postman”,请求可以正常工作;但是,通过 FastAPI 文档(Swagger UI),它会引发一个错误,即未传递
Authorization
标头。这是代码:
@app_reg.post("/confirm")
async def confirm(data: CodeConfirm,
authorization: str = Header(...),
) -> JSONResponse:
"""
Processing of the form for entering the registration confirmation code.
Args:
authorization: Caption Authorization
code: Code from the form.
Returns:
JSONResponse: Code Validation Result.
- 200: Successful validation, returns a success message.
- 422: Validation error, returns an error message.
- 400: Validation error, returns an appropriate message.
Notes:
- Receives data from session, sends to backend, on successful
response from the backend, clears the session.
"""
try:
user_data = get_redis_via_token(authorization, SECRET_KEY_REGISTRATION)
if isinstance(user_data, JSONResponse):
return user_data
email = user_data.get('email')
login = user_data.get('login')
password = user_data.get('password')
verification_code = user_data.get('code')
except Exception as e:
return JSONResponse(content={"message": str(e)}, status_code=400)
result = await Registration.confirm_register(
email, login, password, data.code, verification_code)
if result['status_code'] == 200:
redis_client.delete(f"login:{login}")
return JSONResponse(content={"message": result["message"]},
status_code=200)
else:
return JSONResponse(content={"message": result["message"]},
status_code=400)
这是错误本身,代码为 422:
{
"detail": [
{
"type": "missing",
"loc": [
"header",
"authorization"
],
"msg": "Field required",
"input": null
}
]
}
我尝试添加别名,我尝试通过“Postman”实际发出请求(其中请求正常工作)。
我假设您使用 Swagger。您是否在登录期间在响应中的 cookie 中设置了授权标头。
response.set_cookie(
key="Authorization",
value=f"Bearer {token}",
httponly=True,
max_age=EXPIRES,
expires=EXPIRES,
samesite="none",
secure=False
)