引用此链接: fastapi-supporting-multiple-authentication-dependencies个
我认为这是最接近我需要的东西,但不知何故,我无法让这两个依赖项中的任何一个工作,因为Fastapi在授予对端点的访问权限之前会强制执行这两个依赖项.
用于定制需求的代码片段:
def basic_logged_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
current_username_bytes = credentials.username.encode("utf8")
correct_username_bytes = settings.SESSION_LOGIN_USER.encode("utf8")
is_correct_username = secrets.compare_digest(
current_username_bytes, correct_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
correct_password_bytes = settings.SESSION_LOGIN_PASS.encode("utf8")
is_correct_password = secrets.compare_digest(
current_password_bytes, correct_password_bytes
)
if not (is_correct_username and is_correct_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Credentials",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
def jwt_logged_user(token: str = Depends(utils.OAuth2_scheme),
db: Session = Depends(db_session)):
credential_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"})
token = utils.verify_token(token, credential_exception)
user = db.query(User).filter(User.username == token.username).first()
return user
# custom auth
def auth_user(jwt_auth: HTTPBearer = Depends(jwt_logged_user),
basic_auth: HTTPBasic = Depends(basic_logged_user)):
if not (jwt_auth or basic_auth):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid Credentials')
#endpoint
@router.get("/")
async def get_users(db: Session = Depends(db_session), logged_user: str = Depends(auth_user)):
query_users = db.query(User).all()
return query_users
我希望当我为JWT身份验证或基本身份验证提供正确的凭据时,它会授予我访问终结点的权限,但它仍然强制我为这两种身份验证都输入凭据.我如何才能达到这样的效果:提供两个身份验证中的任何一个,而不是两个都提供.