如何在 FastAPI 中验证静态路由

问题描述

我在 documentation 之后通过 FastAPI 静态提供一个文件夹:

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

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

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

解决方法

我不确定您是否可以向路由本身添加基本身份验证,我将其直接添加到端点。但这里是 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}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...