链接:fastapi-supporting-multiple-authentication-dependencies
我认为这是最接近我所需要的,但不知何故,我不能让任何一个依赖工作,因为fastapi在赠款对endpoint的访问之前强制执行两个依赖。
客户依赖性的筛选:
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认证或基本认证提供正确的凭据时,它会授予我访问端点的权限,但它仍然迫使我为两者都提供凭据。我如何才能实现提供两个认证中的任何一个而不是两者的效果。
1条答案
按热度按时间0s0u357o1#
这个想法是使所有这些安全依赖项在依赖项解析阶段不会引发用户身份验证错误的异常。
对于
HTTPBasic
通过auto_error=False
:字符串
然后在
basic_logged_user
中,你应该检查型
您需要找到如何对第二个身份验证方案(
utils.OAuth2_scheme
)执行相同操作的方法-不是引发HTTP_401_UNAUTHORIZED
,而是返回None
。那么你的
auth_user
就会像你期望的那样工作,只有当两个方案都返回None
时,它才会引发HTTP_401_UNAUTHORIZED
。