Skip to content

Instantly share code, notes, and snippets.

@ji-podhead
Created April 27, 2025 23:43
Show Gist options
  • Select an option

  • Save ji-podhead/19610e63c962c743143ad4acb6fb4425 to your computer and use it in GitHub Desktop.

Select an option

Save ji-podhead/19610e63c962c743143ad4acb6fb4425 to your computer and use it in GitHub Desktop.
fastapi_auth
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
app = FastAPI()
security = HTTPBearer()
def validate_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
if credentials.credentials != "secret-token": # Replace with actual token validation logic
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
)
return credentials.credentials
@app.get("/protected-route")
async def protected_route(token: str = Depends(validate_token)):
return {"message": "Access granted!"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment