Skip to content

Instantly share code, notes, and snippets.

@thinkjrs
Forked from nilsdebruin/fastapi_api_key.py
Last active June 18, 2022 14:25
Show Gist options
  • Save thinkjrs/13ef0d2e0ea1c3cbf73b5b95797ec876 to your computer and use it in GitHub Desktop.
Save thinkjrs/13ef0d2e0ea1c3cbf73b5b95797ec876 to your computer and use it in GitHub Desktop.
from fastapi import Security, Depends, FastAPI, HTTPException
from fastapi.security.api_key import APIKeyQuery, APIKeyHeader, APIKey
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from starlette.status import HTTP_403_FORBIDDEN
from starlette.responses import RedirectResponse, JSONResponse
API_KEY = "1234567asdfgh"
API_KEY_NAME = "access_token"
api_key_query = APIKeyQuery(name=API_KEY_NAME, auto_error=False)
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
async def get_api_key(
api_key_query: str = Security(api_key_query),
api_key_header: str = Security(api_key_header),
):
if api_key_query == API_KEY:
return api_key_query
elif api_key_header == API_KEY:
return api_key_header
else:
raise HTTPException(
status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
)
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
@app.get("/openapi.json", tags=["documentation"])
async def get_open_api_schema(api_key: APIKey = Depends(get_api_key)):
response = JSONResponse(
get_openapi(title="FastAPI security test", version=1, routes=app.routes)
)
return response
@app.get("/documentation", tags=["documentation"])
async def get_documentation(api_key: APIKey = Depends(get_api_key)):
response = get_swagger_ui_html(openapi_url="/openapi.json", title="docs")
return response
@app.get("/secure_endpoint", tags=["test"])
async def get_secure_endpoint(api_key: APIKey = Depends(get_api_key)):
response = "How cool is this?"
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment