> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# API Java Spring Boot

> Ajoutez l’authentification JWT d’Auth0 à une API Spring Boot avec des points de terminaison protégés

export const HowToSchema = () => <script type="application/ld+json">
    {'{"@context":"https://schema.org","@type":"HowTo"}'}
  </script>;

<HowToSchema />

<Callout icon="pencil" color="#FFC107" iconType="solid">
  Ce guide de démarrage rapide est actuellement en **bêta**. Nous serions ravis d’avoir vos commentaires!
</Callout>

<Accordion title="Utiliser l’IA pour intégrer Auth0" icon="microchip-ai" iconType="solid" defaultOpen>
  Si vous utilisez un assistant de programmation IA comme Claude Code, Cursor ou GitHub Copilot, vous pouvez ajouter automatiquement l’authentification Auth0 en quelques minutes à l’aide des [agent skills](https://agentskills.io/home).

  **Installation :**

  ```bash theme={null}
  npx skills add auth0/agent-skills --skill auth0-quickstart --skill auth0-springboot-api
  ```

  **Demandez ensuite à votre assistant IA :**

  ```text theme={null}
  Add Auth0 JWT authentication to my Spring Boot API
  ```

  Votre assistant IA créera automatiquement votre API Auth0, récupérera les informations d’identification, ajoutera la dépendance du SDK Auth0 Spring Boot API, configurera `application.yml` et implémentera une `SecurityFilterChain` avec validation des JWT et points de terminaison protégés. [Documentation complète sur les agent skills →](/fr-CA/docs/quickstart/agent-skills)
</Accordion>

<Note>
  **Prérequis :** Avant de commencer, assurez-vous d’avoir installé ce qui suit :

  * **[JDK 17+](https://openjdk.org/projects/jdk/17/)** pour assurer la compatibilité avec Spring Boot 3.2+
  * **[Maven 3.6+](https://maven.apache.org/download.cgi)** ou **[Gradle 7+](https://gradle.org/install/)** pour la gestion des dépendances
  * L’IDE de votre choix (IntelliJ IDEA, Eclipse ou VS Code avec prise en charge de Java)

  **Compatibilité des versions de Java :** Ce guide de démarrage rapide est compatible avec **Java 17+** et **Spring Boot 3.2+**.
</Note>

<div id="get-started">
  ## Pour commencer
</div>

Ce guide de démarrage rapide montre comment ajouter l’authentification JWT d’Auth0 à une API Spring Boot. Vous créerez une API sécurisée avec des points de terminaison protégés à l’aide du SDK Auth0 Spring Boot API.

<Steps>
  <Step title="Créer un nouveau projet" stepNumber={1}>
    Créez un nouveau projet d’API Spring Boot pour ce guide de démarrage rapide :

    **Avec Spring Initializr :**

    ```bash theme={null}
    curl -L https://start.spring.io/starter.zip \
        -d dependencies=web,security \
        -d javaVersion=17 \
        -d name=auth0-api \
        -d artifactId=auth0-api \
        -d packageName=com.example.auth0api \
        -o auth0-api.zip

    mkdir auth0-api && unzip auth0-api.zip -d auth0-api && cd auth0-api
    ```

    **Ou créez-le manuellement avec Maven :**

    ```bash theme={null}
    mvn archetype:generate \
        -DgroupId=com.example \
        -DartifactId=auth0-api \
        -DarchetypeArtifactId=maven-archetype-quickstart \
        -DinteractiveMode=false

    cd auth0-api
    ```
  </Step>

  <Step title="Ajouter le SDK Auth0" stepNumber={2}>
    Ajoutez le SDK d’API Auth0 Spring Boot aux dépendances de votre projet :

    **Maven (`pom.xml`) :**

    ```xml theme={null}
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>auth0-springboot-api</artifactId>
        <version>1.0.0-beta.0</version>
    </dependency>
    ```

    **Gradle (`build.gradle`) :**

    ```gradle theme={null}
    dependencies {
        implementation 'com.auth0:auth0-springboot-api:1.0.0-beta.0'
    }
    ```
  </Step>

  <Step title="Configurez votre API Auth0" stepNumber={3}>
    Ensuite, créez une nouvelle API sur votre locataire Auth0 et ajoutez la configuration à votre projet.

    Vous pouvez effectuer cette opération automatiquement en exécutant une commande CLI ou manuellement via le tableau de bord :

    <Tabs>
      <Tab title="CLI">
        Exécutez la commande shell suivante à la racine de votre projet pour créer une API Auth0 et mettre à jour votre fichier `application.yml` :

        <Tabs>
          <Tab title="Mac/Linux">
            ```bash expandable theme={null}
            AUTH0_API_NAME="My Spring Boot API" && \
            AUTH0_API_IDENTIFIER="https://my-springboot-api" && \
            brew tap auth0/auth0-cli && \
            brew install auth0 && \
            auth0 login --no-input && \
            auth0 apis create -n "${AUTH0_API_NAME}" -i "${AUTH0_API_IDENTIFIER}" --offline-access --token-lifetime 86400 --signing-alg RS256 --json > auth0-api-details.json && \
            DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && \
            AUDIENCE=$(jq -r '.identifier' auth0-api-details.json) && \
            mkdir -p src/main/resources && \
            printf 'auth0:\n  domain: %s\n  audience: %s\n\nspring:\n  application:\n    name: auth0-api\n' "$DOMAIN" "$AUDIENCE" > src/main/resources/application.yml && \
            rm auth0-api-details.json && \
            echo "✅ application.yml created with your Auth0 API details:" && \
            cat src/main/resources/application.yml
            ```
          </Tab>

          <Tab title="Windows (PowerShell)">
            ```powershell expandable theme={null}
            $ApiName = "My Spring Boot API"
            $ApiIdentifier = "https://my-springboot-api"
            $latestRelease = Invoke-RestMethod -Uri "https://api.github.com/repos/auth0/auth0-cli/releases/latest"
            $latestVersion = $latestRelease.tag_name
            $version = $latestVersion -replace "^v"
            Invoke-WebRequest -Uri "https://github.com/auth0/auth0-cli/releases/download/${latestVersion}/auth0-cli_${version}_Windows_x86_64.zip" -OutFile ".\auth0.zip"
            Expand-Archive ".\auth0.zip" .\
            [System.Environment]::SetEnvironmentVariable('PATH', $Env:PATH + ";${pwd}")
            auth0 login --no-input
            auth0 apis create -n "$ApiName" -i "$ApiIdentifier" --offline-access --token-lifetime 86400 --signing-alg RS256 --json | Set-Content -Path auth0-api-details.json
            $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name
            $Audience = (Get-Content -Raw auth0-api-details.json | ConvertFrom-Json).identifier
            New-Item -ItemType Directory -Force -Path "src\main\resources"
            @"
            auth0:
              domain: "$Domain"
              audience: "$Audience"

            spring:
              application:
                name: auth0-api
            "@ | Set-Content "src\main\resources\application.yml"
            Remove-Item auth0-api-details.json
            Write-Output "✅ application.yml created with your Auth0 API details:"
            Get-Content "src\main\resources\application.yml"
            ```
          </Tab>
        </Tabs>
      </Tab>

      <Tab title="Dashboard">
        Avant de commencer, ajoutez la configuration Auth0 à votre fichier `src/main/resources/application.yml`

        ```yaml src/main/resources/application.yml expandable theme={null}
        auth0:
          domain: "YOUR_AUTH0_DOMAIN"
          audience: "YOUR_AUTH0_API_IDENTIFIER"

        spring:
          application:
            name: auth0-api
        ```

        1. Accédez à [Auth0 Dashboard](https://manage.auth0.com) → **Applications** → **APIs**
        2. Sélectionnez **Create API**
        3. Entrez les renseignements de votre API :
           * **Name** : My Spring Boot API
           * **Identifier** : `https://my-springboot-api` (cela devient votre Audience)
           * **Signing Algorithm** : RS256
        4. Sélectionnez **Create**
        5. Remplacez `YOUR_AUTH0_DOMAIN` dans `application.yml` par votre **Domaine** à partir de l’onglet Test (par exemple, `your-tenant.auth0.com`)
        6. Remplacez `YOUR_AUTH0_API_IDENTIFIER` dans `application.yml` par votre **Identifier**. Par exemple, `https://my-springboot-api`.

        <Info>
          Votre **Domaine** ne doit pas inclure `https://`. Utilisez uniquement le domaine et la région. Par exemple : `your-tenant.auth0.com`.

          L’**Audience** (identifiant de l’API) est un identifiant unique pour votre API et peut être n’importe quel URI valide. Elle n’a pas besoin d’être une URL accessible publiquement.
        </Info>
      </Tab>
    </Tabs>
  </Step>

  <Step title="Configurer l’authentification" stepNumber={4}>
    Créez une classe de configuration de sécurité pour activer l’authentification JWT avec Auth0. Créez `src/main/java/com/example/auth0api/SecurityConfig.java` :

    ```java src/main/java/com/example/auth0api/SecurityConfig.java lines expandable theme={null}
    package com.example.auth0api;

    import com.auth0.spring.boot.Auth0AuthenticationFilter;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

    @Configuration
    public class SecurityConfig {

        @Bean
        SecurityFilterChain apiSecurity(HttpSecurity http, Auth0AuthenticationFilter authFilter) throws Exception {
            return http
                .csrf(csrf -> csrf.disable())
                .sessionManagement(session ->
                    session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/api/public").permitAll()
                    .requestMatchers("/api/private").authenticated()
                    .anyRequest().permitAll())
                .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
        }
    }
    ```
  </Step>

  <Step title="Créer des points de terminaison publics et protégés" stepNumber={5}>
    Créez des points de terminaison d’API pour tester l’authentification. Créez `src/main/java/com/example/auth0api/ApiController.java` :

    ```java src/main/java/com/example/auth0api/ApiController.java expandable theme={null}
    package com.example.auth0api;

    import com.auth0.spring.boot.Auth0AuthenticationToken;
    import org.springframework.http.ResponseEntity;
    import org.springframework.security.core.Authentication;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    import java.util.Map;

    @RestController
    @RequestMapping("/api")
    public class ApiController {

        // Point de terminaison public - aucune authentification requise
        @GetMapping("/public")
        public ResponseEntity<Map<String, String>> publicEndpoint() {
            return ResponseEntity.ok(Map.of(
                "message", "This endpoint is public - no authentication required"
            ));
        }

        // Point de terminaison protégé - authentification requise
        @GetMapping("/private")
        public ResponseEntity<Map<String, Object>> privateEndpoint(Authentication authentication) {
            Auth0AuthenticationToken auth0Token = (Auth0AuthenticationToken) authentication;

            return ResponseEntity.ok(Map.of(
                "message", "This endpoint requires authentication",
                "user", authentication.getName(),
                "scopes", auth0Token.getAuthorities()
            ));
        }
    }
    ```
  </Step>

  <Step title="Lancez votre API" stepNumber={6}>
    Démarrez votre application Spring Boot :

    **Maven :**

    ```bash theme={null}
    ./mvnw spring-boot:run
    ```

    **Gradle:**

    ```bash theme={null}
    ./gradlew bootRun
    ```

    Votre API s’exécute maintenant à l’adresse `http://localhost:8080` (consultez la sortie de la console pour l’URL exacte).
  </Step>
</Steps>

<Check>
  **Vérification**

  Vous devriez maintenant avoir une API protégée par Auth0 pleinement fonctionnelle à l’adresse [localhost](http://localhost:8080/)
</Check>

***

<div id="advanced-usage">
  ## Utilisation avancée
</div>

<Accordion title="Appel d’API protégées">
  Testez vos points de terminaison protégés avec un jeton d’accès.

  **1. Obtenez un jeton d’accès** auprès d’Auth0 à l’aide du flux Client Credentials :

  ```bash theme={null}
  curl --request POST \
    --url https://YOUR_DOMAIN/oauth/token \
    --header 'content-type: application/json' \
    --data '{"client_id":"YOUR_CLIENT_ID","client_secret":"YOUR_CLIENT_SECRET","audience":"YOUR_AUDIENCE","grant_type":"client_credentials"}'
  ```

  <Info>
    Pour obtenir `YOUR_CLIENT_ID` et `YOUR_CLIENT_SECRET`, créez une
    application Machine to Machine dans le [Auth0 Dashboard](https://manage.auth0.com/#/applications)
    et autorisez-la à accéder à votre API.
  </Info>

  **2. Testez le point de terminaison public** (devrait renvoyer 200 OK) :

  ```bash theme={null}
  curl http://localhost:8080/api/public
  ```

  **3. Testez le point de terminaison protégé sans authentification** (devrait renvoyer 401 Unauthorized) :

  ```bash theme={null}
  curl http://localhost:8080/api/private
  ```

  **4. Appelez le point de terminaison protégé avec le jeton :**

  ```bash theme={null}
  curl http://localhost:8080/api/private \
    --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
  ```
</Accordion>

<Accordion title="Accès aux claims JWT">
  Accédez à des informations supplémentaires sur l’utilisateur et aux claims du jeton dans vos points de terminaison.

  ```java theme={null}
  @GetMapping("/profile")
  public ResponseEntity<Map<String, Object>> getUserProfile(Authentication authentication) {
      Auth0AuthenticationToken auth0Token = (Auth0AuthenticationToken) authentication;
      Map<String, Object> claims = auth0Token.getAuthenticationContext().getClaims();

      return ResponseEntity.ok(Map.of(
          "userId", authentication.getName(),
          "email", claims.get("email"),
          "scope", claims.get("scope"),
          "issuer", claims.get("iss"),
          "audience", claims.get("aud")
      ));
  }
  ```
</Accordion>

<Accordion title="Autorisation basée sur les scopes">
  Implémentez un contrôle d’accès granulaire à l’aide des scopes JWT pour renforcer la sécurité.

  **1. Définissez des scopes dans votre API Auth0 :**

  Dans le [Auth0 Dashboard](https://manage.auth0.com) → APIs → Your API → Permissions, ajoutez des scopes :

  * `read:users` - Lire les données des utilisateurs
  * `write:users` - Écrire des données d’utilisateur
  * `admin` - Accès administratif

  **2. Configurez des stratégies d’autorisation :**

  ```java theme={null}
  @Configuration
  public class SecurityConfig {
      @Bean
      SecurityFilterChain apiSecurity(HttpSecurity http, Auth0AuthenticationFilter authFilter) throws Exception {
          return http
              .csrf(csrf -> csrf.disable())
              .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
              .authorizeHttpRequests(auth -> auth
                  .requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
                  .requestMatchers("/api/users/**").hasAnyAuthority("SCOPE_read:users", "SCOPE_write:users")
                  .requestMatchers("/api/private").authenticated()
                  .anyRequest().permitAll())
              .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
              .build();
      }
  }
  ```

  Lorsque vous demandez un jeton d’accès, incluez le scope requis :

  ```bash theme={null}
  curl --request POST \
    --url https://YOUR_DOMAIN/oauth/token \
    --header 'content-type: application/json' \
    --data '{"client_id":"YOUR_CLIENT_ID","client_secret":"YOUR_CLIENT_SECRET","audience":"YOUR_AUDIENCE","grant_type":"client_credentials","scope":"read:users write:users admin"}'
  ```
</Accordion>

<Accordion title="Sécurité renforcée DPoP">
  Activez DPoP (Demonstration of preuve de possession) afin de renforcer la sécurité des jetons en liant les jetons d’accès à des clés cryptographiques.

  **Configurez la prise en charge de DPoP dans application.yml :**

  ```yaml theme={null}
  auth0:
    domain: "your-tenant.auth0.com"
    audience: "https://my-springboot-api"
    dpopMode: ALLOWED # DISABLED, ALLOWED (par défaut), REQUIRED
    dpopIatOffsetSeconds: 300 # 5 minutes (par défaut)
    dpopIatLeewaySeconds: 60 # marge de 1 minute (par défaut : 30s)
  ```

  **Modes DPoP :**

  * `ALLOWED` (par défaut) : accepte à la fois les jetons Bearer et DPoP
  * `REQUIRED` : accepte uniquement les jetons DPoP et rejette les jetons Bearer
  * `DISABLED` : validation JWT Bearer standard uniquement

      <Info>
        Pour en savoir plus sur DPoP, consultez la [documentation Auth0 sur DPoP](https://auth0.com/docs/secure/sender-constraining/demonstrating-proof-of-possession-dpop).
      </Info>
</Accordion>

***

<div id="common-issues">
  ## Problèmes courants
</div>

<AccordionGroup>
  <Accordion title="401 Non autorisé - audience invalide">
    **Problème :** L’API renvoie une erreur 401 même avec des jetons valides.

    **Solution :** Assurez-vous que `auth0.audience` correspond exactement à l’identifiant de votre API Auth0. La revendication audience du jeton doit correspondre à cette valeur.

    ```yaml theme={null}
    # ❌ INCORRECT
    auth0:
      audience: "my-api"

    # ✅ CORRECT
    auth0:
      audience: "https://my-springboot-api"
    ```
  </Accordion>

  <Accordion title="401 Non autorisé - émetteur invalide">
    **Problème :** La validation de l’émetteur du jeton échoue.

    **Solution :** Vérifiez que votre Domaine est correct et n’inclut pas `https://`. Utilisez le domaine sans le préfixe `https://`.

    ```yaml theme={null}
    # ❌ INCORRECT
    auth0:
      domain: "https://your-tenant.auth0.com"

    # ✅ CORRECT
    auth0:
      domain: "your-tenant.auth0.com"
    ```
  </Accordion>

  <Accordion title="Valeurs de configuration introuvables">
    **Problème :** L’application ne démarre pas en raison d’erreurs de configuration.

    **Solution :** Vérifiez la structure de `application.yml` et les noms des propriétés. Assurez-vous que la section auth0 contient les valeurs de Domaine et d’Audience.

    ```yaml theme={null}
    # ✅ Structure CORRECTE
    auth0:
      domain: "your-tenant.auth0.com"
      audience: "https://your-api-identifier"

    spring:
      application:
        name: auth0-api
    ```
  </Accordion>

  <Accordion title="Problèmes d’ordre des filtres">
    **Problème :** L’authentification ne fonctionne pas malgré une configuration correcte.

    **Solution :** Assurez-vous que Auth0AuthenticationFilter est correctement intégré à la chaîne Spring Security. Le filtre doit être ajouté avant UsernamePasswordAuthenticationFilter.

    ```java theme={null}
    // ✅ ORDRE DES FILTRES CORRECT
    .addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
    ```
  </Accordion>

  <Accordion title="Problèmes de connectivité réseau">
    **Problème :** Échec de récupération des JWKS ou délai d’expiration de connexion.

    **Solution :** Il se peut que le pare-feu de l’entreprise bloque les points de terminaison Auth0. Autorisez les domaines Auth0 pour l’accès HTTPS :

    ```bash theme={null}
    # Règles de pare-feu requises (HTTPS/443 sortant)
    *.auth0.com
    *.us.auth0.com  # Pour les locataires de la région US
    *.eu.auth0.com  # Pour les locataires de la région EU
    *.au.auth0.com  # Pour les locataires de la région AU
    ```
  </Accordion>

  <Accordion title="Les scopes ne fonctionnent pas dans les politiques d’autorisation">
    **Problème :** Les politiques d’autorisation basées sur les scopes échouent systématiquement.

    **Solution :** Assurez-vous que votre jeton d’accès inclut les scopes requis. Lorsque vous demandez un jeton, précisez les scopes :

    ```bash theme={null}
    curl --request POST \
      --url https://YOUR_DOMAIN/oauth/token \
      --data '{"client_id":"...","client_secret":"...","audience":"...","grant_type":"client_credentials","scope":"read:users write:users admin"}'
    ```

    Vérifiez également que les scopes sont définis dans les paramètres de votre API Auth0 (Dashboard → APIs → Your API → Permissions).
  </Accordion>
</AccordionGroup>

***

<div id="additional-resources">
  ## Ressources supplémentaires
</div>

<CardGroup cols={3}>
  <Card title="Documentation du SDK" icon="book" href="https://github.com/auth0/auth0-auth-java/tree/main/auth0-springboot-api">
    Documentation complète du SDK et référence de l’API
  </Card>

  <Card title="Exemples de code" icon="code" href="https://github.com/auth0/auth0-auth-java/blob/main/auth0-springboot-api/EXAMPLES.md">
    Exemples de code complets et modèles d’intégration
  </Card>

  <Card title="Documentation sur DPoP" icon="shield" href="https://auth0.com/docs/secure/sender-constraining/demonstrating-proof-of-possession-dpop">
    Découvrez le renforcement de la sécurité par preuve de possession
  </Card>

  <Card title="Référence Spring Security" icon="book" href="https://docs.spring.io/spring-security/reference/">
    Documentation officielle de Spring Security
  </Card>

  <Card title="Auth0 Dashboard" icon="settings" href="https://manage.auth0.com/">
    Gérez vos API et applications Auth0
  </Card>

  <Card title="Forum communautaire" icon="comments" href="https://community.auth0.com/">
    Obtenez de l’aide auprès de la communauté Auth0
  </Card>
</CardGroup>

***

<div id="sample-application">
  ## Application exemple
</div>

Une application exemple complète démontrant toutes les fonctionnalités est disponible dans le dépôt du SDK.

<Card title="Application de démonstration" icon="github" href="https://github.com/auth0/auth0-auth-java/tree/main/auth0-springboot-api-playground">
  Comprend des points de terminaison publics et protégés, la prise en charge de DPoP et des
  exemples complets
</Card>

Clonez et exécutez :

```bash theme={null}
git clone https://github.com/auth0/auth0-auth-java.git
cd auth0-auth-java/auth0-springboot-api-playground

# Mettez à jour src/main/resources/application.yml avec votre configuration Auth0
# Puis exécutez :
./mvnw spring-boot:run
```

**Tester avec curl :**

```bash theme={null}
# Tester le point de terminaison public
curl http://localhost:8080/api/public

# Obtenir un jeton d'accès (remplacer par vos informations d'identification Auth0)
curl -X POST https://YOUR_DOMAIN/oauth/token \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "YOUR_CLIENT_ID",
    "client_secret": "YOUR_CLIENT_SECRET",
    "audience": "https://my-springboot-api",
    "grant_type": "client_credentials"
  }'

# Tester le point de terminaison protégé avec un jeton Bearer
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     http://localhost:8080/api/private
```
