推荐答案
在 FastAPI 中,可以使用 HTTPBasic 和 HTTPBasicCredentials 来实现 HTTP Basic 认证。以下是一个简单的示例:
// www.javascriptcn.com code example
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
correct_username = "user"
correct_password = "password"
if credentials.username != correct_username or credentials.password != correct_password:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
@app.get("/secure")
def read_secure_data(username: str = Depends(get_current_username)):
return {"message": f"Hello, {username}"}在这个示例中,get_current_username 函数用于验证用户名和密码。如果验证失败,将返回 401 状态码和错误信息。
本题详细解读
1. 导入必要的模块
首先,需要导入 FastAPI 的核心模块以及用于 HTTP Basic 认证的 HTTPBasic 和 HTTPBasicCredentials。
from fastapi import FastAPI, Depends, HTTPException, status from fastapi.security import HTTPBasic, HTTPBasicCredentials
2. 创建 FastAPI 应用实例
创建一个 FastAPI 应用实例。
app = FastAPI()
3. 创建 HTTPBasic 实例
创建一个 HTTPBasic 实例,用于处理 HTTP Basic 认证。
security = HTTPBasic()
4. 定义认证函数
定义一个函数 get_current_username,该函数接收 HTTPBasicCredentials 作为参数,并验证用户名和密码。
// www.javascriptcn.com code example
def get_current_username(credentials: HTTPBasicCredentials = Depends(security)):
correct_username = "user"
correct_password = "password"
if credentials.username != correct_username or credentials.password != correct_password:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username5. 创建受保护的路由
创建一个受保护的路由 /secure,该路由依赖于 get_current_username 函数来验证用户身份。
@app.get("/secure")
def read_secure_data(username: str = Depends(get_current_username)):
return {"message": f"Hello, {username}"}6. 运行应用
最后,运行 FastAPI 应用。
uvicorn main:app --reload
通过以上步骤,你就可以在 FastAPI 中实现 HTTP Basic 认证了。