Chapter 25: API Authentication and Bearer Tokens
ASP.NET Core APIs commonly use JWT bearer authentication. FastAPI supports OAuth2 and bearer token dependencies, but you must decide token issuing, validation, and claims mapping.
JWT guidance:
- Prefer external identity providers for production when possible.
- Validate issuer, audience, expiration, signature, and algorithm.
- Keep access tokens short-lived.
- Use refresh tokens carefully and store them securely.
- Do not put sensitive data in JWT payloads.
- Treat scopes/claims as inputs to authorization, not authorization by themselves.
FastAPI dependency shape:
from typing import Annotated
from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/token")
async def get_current_api_user(
token: Annotated[str, Depends(oauth2_scheme)],
) -> User:
claims = token_service.validate_access_token(token)
return users_service.get_user_by_subject(claims.sub)
For browser apps, prefer secure cookies plus CSRF protection. For API clients, bearer tokens are normal. Do not use local storage for highly sensitive browser tokens if a cookie-based flow is viable.