Skip to main content
Saram Consulting LLC

How to Create a Secure Fast API Endpoint

To create a secure FastAPI endpoint using Microsoft Entra, you will follow a series of steps to integrate OAuth 2.0 and OpenID Connect (OIDC) for authentication and authorization, leveraging Microsoft Entra's capabilities. Microsoft Entra is a suite of identity and access management solutions, which includes Azure Active Directory (Azure AD) that provides secure sign-in and authorization services.

Here’s a step-by-step guide:

1. Setup Azure Active Directory (Azure AD) #

First, you need to have an Azure account and a subscription. Once you have that:

  1. Register an Application in Azure AD: Go to the Azure portal, find Azure Active Directory, and navigate to "App registrations". Here, you'll register your application.
  2. Get Application (client) ID and Directory (tenant) ID: After registration, note down the Application (client) ID and Directory (tenant) ID from the Overview section.
  3. Create a Client Secret: Under the "Certificates & secrets" tab, create a new client secret. Take note of the value; you'll need it later.

2. Install Required Libraries #

Ensure you have FastAPI and its dependencies installed. You'll also need python-jose for JWT tokens and httpx for making HTTP calls:

pip install fastapi uvicorn python-jose httpx

3. Create the FastAPI App #

Now, you'll create a FastAPI app that uses OAuth 2.0 with JWT tokens for secure authentication.

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2AuthorizationCodeBearer
from jose import JWTError, jwt
import httpx

# Your Azure AD configuration
TENANT_ID = "your-tenant-id"
CLIENT_ID = "your-client-id"
CLIENT_SECRET = "your-client-secret"
SCOPE = "api://your-app-client-id/.default"  # Adjust this scope based on your setup
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
TOKEN_ENDPOINT = f"{AUTHORITY}/oauth2/v2.0/token"
JWKS_URI = f"{AUTHORITY}/discovery/v2.0/keys"

oauth2_scheme = OAuth2AuthorizationCodeBearer(
    authorizationUrl=f"{AUTHORITY}/oauth2/v2.0/authorize",
    tokenUrl=TOKEN_ENDPOINT,
    refreshUrl=TOKEN_ENDPOINT,
    scopes={"api://your-app-client-id/.default": "default scope"},
)

app = FastAPI()

def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        # Decode and validate the JWT token
        # You'll need to implement the logic to validate the token against Azure AD JWKS
        payload = jwt.decode(token, JWKS_URI, algorithms=["RS256"])
        user_id: str = payload.get("sub")
        if user_id is None:
            raise credentials_exception
        return {"user_id": user_id}
    except JWTError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )

@app.get("/secure-endpoint")
def read_items(current_user: dict = Depends(get_current_user)):
    return {"message": "Secure data", "user": current_user}

4. Run Your FastAPI App #

Run your FastAPI application using uvicorn:

uvicorn main:app --reload

5. Implement Token Validation #

In the get_current_user function, you have a placeholder to decode and validate the JWT token against Azure AD's JWKS. You'll need to use the httpx library to retrieve the JWKS from Azure AD and then use the python-jose library to validate the JWT signature and claims.

Important Considerations #

This guide provides a foundational approach to securing a FastAPI endpoint using Microsoft Entra (Azure AD). Depending on your specific requirements, you might need to adjust scopes, permissions, and token validation logic.