![[FastAPI_logo.svg|300]]
A simple python [[API]] framework based on [[Starlette]].
## Authorization
There are prebuilt security headers to use in fastapi.
- security
- bearer
- key
- oauthpasswordbearer
Use with depends to create a dependency chain for authenticating users. It is possible to add this authentication per endpoint or per router or even full app.
Secure whole router/ app:
```python
from fastapi import FastAPI, APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
app = FastAPI()
# Set up OAuth2 (as an example)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
def verify_token(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token missing subject",
headers={"WWW-Authenticate": "Bearer"},
)
return username
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate token",
headers={"WWW-Authenticate": "Bearer"},
)
# Create a router and secure all its routes using a dependency.
protected_router = APIRouter(
prefix="/protected",
dependencies=[Depends(verify_token)]
)
@protected_router.get("/items")
async def read_items():
return {"message": "This is a protected endpoint!"}
app.include_router(protected_router)
```