如何在 FastAPI 中验证静态路由

How to authenticate static routes in FastAPI

我在 documentation:

之后通过 FastAPI 静态提供一个文件夹
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

app.mount("/static", StaticFiles(directory="static"), name="static")

如何向此路由添加基本身份验证(用户、密码)/static

我不确定您是否可以将基本身份验证添加到路由本身,我直接将其添加到端点。但是这里有一个 link,其中包含 fastapi 的最佳身份验证模块。希望能帮助到你。我喜欢FastAPI登录

FastAPI Auth

直接从 FastAPI 文档中提取:https://fastapi.tiangolo.com/advanced/security/http-basic-auth/

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)):
    correct_username = secrets.compare_digest(credentials.username, "stanleyjobson")
    correct_password = secrets.compare_digest(credentials.password, "swordfish")
    if not (correct_username and correct_password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect email 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}