Skip to main content

Working with HTTP Bearer Tokens

When you need to protect your API using Bearer tokens (such as JSON Web Tokens), FastAPI provides the HTTPBearer class to automatically extract the token from the Authorization header.

Extracting Bearer Tokens

To require a Bearer token for a path operation, create an instance of HTTPBearer and use it as a dependency. FastAPI will look for an Authorization header with the Bearer scheme and return an HTTPAuthorizationCredentials object.

from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

app = FastAPI()

security = HTTPBearer()

@app.get("/users/me")
def read_current_user(
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]
):
return {"scheme": credentials.scheme, "credentials": credentials.credentials}

The HTTPAuthorizationCredentials object contains two attributes:

  • scheme: The authentication scheme found (e.g., "Bearer").
  • credentials: The actual token string extracted from the header.

Optional Authentication

If you want to allow requests without a token, set auto_error=False when initializing HTTPBearer. When the header is missing or invalid, the dependency will return None instead of raising an exception.

from fastapi import FastAPI, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

app = FastAPI()

# Setting auto_error=False makes the dependency optional
security = HTTPBearer(auto_error=False)

@app.get("/users/me")
def read_current_user(
credentials: HTTPAuthorizationCredentials | None = Security(security),
):
if credentials is None:
return {"msg": "Guest user"}
return {"token": credentials.credentials}

Customizing Authentication Errors

By default, HTTPBearer raises an HTTPException with a 401 Unauthorized status code and a WWW-Authenticate: Bearer header if the token is missing. You can customize this behavior by subclassing HTTPBearer and overriding the make_not_authenticated_error method.

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

class HTTPBearer403(HTTPBearer):
def make_not_authenticated_error(self) -> HTTPException:
return HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Custom authentication error message"
)

app = FastAPI()
security = HTTPBearer403()

@app.get("/secure-data")
def get_secure_data(credentials: Annotated[HTTPAuthorizationCredentials, Depends(security)]):
return {"message": "Access granted"}

Configuring OpenAPI Documentation

You can customize how the security scheme appears in the generated /docs (Swagger UI) using the bearerFormat, scheme_name, and description parameters.

security = HTTPBearer(
bearerFormat="JWT",
scheme_name="JWT_Auth",
description="Enter your JWT token to access this API"
)
  • bearerFormat: A string used purely for documentation purposes (e.g., "JWT") to hint to the client what type of token is expected.
  • scheme_name: The name of the security scheme in the OpenAPI components.
  • description: A description that will appear in the documentation UI.

Important Considerations

  • No Automatic Validation: HTTPBearer only extracts the token from the header and verifies that the scheme is "Bearer" (case-insensitive). It does not validate the token's content, expiration, or signature. You must perform these checks (e.g., using a library like PyJWT or python-jose) within your dependency or path operation.
  • Header Parsing: FastAPI uses fastapi.security.utils.get_authorization_scheme_param internally to split the Authorization header. It expects the format Bearer <token>. If the header is malformed or the scheme is not Bearer, and auto_error is True, the request will be rejected.