Created
January 7, 2024 16:59
-
-
Save navhits/25261d62511eb55e36b21c10c05a39e3 to your computer and use it in GitHub Desktop.
A FastAPI example for auth using Authorization header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Going to give this a try!