Reputation: 381
I am statically serving a folder via FastAPI following the documentation:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
How can I add basic authentication (user, password) to this route /static
?
Upvotes: 3
Views: 3486
Reputation: 451
Pulled directly from the FastAPI docs: 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}
Upvotes: 0
Reputation: 263
Im not sure you can add basic authentication to the route itself I add it directly to the endpoint. But here's a link with the best auth modules for fastapi. Hope it helps. I like FastAPI Login.
Upvotes: 1