> ## 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.

> Ce guide montre comment intégrer Auth0 à une application ASP.NET MVC, nouvelle ou existante, à l’aide du SDK Auth0.AspNetCore.Authentication.

# Ajouter la connexion à votre application ASP.NET MVC

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

<HowToSchema />

<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 l’authentification Auth0 automatiquement 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-aspnetcore-authentication
  ```

  **Demandez ensuite à votre assistant IA :**

  ```text theme={null}
  Add Auth0 authentication to my ASP.NET Core MVC app
  ```

  Votre assistant IA créera automatiquement votre application Auth0, récupérera les identifiants, installera le SDK Auth0 ASP.NET Core Authentication, configurera le middleware d’authentification et mettra en œuvre les flux de connexion et de déconnexion. [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é les éléments suivants :

  * **[.NET SDK](https://dotnet.microsoft.com/download)** 8.0 ou version ultérieure
  * Votre éditeur de code préféré (Visual Studio, VS Code ou Rider)
  * Un compte Auth0 ([inscrivez-vous gratuitement](https://auth0.com/signup))
</Note>

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

Auth0 vous permet d’ajouter rapidement l’authentification et d’accéder aux renseignements de profil de l’utilisateur dans votre application. Ce guide explique comment intégrer Auth0 à toute application ASP.NET MVC, nouvelle ou existante, à l’aide du SDK `Auth0.AspNetCore.Authentication`.

<Steps>
  <Step title="Créer un projet" stepNumber={1}>
    Créez un nouveau projet ASP.NET Core MVC pour ce guide de démarrage rapide

    ```shellscript theme={null}
    dotnet new mvc -n SampleMvcApp
    ```

    Ouvrez le projet

    ```shellscript theme={null}
    cd SampleMvcApp
    ```
  </Step>

  <Step title="Installer le SDK Auth0" stepNumber={2}>
    ```shellscript theme={null}
    dotnet add package Auth0.AspNetCore.Authentication
    ```
  </Step>

  <Step title="Configurez votre application Auth0" stepNumber={3}>
    Ensuite, créez une nouvelle application 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 du répertoire de votre projet pour créer une application Auth0 et mettre à jour votre fichier `appsettings.json` :

        <Tabs>
          <Tab title="Mac/Linux">
            ```shellscript theme={null}
            AUTH0_APP_NAME="My App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:5000/callback -l http://localhost:5000 -o http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-cli" > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && CLIENT_SECRET=$(jq -r '.client_secret' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && rm auth0-app-details.json && cat > appsettings.json << EOF
            {
              "Logging": {
                "LogLevel": {
                  "Default": "Information",
                  "Microsoft.AspNetCore": "Warning"
                }
              },
              "AllowedHosts": "*",
              "Auth0": {
                "Domain": "${DOMAIN}",
                "ClientId": "${CLIENT_ID}",
                "ClientSecret": "${CLIENT_SECRET}"
              }
            }
            EOF
            echo "appsettings.json created with your Auth0 details:" && cat appsettings.json
            ```
          </Tab>

          <Tab title="Windows (PowerShell)">
            ```powershell theme={null}
            $AUTH0_APP_NAME = "My MVC App"
            $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 apps create -n "${AUTH0_APP_NAME}" -t regular -c http://localhost:5000/callback -l http://localhost:5000 -o http://localhost:5000 --reveal-secrets --json --metadata created_by="quickstart-docs-cli" | Set-Content -Path auth0-app-details.json
            $AppDetails = Get-Content -Raw auth0-app-details.json | ConvertFrom-Json
            $ClientId = $AppDetails.client_id
            $ClientSecret = $AppDetails.client_secret
            $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name
            $Config = Get-Content -Raw appsettings.json | ConvertFrom-Json
            if (-not $Config.Auth0) { $Config | Add-Member -MemberType NoteProperty -Name Auth0 -Value @{} }
            $Config.Auth0.Domain = $Domain
            $Config.Auth0.ClientId = $ClientId
            $Config.Auth0.ClientSecret = $ClientSecret
            $Config | ConvertTo-Json -Depth 10 | Set-Content appsettings.json
            Remove-Item auth0-api-details.json
            Write-Output "✅ appsettings.json updated with your Auth0 API details:"
            Get-Content appsettings.json
            ```
          </Tab>
        </Tabs>
      </Tab>

      <Tab title="Tableau de bord">
        Avant de commencer, créez ou mettez à jour `appsettings.json` à la racine de votre projet

        ```json appsettings.json theme={null}
        {
          "Logging": {
            "LogLevel": {
              "Default": "Information",
              "Microsoft.AspNetCore": "Warning"
            }
          },
          "AllowedHosts": "*",
          "Auth0": {
            "Domain": "YOUR_AUTH0_DOMAIN",
            "ClientId": "YOUR_CLIENT_ID",
            "ClientSecret": "YOUR_CLIENT_SECRET"
          }
        }
        ```

        1. Accédez à l’[Auth0 Dashboard](https://manage.auth0.com/dashboard/)
        2. Cliquez sur **Applications → Applications → Create Application**
        3. Saisissez le nom de votre application (par exemple, "Mon application MVC")
        4. Sélectionnez **Regular Web Application** comme type d’application
        5. Cliquez sur **Create**
        6. Accédez à l’onglet **Settings**
        7. Remplacez `YOUR_AUTH0_DOMAIN`, `YOUR_CLIENT_ID` et `YOUR_CLIENT_SECRET` dans le fichier `appsettings.json` par les valeurs **Domaine**, **ID client** et **Secret client** de l’Auth0 Dashboard
      </Tab>
    </Tabs>

    **Configurer les URL de rappel :**

    Dans l'onglet **Settings**, configurez les URL suivantes :

    * **Allowed Callback URLs** : `http://localhost:5000/callback`
    * **URL de déconnexion autorisées**: `http://localhost:5000`
    * **Origines Web autorisées**: `http://localhost:5000`

    Cliquez sur **Enregistrer les modifications**

    <Info>
      **Important :** Assurez-vous de [configurer les connexions](https://auth0.com/docs/get-started/applications/set-up-database-connections) et de les activer pour votre application dans l’Auth0 Dashboard, sous l’onglet **Connexions**.
    </Info>
  </Step>

  <Step title="Configurer l’authentification" stepNumber={4}>
    Mettez à jour votre `Program.cs` pour configurer l’authentification avec Auth0 :

    ```csharp Program.cs lines theme={null}
    using Auth0.AspNetCore.Authentication;

    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddAuth0WebAppAuthentication(options =>
    {
        options.Domain = builder.Configuration["Auth0:Domain"];
        options.ClientId = builder.Configuration["Auth0:ClientId"];
        options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
    });

    builder.Services.AddControllersWithViews();

    var app = builder.Build();

    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    app.Run();
    ```
  </Step>

  <Step title="Ajouter les fonctionnalités de connexion et de déconnexion" stepNumber={5}>
    Créez un fichier `AccountController.cs` dans le dossier `Controllers` :

    ```csharp Controllers/AccountController.cs lines theme={null}
    using Auth0.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.Cookies;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Mvc;

    public class AccountController : Controller
    {
        public async Task Login(string returnUrl = "/")
        {
            var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                .WithRedirectUri(returnUrl)
                .Build();

            await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
        }

        [Authorize]
        public async Task Logout()
        {
            var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
                .WithRedirectUri(Url.Action("Index", "Home"))
                .Build();

            await HttpContext.SignOutAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }

        [Authorize]
        public IActionResult Profile()
        {
            return View();
        }
    }
    ```
  </Step>

  <Step title="Vue de création de profil" stepNumber={6}>
    Créez un fichier `Views/Account/Profile.cshtml` :

    ```html Views/Account/Profile.cshtml lines theme={null}
    @{
        ViewData["Title"] = "User Profile";
    }

    <div class="row">
        <div class="col-md-12">
            <h2>@ViewData["Title"]</h2>
            <div class="row">
                <div class="col-md-2">
                    <img src="@User.FindFirst(c => c.Type == "picture")?.Value" alt="User's profile picture" class="img-fluid rounded-circle" />
                </div>
                <div class="col-md-10">
                    <h3>@User.Identity.Name</h3>
                    <p><strong>Email:</strong> @User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value</p>
                    <p><strong>Email Verified:</strong> @User.FindFirst(c => c.Type == "email_verified")?.Value</p>
                    <p><strong>User ID:</strong> @User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value</p>
                </div>
            </div>
            
            <h4 class="mt-4">User Claims</h4>
            <table class="table">
                <thead>
                    <tr>
                        <th>Claim Type</th>
                        <th>Claim Value</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var claim in User.Claims)
                    {
                        <tr>
                            <td>@claim.Type</td>
                            <td>@claim.Value</td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
    </div>
    ```

    <Info>
      **Remarque :** Vous devrez d’abord créer le répertoire `Views/Account` s’il n’existe pas déjà.
    </Info>
  </Step>

  <Step title="Mettre à jour votre mise en page" stepNumber={7}>
    Mettez à jour votre fichier de mise en page pour y ajouter des boutons de connexion et de déconnexion. Dans `Views/Shared/_Layout.cshtml`, trouvez l’élément `<nav>` et remplacez-le par :

    ```html Views/Shared/_Layout.cshtml lines theme={null}
    <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
        <div class="container-fluid">
            <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">SampleMvcApp</a>
            <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                <ul class="navbar-nav flex-grow-1">
                    <li class="nav-item">
                        <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    @if (User.Identity.IsAuthenticated)
                    {
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-controller="Account" asp-action="Profile">@User.Identity.Name</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-controller="Account" asp-action="Logout">Logout</a>
                        </li>
                    }
                    else
                    {
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-controller="Account" asp-action="Login">Login</a>
                        </li>
                    }
                </ul>
            </div>
        </div>
    </nav>
    ```

    <Info>
      **Important :** Remplacez uniquement l’élément `<nav>`. Conservez toutes les autres parties de \_Layout.cshtml intactes, en particulier l’appel `@RenderBody()`, qui est nécessaire à l’affichage du contenu de la page.
    </Info>
  </Step>

  <Step title="Lancez votre application" stepNumber={8}>
    ```shellscript theme={null}
    dotnet run
    ```

    Votre application devrait démarrer et afficher l’URL d’écoute :

    ```
    info: Microsoft.Hosting.Lifetime[14]
          Now listening on: http://localhost:5000
    ```

    Ouvrez votre navigateur et accédez à `http://localhost:5000`. Cliquez sur le lien **Login** dans la barre de navigation. Vous serez redirigé vers la page de connexion d’Auth0. Une fois connecté, vous serez redirigé vers votre application, et votre nom devrait s’afficher dans la barre de navigation.
  </Step>
</Steps>

<Check>
  **Point de vérification**

  Vous devriez maintenant avoir une application MVC entièrement fonctionnelle protégée par Auth0, en cours d’exécution à l’adresse [http://localhost:5000](http://localhost:5000). Les utilisateurs peuvent se connecter, consulter leur profil et se déconnecter.
</Check>

***

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

<Accordion title="Accéder aux informations du profil de l’utilisateur">
  Vous pouvez accéder aux informations du profil de l’utilisateur à l’aide de la propriété `User` dans vos contrôleurs ou vos vues :

  ```csharp Controllers/AccountController.cs theme={null}
  [Authorize]
  public IActionResult Profile()
  {
      var user = new
      {
          Name = User.Identity.Name,
          EmailAddress = User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.Email)?.Value,
          ProfileImage = User.FindFirst(c => c.Type == "picture")?.Value,
          UserId = User.FindFirst(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier)?.Value
      };
      
      return View(user);
  }
  ```

  Les revendications de l’utilisateur contiennent des informations OIDC standard :

  * **Name** : nom d’affichage de l’utilisateur
  * **Email** : adresse courriel de l’utilisateur
  * **Picture** : URL de l’image de profil de l’utilisateur
  * **NameIdentifier** (sub) : ID unique de l’utilisateur
</Accordion>

<Accordion title="Personnaliser les paramètres de connexion">
  Vous pouvez transmettre des paramètres personnalisés à la page de connexion d’Auth0 :

  ```csharp Controllers/AccountController.cs theme={null}
  public async Task Login(string returnUrl = "/")
  {
      var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
          .WithRedirectUri(returnUrl)
          .WithParameter("screen_hint", "signup")  // Afficher la page d’inscription
          .WithParameter("ui_locales", "es")       // Définir la langue à l’espagnol
          .Build();

      await HttpContext.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
  }
  ```
</Accordion>

<Accordion title="Stocker des jetons pour les appels d’API">
  Si vous devez appeler des API externes au nom de l’utilisateur, vous pouvez récupérer et stocker des jetons :

  ```csharp Program.cs theme={null}
  builder.Services.AddAuth0WebAppAuthentication(options =>
  {
      options.Domain = builder.Configuration["Auth0:Domain"];
      options.ClientId = builder.Configuration["Auth0:ClientId"];
      options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
  })
  .WithAccessToken(options =>
  {
      options.Audience = "https://your-api.example.com";
  });
  ```

  Récupérez ensuite le jeton d’accès dans votre contrôleur :

  ```csharp Controllers/ApiController.cs theme={null}
  [Authorize]
  public async Task<IActionResult> CallApi()
  {
      var accessToken = await HttpContext.GetTokenAsync("access_token");
      
      // Utiliser le jeton d’accès pour appeler votre API
      var client = new HttpClient();
      client.DefaultRequestHeaders.Authorization = 
          new AuthenticationHeaderValue("Bearer", accessToken);
      
      var response = await client.GetAsync("https://your-api.example.com/data");
      var data = await response.Content.ReadAsStringAsync();
      
      return View(data);
  }
  ```
</Accordion>

<Accordion title="Gérer les événements d’authentification">
  Personnalisez le comportement d’authentification en gérant les événements :

  ```csharp Program.cs theme={null}
  builder.Services.AddAuth0WebAppAuthentication(options =>
  {
      options.Domain = builder.Configuration["Auth0:Domain"];
      options.ClientId = builder.Configuration["Auth0:ClientId"];
      options.ClientSecret = builder.Configuration["Auth0:ClientSecret"];
  })
  .WithAccessToken(options =>
  {
      options.Events = new Auth0WebAppWithAccessTokenEvents
      {
          OnMissingRefreshToken = async (context) =>
          {
              await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
              var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                  .WithRedirectUri("/")
                  .Build();
              
              await context.ChallengeAsync(Auth0Constants.AuthenticationScheme, authenticationProperties);
          }
      };
  });
  ```
</Accordion>

***

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

<CardGroup cols={2}>
  <Card title="Dépôt GitHub" icon="github" href="https://github.com/auth0/auth0-aspnetcore-authentication">
    Code source et suivi des problèmes
  </Card>

  <Card title="Référence de l’API" icon="code" href="https://auth0.github.io/auth0-aspnetcore-authentication/">
    Documentation détaillée de l’API
  </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="common-issues">
  ## Problèmes courants
</div>

<AccordionGroup>
  <Accordion title="Impossible d’obtenir la configuration">
    **Problème :** `Unable to obtain configuration from: https://your-tenant.auth0.com/.well-known/openid-configuration`

    **Solution :** Vérifiez que votre Domaine est correct et qu’il n’inclut pas `https://`. La bibliothèque construit automatiquement l’autorité.

    ```json theme={null}
    {
      "Auth0": {
        "Domain": "your-tenant.auth0.com"  // Correct - no protocol
      }
    }
    ```

    Assurez-vous également :

    * Qu’il n’y a pas de barre oblique à la fin de la valeur du domaine
    * Que votre application a accès à Internet pour joindre Auth0
    * Que le format du domaine correspond à la région de votre locataire (`.auth0.com`, `.us.auth0.com`, `.eu.auth0.com`)
  </Accordion>

  <Accordion title="Valeurs de configuration introuvables">
    **Problème :** `ArgumentNullException: Value cannot be null. (Parameter 'Domain')` ou un message similaire.

    **Solution :** Assurez-vous que `appsettings.json` contient la section Auth0 avec les valeurs Domain, ClientId et ClientSecret. Vérifiez également que la configuration est correctement lue :

    ```csharp Program.cs theme={null}
    builder.Services.AddAuth0WebAppAuthentication(options =>
    {
        options.Domain = builder.Configuration["Auth0:Domain"]
            ?? throw new InvalidOperationException("Auth0:Domain is required");
        options.ClientId = builder.Configuration["Auth0:ClientId"]
            ?? throw new InvalidOperationException("Auth0:ClientId is required");
        options.ClientSecret = builder.Configuration["Auth0:ClientSecret"]
            ?? throw new InvalidOperationException("Auth0:ClientSecret is required");
    });
    ```
  </Accordion>

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

    **Solution :** Assurez-vous que le middleware est dans le bon ordre. `UseAuthentication()` doit être appelé avant `UseAuthorization()` :

    ```csharp Program.cs theme={null}
    app.UseRouting();
    app.UseAuthentication();  // Must be before UseAuthorization
    app.UseAuthorization();
    app.MapControllerRoute(...);
    ```
  </Accordion>
</AccordionGroup>

***

<div id="sample-application">
  ## Exemple d’application
</div>

Vous trouverez un exemple d’application avec le code source du SDK :

<Card title="Application de démonstration ASP.NET Core MVC" icon="github" href="https://github.com/auth0/auth0-aspnetcore-authentication/tree/main/playground/Auth0.AspNetCore.Authentication.Playground">
  Comprend des exemples de connexion, de déconnexion, de profil d’utilisateur, et plus encore.
</Card>

Clonez et exécutez :

```bash theme={null}
git clone https://github.com/auth0/auth0-aspnetcore-authentication.git
cd auth0-aspnetcore-authentication/playground/Auth0.AspNetCore.Authentication.Playground
# Mettez à jour appsettings.json avec votre configuration Auth0
dotnet run
```

***
