将 API 密钥身份验证添加到 FastAPI 应用程序
APIKeyHeader 的源码
class APIKeyHeader(APIKeyBase):
def __init__(
self,
*,
name: str,
scheme_name: Optional[str] = None,
description: Optional[str] = None,
auto_error: bool = True,
):
self.model: APIKey = APIKey(
**{"in": APIKeyIn.header}, # type: ignore[arg-type]
name=name,
description=description,
)
self.scheme_name = scheme_name or self.__class__.__name__
// ...
如果 auto_error=True(默认),那么当 api_key 不存在时,会抛出 HTTPException 异常,返回 403 状态码。
如果 auto_error=False,那么当 api_key 不存在时,会返回 None。那么自定义函数 get_api_key 才会被调用。