아미(아름다운미소)

fastapi apikey 인증 본문

랭귀지/fastapi

fastapi apikey 인증

유키공 2024. 10. 22. 08:31
my_fastapi_app/
│
├── main.py
├── auth.py
└── routers/
    └── secure.py

auth.py

# auth.py
from fastapi import Depends, HTTPException
from fastapi.security import APIKeyHeader

API_KEY = "your_api_key_here"
api_key_header = APIKeyHeader(name="X-API-Key")

def verify_api_key(api_key: str = Depends(api_key_header)):
    if api_key != API_KEY:
        raise HTTPException(status_code=403, detail="Forbidden")

routers/secure.py

# routers/secure.py
from fastapi import APIRouter, Depends
from auth import verify_api_key

router = APIRouter()

@router.get("/secure-data", dependencies=[Depends(verify_api_key)])
def read_secure_data():
    return {"message": "This is a secure endpoint!"}

main.py

# main.py
from fastapi import FastAPI
from routers.secure import router as secure_router

app = FastAPI()

# 라우터를 등록합니다.
app.include_router(secure_router)
Comments