Passer au contenu principal

Instruction à l’IA

Vous utilisez l’IA pour intégrer Auth0 ? Ajoutez cette invite à Cursor, Windsurf, Copilot, Claude Code ou votre IDE IA préféré pour accélérer le développement.
Integrate the Auth0 FastAPI SDK into a Python API

AI PERSONA & PRIMARY OBJECTIVE
You are a helpful Auth0 SDK Integration Assistant for FastAPI APIs. Your primary function is to execute commands to set up a Python FastAPI development environment with Auth0 authentication. Your secondary function is to modify the files created during setup.

CRITICAL BEHAVIORAL INSTRUCTIONS
1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Python project (requirements.txt, pyproject.toml, or .py files). If it does, skip project creation and work with the existing project.
2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete.
3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command.
4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation.
5. SECURITY FIRST: NEVER hardcode Auth0 Domain or Audience values. ALWAYS use environment variables via python-dotenv.
6. 🚨 VIRTUAL ENVIRONMENT RULE: ALWAYS activate the virtual environment before installing packages or running the server. Never skip venv activation.

EXECUTION FLOW

⚠️ CRITICAL: Before ANY command execution, run `pwd` to check current directory and verify you're in the correct location.

Step 1: Check for Existing FastAPI Project and Prerequisites
FIRST, verify prerequisites and check for existing Python project:

  # Vérifier si Python 3.9+ et pip sont disponibles
  python3 --version && pip --version

Then examine the current directory:

  # Vérifier s'il existe un projet Python
  if [ -f "requirements.txt" ] || [ -f "pyproject.toml" ] || [ -f "app.py" ]; then
    echo "Found existing Python project"
    ls -la
  else
    echo "No Python project found, will create new project"
  fi

Based on the results:
- If an existing FastAPI project exists, proceed to Step 1b (create venv and install dependencies only)
- If no project exists, proceed to Step 1a (create new project structure)

Step 1a: Create New FastAPI Project
If no existing project, create project structure:

  mkdir my-fastapi-api && cd my-fastapi-api && python3 -m venv venv && source venv/bin/activate

⚠️ WINDOWS USERS: Use `venv\Scripts\activate` instead of `source venv/bin/activate`

Step 1b: Work with Existing Project
If project exists, create and activate virtual environment:

  python3 -m venv venv && source venv/bin/activate

Step 2: Install Dependencies
Create requirements.txt with the following content:

  cat > requirements.txt << 'EOF'
  fastapi>=0.115.0
  uvicorn[standard]>=0.34.0
  auth0-fastapi-api>=1.0.0b5
  python-dotenv>=1.0.0
  EOF

Then install dependencies (MUST be in activated venv):

  pip install -r requirements.txt

Step 3: Setup Auth0 API

⚠️ CRITICAL: Verify you're in the project directory with `pwd` before running Auth0 CLI commands.

Step 3a: Execute Auth0 CLI Setup

If MacOS, execute:

  AUTH0_API_NAME="My FastAPI API" && AUTH0_API_IDENTIFIER="https://my-fastapi-api" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apis create --name "${AUTH0_API_NAME}" --identifier "${AUTH0_API_IDENTIFIER}" --signing-alg RS256 --no-input && echo "AUTH0_DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name')\nAUTH0_AUDIENCE=${AUTH0_API_IDENTIFIER}" > .env

If Windows, execute:

  $ApiName = "My FastAPI API"; $ApiIdentifier = "https://my-fastapi-api"; auth0 login --no-input; auth0 apis create -n $ApiName -i $ApiIdentifier --signing-alg RS256 --no-input; $ActiveTenant = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; "AUTH0_DOMAIN=$ActiveTenant`nAUTH0_AUDIENCE=$ApiIdentifier" | Out-File -FilePath .env -Encoding utf8

Step 3b: Verify .env file was created correctly

  cat .env

Expected output:
  AUTH0_DOMAIN=your-domain.auth0.com
  AUTH0_AUDIENCE=https://my-fastapi-api

⚠️ If AUTH0_DOMAIN is null or missing, manually add your Auth0 domain to the .env file.

Step 3c: Add Permissions in Auth0 Dashboard (Manual Step)
Inform the user to:
1. Navigate to Applications > APIs in Auth0 Dashboard
2. Select "My FastAPI API"
3. Go to Permissions tab
4. Add permissions:
   - Permission: `read:messages`, Description: "Read messages"
   - Permission: `write:messages`, Description: "Write messages"

Step 4: Create FastAPI Application with Auth0
Create app.py with the following content:

  cat > app.py << 'EOF'
  from fastapi import FastAPI, Depends
  from fastapi_plugin.fast_api_client import Auth0FastAPI
  import os
  from dotenv import load_dotenv

  # Charger les variables d'environnement
  load_dotenv()

  app = FastAPI()

  # Initialiser Auth0
  auth0 = Auth0FastAPI(
      domain=os.environ.get("AUTH0_DOMAIN"),
      audience=os.environ.get("AUTH0_AUDIENCE")
  )

  # Route publique - aucune authentification requise
  @app.get("/api/public")
  async def public():
      return {
          "message": "Hello from a public endpoint! You don't need to be authenticated to see this."
      }

  # Route protégée - authentification requise
  @app.get("/api/private")
  async def private(claims: dict = Depends(auth0.require_auth())):
      return {
          "message": "Hello from a private endpoint! You need to be authenticated to see this.",
          "user_id": claims.get("sub")
      }

  # Route avec scope - permission spécifique requise
  @app.get("/api/private-scoped")
  async def private_scoped(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
      return {
          "message": "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.",
          "user_id": claims.get("sub")
      }
  EOF

Step 5: Run the FastAPI Application

⚠️ CRITICAL: Verify virtual environment is activated before running uvicorn.

  # Vérifier que le venv est activé (vous devriez voir (venv) dans votre invite de commande)
  which python

  # Démarrer le serveur
  uvicorn app:app --reload

Expected output: Server starts on http://127.0.0.1:8000

Step 6: Test the API

6a: Test public endpoint (no authentication required):

  curl http://localhost:8000/api/public

6b: Test protected endpoints (authentication required):
Inform the user to:
1. Get access token from Auth0 Dashboard:
   - Navigate to Applications > APIs
   - Select "My FastAPI API"
   - Click "Test" tab
   - Click "Copy Token"

2. Test private endpoint:

  curl -X GET http://localhost:8000/api/private -H 'authorization: Bearer YOUR_ACCESS_TOKEN'

3. Test scoped endpoint:

  curl -X GET http://localhost:8000/api/private-scoped -H 'authorization: Bearer YOUR_ACCESS_TOKEN'

ANTI-PATTERNS - NEVER DO THESE

1. ❌ NEVER hardcode Auth0 credentials in Python code
   - WRONG: auth0 = Auth0FastAPI(domain="dev-example.us.auth0.com", audience="https://my-api")
   - ✓ CORRECT: Always use environment variables via dotenv

2. ❌ NEVER skip virtual environment activation
   - WRONG: Installing packages without activating venv first
   - ✓ CORRECT: Always activate venv first with `source venv/bin/activate`

3. ❌ NEVER use multi-line curl commands with backslashes (they often fail)
   - ✓ CORRECT: Use single-line format: `curl -X GET <url> -H 'authorization: Bearer TOKEN'`

4. ❌ NEVER proceed if .env file has null values
   - WRONG: AUTH0_DOMAIN=null in .env file
   - ✓ CORRECT: Verify .env contains valid Auth0 domain before proceeding

ABSOLUTE REQUIREMENTS

1. ✓ Virtual environment MUST be activated before pip install
2. ✓ .env file MUST contain valid AUTH0_DOMAIN (not null)
3. ✓ .env file MUST be added to .gitignore to prevent credential exposure
4. ✓ Auth0FastAPI MUST use os.environ.get() for credentials
5. ✓ All endpoints requiring authentication MUST use Depends(auth0.require_auth())

COMMON ISSUES & SOLUTIONS

1. **ModuleNotFoundError: No module named 'fastapi_plugin'**
   - Cause : Mauvais environnement virtuel activé ou environnement virtuel non activé
   - Solution : Désactivez tous les environnements virtuels, puis activez le bon dans le répertoire du projet

2. **AUTH0_DOMAIN est nul dans .env**
   - Cause : La commande CLI Auth0 n'extrait pas correctement le domaine
   - Solution : Ajoutez manuellement le domaine au fichier .env depuis le tableau de bord Auth0

3. **401 Non autorisé - Émetteur invalide**
   - Cause : AUTH0_DOMAIN inclut le protocole https://
   - Solution : Le domaine doit être simplement `dev-example.us.auth0.com` sans protocole

4. **401 Non autorisé - Audience invalide**
   - Cause : AUTH0_AUDIENCE ne correspond pas à l'identifiant de l'API
   - Solution : Vérifiez que AUTH0_AUDIENCE correspond exactement à l'identifiant dans le tableau de bord Auth0

5. **403 Interdit - Scope insuffisant**
   - Cause : Le jeton d'accès n'inclut pas le scope requis
   - Solution : Vérifiez que les permissions existent dans le tableau de bord Auth0 et que le jeton les inclut

LISTE DE VÉRIFICATION

Avant de considérer l'intégration comme terminée, vérifiez :
- [ ] L'environnement virtuel est activé (vérifiez avec `which python`)
- [ ] Le fichier .env existe et contient un AUTH0_DOMAIN valide (non nul)
- [ ] .env est ajouté à .gitignore
- [ ] app.py importe et initialise Auth0FastAPI correctement
- [ ] L'endpoint public renvoie 200 OK sans authentification
- [ ] L'endpoint privé renvoie 401 sans jeton
- [ ] L'endpoint privé renvoie 200 avec un jeton valide
- [ ] L'endpoint avec scope renvoie 403 sans le scope requis
- [ ] L'endpoint avec scope renvoie 200 avec un jeton contenant le scope read:messages
Ce guide de démarrage rapide nécessite :
  • Python 3.9 ou une version ultérieure
  • Le gestionnaire de paquets pip
  • jq - requis pour la configuration d’Auth0 CLI
  • Une connaissance de FastAPI
Si ce n’est pas déjà fait, créez un compte Auth0 gratuit pour suivre ce guide.
Ce guide montre comment intégrer Auth0 à une API FastAPI pour ajouter l’authentification et protéger vos endpoints.
1

Créer un projet FastAPI

Créez un nouveau répertoire pour votre projet FastAPI, puis configurez un environnement virtuel.
mkdir my-fastapi-api
cd my-fastapi-api
python3 -m venv venv
source venv/bin/activate  # Windows : venv\Scripts\activate
2

Installer les dépendances

Créez un fichier requirements.txt contenant les dépendances suivantes :
requirements.txt
fastapi>=0.115.0
uvicorn[standard]>=0.34.0
auth0-fastapi-api>=1.0.0b5
python-dotenv>=1.0.0
Installez les dépendances :
pip install -r requirements.txt
3

Configurez votre API Auth0

Vous devrez créer une API Auth0 pour représenter votre application FastAPI.
  1. Accédez à Applications > APIs dans l’Auth0 Dashboard
  2. Cliquez sur Create API
  3. Saisissez un Name pour votre API (p. ex., “My FastAPI API”)
  4. Définissez l’Identifier sur l’identifiant de votre API (p. ex., https://my-fastapi-api)
  5. Laissez Signing Algorithm à RS256
  6. Cliquez sur Create
L’Identifier est un identifiant unique pour votre API. Nous recommandons d’utiliser une URL, mais elle n’a pas à être accessible publiquement — Auth0 ne l’appellera pas. Cette valeur ne peut pas être modifiée par la suite.
Prenez note des valeurs Domaine et Identifier (Audience). Vous en aurez besoin à l’étape suivante.
4

Définir les permissions de l’API

Les permissions (aussi appelées scopes) vous permettent de définir comment votre API peut être accessible. Vous pouvez créer des permissions pour votre API dans Auth0 Dashboard.
  1. Dans Auth0 Dashboard, accédez à l’onglet Permissions de votre API
  2. Ajoutez les permissions suivantes :
    • read:messages avec la description “Lire les messages”
    • write:messages avec la description “Écrire les messages”
Ces permissions serviront à contrôler l’accès à des points de terminaison précis de votre API.
5

Configurer l’application Auth0

Créez un fichier .env à la racine de votre projet pour y stocker votre configuration d’Auth0 :
.env
AUTH0_DOMAIN=YOUR_AUTH0_DOMAIN
AUTH0_AUDIENCE=YOUR_API_IDENTIFIER
Remplacez YOUR_AUTH0_DOMAIN par votre domaine Auth0 (par exemple, dev-abc123.us.auth0.com) et YOUR_API_IDENTIFIER par l’identifiant que vous avez défini lors de la création de votre API.
N’ajoutez jamais votre fichier .env au contrôle de version. Ajoutez-le à votre fichier .gitignore pour protéger vos identifiants.
Créez maintenant un fichier app.py et initialisez votre application FastAPI avec Auth0 :
app.py
from fastapi import FastAPI, Depends
from fastapi_plugin.fast_api_client import Auth0FastAPI
import os
from dotenv import load_dotenv

# Charger les variables d'environnement
load_dotenv()

app = FastAPI()

# Initialiser Auth0
auth0 = Auth0FastAPI(
    domain=os.environ.get("AUTH0_DOMAIN"),
    audience=os.environ.get("AUTH0_AUDIENCE")
)
6

Créer des routes protégées

Ajoutez les routes suivantes à votre fichier app.py. Elles illustrent différents niveaux de contrôle d’accès :
app.py
from fastapi import FastAPI, Depends
from fastapi_plugin.fast_api_client import Auth0FastAPI
import os
from dotenv import load_dotenv

load_dotenv()

app = FastAPI()

auth0 = Auth0FastAPI(
    domain=os.environ.get("AUTH0_DOMAIN"),
    audience=os.environ.get("AUTH0_AUDIENCE")
)

# Route publique - aucune authentification requise
@app.get("/api/public")
async def public():
    return {
        "message": "Hello from a public endpoint! You don't need to be authenticated to see this."
    }

# Route protégée - authentification requise
@app.get("/api/private")
async def private(claims: dict = Depends(auth0.require_auth())):
    return {
        "message": "Hello from a private endpoint! You need to be authenticated to see this.",
        "user_id": claims.get("sub")
    }

# Route avec scope - permission spécifique requise
@app.get("/api/private-scoped")
async def private_scoped(claims: dict = Depends(auth0.require_auth(scopes="read:messages"))):
    return {
        "message": "Hello from a private endpoint! You need to be authenticated and have a scope of read:messages to see this.",
        "user_id": claims.get("sub")
    }
La méthode require_auth() valide le jeton d’accès envoyé dans l’en-tête Authorization. Lorsqu’elle est appelée avec un paramètre scopes, elle vérifie également que le jeton contient la permission spécifiée.
7

Lancez votre API

Démarrez votre application FastAPI :
uvicorn app:app --reload
Votre API fonctionne maintenant à l’adresse http://localhost:8000.
Ouvrez http://localhost:8000/api/public dans votre navigateur. Vous devriez voir le message public sans avoir à vous authentifier.

Testez votre API

Pour tester les points de terminaison protégés, vous devez obtenir un jeton d’accès auprès d’Auth0.

Obtenir un jeton d’accès

Le moyen le plus simple d’obtenir un jeton d’accès à des fins de test est de passer par Auth0 Dashboard :
  1. Accédez à Applications > APIs dans Auth0 Dashboard
  2. Sélectionnez votre API
  3. Cliquez sur l’onglet Test
  4. Cliquez sur Copy Token dans la section Asking Auth0 for tokens from my application

Appelez votre API

Utilisez le jeton d’accès pour appeler votre point de terminaison protégé :
curl -X GET http://localhost:8000/api/private -H 'authorization: Bearer YOUR_ACCESS_TOKEN'
Vous devriez recevoir une réponse contenant le message privé et votre ID utilisateur. Pour tester le point de terminaison associé à ce scope, assurez-vous que votre jeton inclut le scope read:messages :
curl -X GET http://localhost:8000/api/private-scoped -H 'authorization: Bearer YOUR_ACCESS_TOKEN'
Si votre jeton n’a pas le scope requis, vous recevrez une réponse 403 Forbidden.

Utilisation avancée

Vous pouvez accéder aux revendications personnalisées ajoutées au jeton d’accès à l’aide d’Auth0 Actions.Accédez aux revendications personnalisées dans votre gestionnaire de route :
@app.get("/api/profile")
async def profile(claims: dict = Depends(auth0.require_auth())):
    return {
        "user_id": claims.get("sub"),
        "email": claims.get("email"),
        "permissions": claims.get("permissions", []),
        "custom_claim": claims.get("https://myapp.example.com/custom_claim")
    }
Pour ajouter des revendications personnalisées à vos jetons d’accès, créez une Auth0 Action :
  1. Accédez à Actions > bibliothèque dans l’Auth0 Dashboard
  2. Cliquez sur Create Action
  3. Sélectionnez Build from scratch
  4. Donnez un nom à votre action et sélectionnez le déclencheur Login / Post Login
  5. Ajoutez vos revendications personnalisées :
exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://myapp.example.com';

  if (event.authorization) {
    // Ajouter un claim personnalisé au jeton d’accès
    api.accessToken.setCustomClaim(`${namespace}/roles`, event.user.app_metadata.roles || []);
  }
};
  1. Cliquez sur Deploy et ajoutez l’action à votre flux de connexion
Les revendications personnalisées doivent utiliser un format avec espace de noms (p. ex. https://myapp.example.com/claim_name) afin d’éviter les conflits avec les revendications standard.
Si vous devez protéger un point de terminaison sans avoir besoin d’accéder aux revendications, vous pouvez utiliser le paramètre dependencies :
@app.get("/api/protected", dependencies=[Depends(auth0.require_auth())])
async def protected():
    return {"message": "This endpoint is protected"}
Cela valide le jeton d’accès, mais n’injecte pas les revendications dans votre fonction.
DPoP (Demonstrating Proof-of-Possession) est actuellement en Accès anticipé. Communiquez avec Auth0 support pour l’activer pour votre locataire.
DPoP renforce la sécurité en liant cryptographiquement les jetons d’accès à l’application cliente qui les a demandés. Cela empêche le vol de jetons et les attaques par rejeu.Le SDK active la prise en charge de DPoP par défaut. Vous pouvez configurer le comportement de DPoP :
auth0 = Auth0FastAPI(
    domain=os.environ.get("AUTH0_DOMAIN"),
    audience=os.environ.get("AUTH0_AUDIENCE"),
    dpop_enabled=True,      # Activer DPoP (par défaut : True)
    dpop_required=False     # Exiger DPoP (par défaut : False)
)
Le mode mixte (par défaut) accepte à la fois les jetons Bearer et DPoP :
auth0 = Auth0FastAPI(
    domain=os.environ.get("AUTH0_DOMAIN"),
    audience=os.environ.get("AUTH0_AUDIENCE"),
    dpop_enabled=True,
    dpop_required=False
)
Le mode DPoP uniquement rejette les jetons Bearer :
auth0 = Auth0FastAPI(
    domain=os.environ.get("AUTH0_DOMAIN"),
    audience=os.environ.get("AUTH0_AUDIENCE"),
    dpop_required=True
)
Lorsque vous utilisez DPoP, les applications clientes doivent inclure à la fois les en-têtes Authorization: DPoP <token> et DPoP: <proof>. Le SDK valide automatiquement la preuve DPoP et l’associe au jeton d’accès.
Activez trust_proxy uniquement lorsque votre application se trouve derrière un proxy inverse approuvé. Ne l’activez jamais pour des applications exposées directement à Internet.
Si votre application s’exécute derrière un proxy inverse (nginx, AWS ALB, etc.), vous devez activer la confiance envers le proxy pour que la validation DPoP fonctionne correctement :
from fastapi import FastAPI

app = FastAPI()

# Activer la confiance envers le proxy
app.state.trust_proxy = True

auth0 = Auth0FastAPI(
    domain=os.environ.get("AUTH0_DOMAIN"),
    audience=os.environ.get("AUTH0_AUDIENCE")
)
Configurez votre proxy inverse pour transférer les en-têtes nécessaires :
location /api {
    proxy_pass http://localhost:8000;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Prefix /api;
}
C’est essentiel pour la validation DPoP, car le SDK doit faire correspondre exactement l’URL utilisée par l’application cliente. Sans confiance envers le proxy, votre application voit des URL internes, tandis que les preuves DPoP font référence à des URL externes, ce qui entraîne des échecs de validation.
Le SDK déclenche une HTTPException en cas d’erreurs d’authentification. FastAPI les gère automatiquement et renvoie au client les réponses HTTP appropriées.Vous pouvez mettre en place une gestion personnalisée des erreurs au besoin :
from fastapi import Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import HTTPException

@app.exception_handler(HTTPException)
async def custom_http_exception_handler(request: Request, exc: HTTPException):
    if exc.status_code in [401, 403]:
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "error": "authentication_failed",
                "message": "You must be authenticated to access this resource",
                "details": exc.detail
            }
        )
    return JSONResponse(
        status_code=exc.status_code,
        content={"detail": exc.detail}
    )
Les erreurs d’authentification comprennent :
  • 401 Unauthorized : jeton d’accès manquant, invalide ou expiré
  • 403 Forbidden : jeton valide, mais permissions insuffisantes (scopes)

Problèmes courants

Problème : La validation du jeton échoue avec l’erreur « Invalid audience ».Solution : Vérifiez que AUTH0_AUDIENCE dans votre fichier .env correspond exactement à l’Identifier que vous avez configuré pour votre API dans l’Auth0 Dashboard.
  1. Ouvrez l’Auth0 Dashboard et accédez à Applications > APIs
  2. Sélectionnez votre API
  3. Vérifiez la valeur Identifier dans l’onglet Settings
  4. Mettez à jour votre fichier .env :
    AUTH0_AUDIENCE=https://your-exact-api-identifier
    
  5. Redémarrez votre application
Problème : La validation du jeton échoue avec l’erreur « Invalid issuer ».Solution : Vérifiez que votre AUTH0_DOMAIN est correct et qu’il n’inclut pas le protocole https://.Votre domaine devrait ressembler à dev-abc123.us.auth0.com, et non à https://dev-abc123.us.auth0.com.Mettez à jour votre fichier .env :
AUTH0_DOMAIN=dev-abc123.us.auth0.com
Problème : Le point de terminaison protégé retourne un code 403 même avec un jeton d’accès valide.Solution : Le jeton d’accès n’inclut pas le scope requis.
  1. Vérifiez quels scopes sont requis par votre point de terminaison
  2. Lorsque vous demandez un jeton, assurez-vous d’inclure les scopes requis
  3. Vérifiez que le scope existe dans l’onglet permission de votre API dans l’Auth0 Dashboard
  4. Décodez votre jeton sur jwt.io pour vérifier qu’il contient la revendication scope avec les valeurs requises
Problème : Python ne parvient pas à trouver le SDK Auth0 FastAPI.Solution : Assurez-vous que le SDK est installé dans votre environnement virtuel actif.
# Activez votre environnement virtuel
source venv/bin/activate  # Windows: venv\Scripts\activate

# Installez le SDK
pip install auth0-fastapi-api

# Vérifiez l’installation
pip show auth0-fastapi-api
Problème : L’application ne parvient pas à récupérer les clés de signature depuis Auth0.Solution : Vérifiez votre connectivité réseau et la configuration de votre domaine.
  1. Vérifiez que votre domaine est accessible :
    curl https://YOUR_DOMAIN/.well-known/openid-configuration
    
  2. Vérifiez que votre pare-feu autorise les connexions HTTPS sortantes (port 443) vers *.auth0.com
  3. Si vous êtes derrière un proxy d’entreprise, configurez les variables d’environnement HTTP_PROXY et HTTPS_PROXY
Problème : L’authentification DPoP retourne des erreurs liées à l’URL ou à la validation de la preuve.Solution :
  1. Si vous êtes derrière un proxy inverse, activez la confiance du proxy :
    app.state.trust_proxy = True
    
  2. Vérifiez que votre proxy transmet ces en-têtes :
    • X-Forwarded-Proto
    • X-Forwarded-Host
    • X-Forwarded-Prefix
  3. Assurez-vous que DPoP est activé pour votre locataire (contactez Auth0 Support)
  4. Vérifiez que la revendication htu de la preuve DPoP correspond exactement à l’URL de votre requête

Prochaines étapes

Documentation du SDK

Explorez le SDK Auth0 FastAPI sur GitHub pour la configuration avancée et des exemples

Scopes et permissions

Découvrez comment définir et utiliser les scopes pour un contrôle d’accès granulaire

Auth0 Actions

Personnalisez votre flux d’authentification et ajoutez des claims personnalisés aux jetons

Documentation FastAPI

Découvrez les fonctionnalités de FastAPI, les modèles asynchrones et les pratiques exemplaires

Autorisation de l’API

Implémentez le contrôle d’accès basé sur les rôles (RBAC) pour votre API

Déployer en production

Pratiques exemplaires pour déployer des applications FastAPI avec Auth0