Skip to content

Instantly share code, notes, and snippets.

@johnidm
Created July 31, 2024 17:24
Show Gist options
  • Save johnidm/faa130826a398434123737d52d1406f8 to your computer and use it in GitHub Desktop.
Save johnidm/faa130826a398434123737d52d1406f8 to your computer and use it in GitHub Desktop.
Securing Application with API Key Authentication
from fastapi.security import APIKeyHeader
from fastapi import Security, HTTPException, status
from fastapi import APIRouter, FastAPI, Depends
import sqlite3


print(sqlite3.sqlite_version)

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

clients = [
    { "client" : "backend", "api_key" : "e54d4431-5dab-474e-b71a-0db1fcb9e659"},
    { "client" : "frontend", "api_key" : "5f0c7127-3be9-4488-b801-c7b6415b45e9"},
]

def get_client_from_api_key(api_key_header: str):
    return next( (item for item in clients if item["api_key"] == api_key_header), None)


def get_api_key(api_key_header: str = Security(api_key_header)):
    user = get_client_from_api_key(api_key_header)
    
    if user is None:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="API key inválida"
        )
    
    return user

    
public_router = APIRouter()

@public_router.get("/")
async def get_home():
    return "OK"

secure_router = APIRouter()
@secure_router.get("/")
async def get_testroute():
    return "OK"


app = FastAPI()

app.include_router(
    public_router,
    prefix="/api/v1/public"
)
app.include_router(
    secure_router,
    prefix="/api/v1/secure",
    dependencies=[Depends(get_api_key)]
)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000,)

curl -X GET \
    'http://0.0.0.0:8000/api/v1/secure/' \
    -H 'accept: application/json' \
    -H 'X-API-Key: e54d4431-5dab-474e-b71a-0db1fcb9e659'

curl -X 'GET' \
    'http://0.0.0.0:8000/api/v1/public/' \
    -H 'accept: application/json'  
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment