Skip to main content

HTTP Authentication Methods

FastAPI provides a set of classes in fastapi.security.http to implement standard HTTP authentication schemes. These classes integrate with FastAPI's dependency injection system to extract and validate credentials from the Authorization header of incoming requests.

The Foundation: HTTPBase

All HTTP authentication providers in this codebase inherit from HTTPBase. This base class defines the core mechanism for interacting with the Authorization header.

When a class inheriting from HTTPBase is used as a dependency, its __call__ method performs the following:

  1. Retrieves the Authorization header from the request.
  2. Uses get_authorization_scheme_param (from fastapi.security.utils) to split the header value into a scheme (e.g., "Basic" or "Bearer") and the actual credentials.
  3. If the header is missing or invalid and auto_error is True, it raises an HTTPException with a 401 status code via make_not_authenticated_error.

HTTP Basic Authentication

The HTTPBasic class implements the standard Basic authentication scheme (RFC 7617). It expects a Base64-encoded string containing a username and password separated by a colon.

Implementation Details

When HTTPBasic is invoked:

  • It decodes the Base64 parameter.
  • It partitions the decoded string at the first colon.
  • It returns an HTTPBasicCredentials object, which is a Pydantic model containing the username and password.

Example Usage

In this example from fastapi/security/http.py, the security instance is used as a dependency to provide the credentials directly to the path operation function:

from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials

app = FastAPI()
security = HTTPBasic()

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

HTTP Bearer Token Authentication

The HTTPBearer class is designed for token-based authentication, commonly used with JWTs or API keys. It validates that the scheme used in the header is exactly "Bearer".

Implementation Details

Unlike HTTPBasic, HTTPBearer does not attempt to parse the token itself. It returns an HTTPAuthorizationCredentials object containing:

  • scheme: The string "Bearer".
  • credentials: The raw token string provided in the header.

Example Usage

The following implementation shows how to use HTTPBearer to capture a token:

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

app = FastAPI()
security = HTTPBearer()

@app.get("/users/me")
def read_current_user(credentials: HTTPAuthorizationCredentials = Security(security)):
return {"scheme": credentials.scheme, "credentials": credentials.credentials}

Optional Authentication

By default, all HTTP security classes raise a 401 Unauthorized error if the Authorization header is missing or the scheme is incorrect. This behavior is controlled by the auto_error parameter in the constructor.

Setting auto_error=False allows for optional authentication. If the credentials are not provided, the dependency result will be None instead of an error:

# Example of optional bearer token
security = HTTPBearer(auto_error=False)

@app.get("/optional")
def read_optional_data(credentials: HTTPAuthorizationCredentials | None = Depends(security)):
if credentials:
return {"message": f"Hello, {credentials.credentials}"}
return {"message": "Hello, anonymous"}

Customizing Authentication Errors

The error response generated when authentication fails can be customized by subclassing the provider and overriding the make_not_authenticated_error method. This is useful if you need to return a different status code, such as 403 Forbidden, or custom headers.

As seen in the project's documentation examples (docs_src/authentication_error_status_code/tutorial001_an_py310.py), you can modify the default behavior like this:

from fastapi import HTTPException, status
from fastapi.security import HTTPBearer

class HTTPBearer403(HTTPBearer):
def make_not_authenticated_error(self) -> HTTPException:
return HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not authenticated"
)

HTTP Digest Authentication

The codebase includes an HTTPDigest class, but it serves primarily as a stub for OpenAPI documentation. While it can extract the credentials from a "Digest" scheme header into an HTTPAuthorizationCredentials object, it does not implement the complex challenge-response logic (handling nonces, opaque values, etc.) required by RFC 7616.

To use Digest authentication fully, you must subclass HTTPDigest and implement the verification logic within your application code.