Guide Home Part 1 - FastAPI Foundations Part 2 - Building Applications Part 3 - Pages and HTML Part 4 - Security and Deployment Part 5 - Going Further Capstone Build Plan Markdown Source All Guides

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:

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.