Created
April 27, 2025 23:43
-
-
Save ji-podhead/19610e63c962c743143ad4acb6fb4425 to your computer and use it in GitHub Desktop.
fastapi_auth
This file contains hidden or 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
| 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