Skip to content

Instantly share code, notes, and snippets.

@navhits
Created January 7, 2024 16:59
Show Gist options
  • Save navhits/25261d62511eb55e36b21c10c05a39e3 to your computer and use it in GitHub Desktop.
Save navhits/25261d62511eb55e36b21c10c05a39e3 to your computer and use it in GitHub Desktop.
A FastAPI example for auth using Authorization header
import os
import secrets
from fastapi import FastAPI, Security, HTTPException, status, Depends
from starlette.responses import JSONResponse
from fastapi.security.api_key import APIKeyHeader, APIKey
auth_header = APIKeyHeader(name="Authorization", auto_error=False)
async def get_auth(auth_header: str = Security(auth_header)):
auth_comp = auth_header.split(' ') if auth_header else None
if len(auth_comp) == 2:
if auth_comp[0].lower() == "token":
return secrets.compare_digest(os.getenv("TOKEN").encode('utf-8'), auth_comp[0].lower().encode('utf-8'))
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Token"})
app = FastAPI()
@app.get("/hello")
def hello(api_key: APIKey = Depends(get_auth)):
return JSONResponse(content={"message": "Hello"}, status_code=status.HTTP_200_OK,
media_type="application/json")
@Ram1103
Copy link

Ram1103 commented Jan 12, 2024

Going to give this a try!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment