HTTP Basic Auth¶
对于最简单的情况,你可以使用 HTTP Basic Auth。
在 HTTP Basic Auth 中,应用程序期望一个包含用户名和密码的请求头。
如果未收到,则返回 HTTP 401 "Unauthorized" 错误。
并返回一个 WWW-Authenticate 头,值为 Basic,以及一个可选的 realm 参数。
这会告诉浏览器显示集成的用户名和密码提示。
然后,当你输入用户名和密码后,浏览器会自动将它们发送到请求头中。
简单的 HTTP Basic Auth¶
- 导入
HTTPBasic和HTTPBasicCredentials。 - 使用
HTTPBasic创建一个“security方案”。 - 在你的 *路径操作* 中,将该
security与依赖项一起使用。 - 它返回一个
HTTPBasicCredentials类型的对象。- 它包含发送的
username和password。
- 它包含发送的
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
@app.get("/users/me")
def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
return {"username": credentials.username, "password": credentials.password}
🤓 其他版本和变体
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing_extensions import Annotated
app = FastAPI()
security = HTTPBasic()
@app.get("/users/me")
def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
return {"username": credentials.username, "password": credentials.password}
提示
如果可能,请优先使用 Annotated 版本。
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
@app.get("/users/me")
def read_current_user(credentials: HTTPBasicCredentials = Depends(security)):
return {"username": credentials.username, "password": credentials.password}
当你第一次尝试打开 URL(或点击文档中的“执行”按钮)时,浏览器会要求你输入用户名和密码。

检查用户名¶
这是一个更完整的例子。
使用依赖项检查用户名和密码是否正确。
为此,请使用 Python 标准模块 secrets 检查用户名和密码。
secrets.compare_digest() 需要接收 bytes 或仅包含 ASCII 字符(英文字符)的 str,这意味着它不能处理 á(如 Sebastián)之类的字符。
为了解决这个问题,我们首先使用 UTF-8 编码将 username 和 password 转换为 bytes。
然后我们可以使用 secrets.compare_digest() 确保 credentials.username 是 "stanleyjobson",并且 credentials.password 是 "swordfish"。
import secrets
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
def get_current_username(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
):
current_username_bytes = credentials.username.encode("utf8")
correct_username_bytes = b"stanleyjobson"
is_correct_username = secrets.compare_digest(
current_username_bytes, correct_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
correct_password_bytes = b"swordfish"
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="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/users/me")
def read_current_user(username: Annotated[str, Depends(get_current_username)]):
return {"username": username}
🤓 其他版本和变体
import secrets
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing_extensions import Annotated
app = FastAPI()
security = HTTPBasic()
def get_current_username(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
):
current_username_bytes = credentials.username.encode("utf8")
correct_username_bytes = b"stanleyjobson"
is_correct_username = secrets.compare_digest(
current_username_bytes, correct_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
correct_password_bytes = b"swordfish"
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="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/users/me")
def read_current_user(username: Annotated[str, Depends(get_current_username)]):
return {"username": username}
提示
如果可能,请优先使用 Annotated 版本。
import secrets
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
current_username_bytes = credentials.username.encode("utf8")
correct_username_bytes = b"stanleyjobson"
is_correct_username = secrets.compare_digest(
current_username_bytes, correct_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
correct_password_bytes = b"swordfish"
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="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/users/me")
def read_current_user(username: str = Depends(get_current_username)):
return {"username": username}
这类似于
if not (credentials.username == "stanleyjobson") or not (credentials.password == "swordfish"):
# Return some error
...
但是通过使用 secrets.compare_digest(),它将能抵御一种被称为“计时攻击”的攻击。
计时攻击¶
但是什么是“计时攻击”?
我们来想象一下,一些攻击者正在尝试猜测用户名和密码。
他们发送了一个用户名 johndoe 和密码 love123 的请求。
然后你的应用程序中的 Python 代码将等同于以下内容:
if "johndoe" == "stanleyjobson" and "love123" == "swordfish":
...
但就在 Python 比较 johndoe 中的第一个 j 和 stanleyjobson 中的第一个 s 时,它会返回 False,因为它已经知道这两个字符串不相同,认为“没有必要浪费更多的计算来比较其余的字母”。你的应用程序会说“不正确的用户名或密码”。
但随后攻击者尝试使用用户名 stanleyjobsox 和密码 love123。
你的应用程序代码会执行类似以下的操作
if "stanleyjobsox" == "stanleyjobson" and "love123" == "swordfish":
...
Python 必须比较 stanleyjobsox 和 stanleyjobson 中完整的 stanleyjobso,然后才能发现两个字符串不相同。因此,它会多花几微秒才能回复“用户名或密码不正确”。
响应时间帮助攻击者¶
届时,攻击者通过注意到服务器发送“不正确的用户名或密码”响应所花费的时间多出几微秒,就会知道他们 *某些地方* 是正确的,一些初始字母是正确的。
然后他们可以再次尝试,知道它可能更类似于 stanleyjobsox 而不是 johndoe。
一次“专业”的攻击¶
当然,攻击者不会手动尝试这一切,他们会编写一个程序来完成,可能每秒进行数千甚至数百万次测试。他们一次只会获得一个额外的正确字母。
但是,通过这样做,在几分钟或几小时内,攻击者将猜出正确的用户名和密码,在我们的应用程序的“帮助”下,仅仅利用响应时间。
用 secrets.compare_digest() 修复¶
但在我们的代码中,我们实际上使用了 secrets.compare_digest()。
简而言之,比较 stanleyjobsox 和 stanleyjobson 所需的时间与比较 johndoe 和 stanleyjobson 所需的时间相同。密码也是如此。
这样,在您的应用程序代码中使用 secrets.compare_digest() 将可以安全地抵御所有这些范围的安全攻击。
返回错误¶
在检测到凭据不正确后,返回一个状态码为 401 的 HTTPException(与未提供凭据时返回的状态码相同),并添加 WWW-Authenticate 请求头,使浏览器再次显示登录提示。
import secrets
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
def get_current_username(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
):
current_username_bytes = credentials.username.encode("utf8")
correct_username_bytes = b"stanleyjobson"
is_correct_username = secrets.compare_digest(
current_username_bytes, correct_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
correct_password_bytes = b"swordfish"
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="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/users/me")
def read_current_user(username: Annotated[str, Depends(get_current_username)]):
return {"username": username}
🤓 其他版本和变体
import secrets
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from typing_extensions import Annotated
app = FastAPI()
security = HTTPBasic()
def get_current_username(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
):
current_username_bytes = credentials.username.encode("utf8")
correct_username_bytes = b"stanleyjobson"
is_correct_username = secrets.compare_digest(
current_username_bytes, correct_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
correct_password_bytes = b"swordfish"
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="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/users/me")
def read_current_user(username: Annotated[str, Depends(get_current_username)]):
return {"username": username}
提示
如果可能,请优先使用 Annotated 版本。
import secrets
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
current_username_bytes = credentials.username.encode("utf8")
correct_username_bytes = b"stanleyjobson"
is_correct_username = secrets.compare_digest(
current_username_bytes, correct_username_bytes
)
current_password_bytes = credentials.password.encode("utf8")
correct_password_bytes = b"swordfish"
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="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/users/me")
def read_current_user(username: str = Depends(get_current_username)):
return {"username": username}