BudiBadu Logo
Samplebadu

FastAPI by Example: OAuth2 Bearer Schema

FastAPI 0.100+

FastAPI provides built-in support for OAuth2, making it easy to implement secure authentication. This code example demonstrates how to set up the `OAuth2PasswordBearer` scheme to extract tokens.

Code

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from typing import Annotated

app = FastAPI()

# 1. Define the scheme
# tokenUrl is where the client sends username/password to get a token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

# 2. Dependency to extract token
async def get_current_token(token: Annotated[str, Depends(oauth2_scheme)]):
    # In a real app, you would verify the token here
    if token != "fake-super-secret-token":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return token

@app.get("/items/")
async def read_items(token: Annotated[str, Depends(get_current_token)]):
    return {"token": token}

# Dummy route to simulate getting a token
@app.post("/token")
async def login():
    return {"access_token": "fake-super-secret-token", "token_type": "bearer"}

Explanation

The OAuth2PasswordBearer class is a security utility that tells FastAPI that the API uses OAuth2 with Bearer tokens. When used as a dependency, it automatically looks for the Authorization header in the incoming request, checks if it starts with Bearer, and extracts the token string. If the header is missing or malformed, FastAPI automatically returns a 401 Unauthorized error, simplifying the authentication flow for developers.

This scheme integrates seamlessly with the automatic API documentation provided by Swagger UI. By specifying the tokenUrl parameter, the documentation interface enables the "Authorize" button, allowing developers to log in and test protected endpoints directly from the browser. This feature streamlines the testing process and ensures that the security configuration is transparent and easy to verify.

It is important to note that OAuth2PasswordBearer is responsible solely for extracting the token, not for verifying its validity. The actual verification logic, such as checking a JWT signature or looking up a session in a database, must be implemented within the dependency function. This separation of concerns allows for flexibility in choosing the underlying authentication mechanism while maintaining a consistent interface for token extraction.

Code Breakdown

9
tokenUrl="token" points to the relative URL that clients should use to obtain a token.
12
Depends(oauth2_scheme) declares the dependency that extracts the token.
14
if token != ... simulates verification. In production, you would verify the JWT signature here.
18
WWW-Authenticate: Bearer header is required by the HTTP spec for 401 responses.