我一直在开发一个API的认证功能,但现在遇到了一个看似简单的问题(希望如此)。我有一个login
端点:
@router.get("/login")
def login(request: Request):
return templates.TemplateResponse("auth/login.html", {"request": request})
@router.post("/login")
def login(
request: Request,
username: str = Form(...),
password: str = Form(...),
):
errors = []
user_db = pd.read_excel('users.xlsx')
user = authenticate_user(user_db=user_db, username=username, password=password)
access_token = create_access_token(data={"sub": username})
response.set_cookie(
key="access_token", value=f"Bearer {access_token}", httponly=True
)
response.headers['Authorization'] = f"Bearer {access_token}"
return response
这个登录功能能正常工作并生成token。但是,我还有一个需要认证的其他端点,在访问时无法获取到“Authorization”头信息,导致认证失败:
@router.get("/register")
def register(request: Request,
access_token: Annotated[Union[str, None], Cookie()] = None
):
# print(access_token)
#print(request.headers['Authorization'])
return templates.TemplateResponse("auth/register.html", {"request": request})
@router.post("/register")
def register(
request: Request,
current_user: Annotated[User, Depends(get_current_active_user)], # 这里认证失败
username: str = Form(...),
password: str = Form(...),
password_confirm: str = Form(...),
):
print(current_user)
try:
user = UserCreate(username=username, password=password, password_confirm=password_confirm,
superuser=False)
if current_user.superuser:
message = crear_usuario(user=user)
return JSONResponse(content={'message': message})
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User should be a superuser",
headers={"WWW-Authenticate": "Bearer"},
)
except ValidationError as e:
errors_list = json.loads(e.json())
for item in errors_list:
errors.append(item.get("loc")[0] + ": " + item.get("msg"))
return templates.TemplateResponse(
"auth/register.html", {"request": request, "errors": errors}
)
我已经通过编程方式在Python中将token添加到headers中使其可以正常工作,但我需要普通用户也能正常发送Authorization头信息。Swagger UI中的“Authorize”按钮是如何实现这一点的呢?它为何能让请求携带Authorization头信息?