> ## 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 explique comment intégrer Auth0 à toute application Blazor Server, nouvelle ou existante, à l’aide du SDK Auth0.AspNetCore.Authentication.

# Ajouter la fonctionnalité de connexion à votre application Blazor Server

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

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

<HowToSchema />

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

  **Installer :**

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

  **Ensuite, demandez à votre assistant IA :**

  ```text theme={null}
  Add Auth0 authentication to my Blazor Server app
  ```

  Votre assistant IA créera automatiquement votre application Auth0, récupérera les informations d’identification, installera le SDK Auth0 ASP.NET Core Authentication, configurera le middleware d’authentification et mettra en place les flux de connexion et de déconnexion. [Documentation complète sur Agent Skills →](/docs/fr-ca/quickstart/agent-skills)
</Accordion>

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

  * **[.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">
  ## Premiers pas
</div>

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

<Steps>
  <Step title="Créer un nouveau projet" stepNumber={1}>
    Créez un nouveau projet Blazor Server pour ce Quickstart

    ```shellscript theme={null}
    dotnet new blazor -n SampleBlazorApp --interactivity Server
    ```

    Ouvrir le projet

    ```shellscript theme={null}
    cd SampleBlazorApp
    ```
  </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, vous devez créer une nouvelle application sur votre tenant Auth0 et ajouter la configuration à votre projet.

    Vous pouvez choisir de configurer automatiquement votre application Auth0 en exécutant une commande CLI, ou le faire manuellement via le Dashboard :

    <Tabs>
      <Tab title="CLI">
        Exécutez la commande shell suivante à partir du répertoire racine de votre projet pour créer une application Auth0 et mettre à jour votre `appsettings.json` :

        <CodeGroup>
          ```shellscript Mac theme={null}
          # Installer Auth0 CLI (s’il n’est pas déjà installé)
          brew tap auth0/auth0-cli && brew install auth0

          # Configurer l’application Auth0 et générer appsettings.json
          auth0 qs setup --app --type regular --framework aspnet-blazor --port 5000 --name "My Blazor Server App"
          ```

          ```powershell Windows theme={null}
          # Installer Auth0 CLI (s’il n’est pas déjà installé)
          scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
          scoop install auth0

          # Configurer l’application Auth0 et générer appsettings.json
          auth0 qs setup --app --type regular --framework aspnet-blazor --port 5000 --name "My Blazor Server App"
          ```
        </CodeGroup>

        <Note>
          Cette commande permettra de :

          1. Vérifier si vous êtes authentifié (et vous inviter à vous connecter au besoin)
          2. Créer une application Web régulière Auth0 configurée pour `http://localhost:5000`
          3. Mettre à jour `appsettings.json` avec `Auth0:Domain`, `Auth0:ClientId` et `Auth0:ClientSecret`
        </Note>
      </Tab>

      <Tab title="Dashboard">
        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 au [Auth0 Dashboard](https://manage.auth0.com/dashboard/)
        2. Cliquez sur **Applications → Applications → Create Application**
        3. Entrez un nom pour votre application (p. ex., "My Blazor App")
        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 **Domain**, **Client ID** et **Client Secret** du Dashboard
      </Tab>
    </Tabs>

    **Configurer les URL de rappel :**

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

    * **URLs de rappel autorisées**: `http://localhost:5000/callback`
    * **URLs 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 **Connections**.
    </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;
    using SampleBlazorApp.Components;

    var builder = WebApplication.CreateBuilder(args);

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

    // Ajouter les composants Razor et Blazor Server
    builder.Services.AddRazorComponents()
        .AddInteractiveServerComponents();

    // Ajouter l'état d'authentification en cascade
    builder.Services.AddCascadingAuthenticationState();

    // Ajouter les pages Razor pour les endpoints d'authentification
    builder.Services.AddRazorPages();

    var app = builder.Build();

    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error", createScopeForErrors: true);
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseAntiforgery();

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

    app.MapStaticAssets();
    app.MapRazorComponents<App>()
        .AddInteractiveServerRenderMode();

    // Mapper les pages Razor pour l'authentification
    app.MapRazorPages();

    app.Run();
    ```

    <Info>
      **Remarque :** L’ordre des middleware est important. `UseAuthentication()` doit être appelé avant `UseAuthorization()`.
    </Info>
  </Step>

  <Step title="Ajouter des pages de connexion et de déconnexion" stepNumber={5}>
    Créez les pages Login et Logout pour permettre aux utilisateurs de s’authentifier.

    Créez d’abord le dossier `Pages` et les fichiers suivants :

    <Tabs>
      <Tab title="Mac/Linux">
        ```shellscript theme={null}
        mkdir -p Pages && touch Pages/Login.cshtml Pages/Login.cshtml.cs Pages/Logout.cshtml Pages/Logout.cshtml.cs Pages/_ViewImports.razor
        ```
      </Tab>

      <Tab title="Windows (PowerShell)">
        ```powershell theme={null}
        New-Item -ItemType Directory -Force -Path Pages; New-Item -ItemType File -Force -Path Pages/Login.cshtml, Pages/Login.cshtml.cs, Pages/Logout.cshtml, Pages/Logout.cshtml.cs, Pages/_ViewImports.razor
        ```
      </Tab>
    </Tabs>

    Ajoutez ensuite les extraits de code suivants :

    <AuthCodeGroup>
      ```razor Pages/Login.cshtml lines theme={null}
      @page
      @model LoginModel
      ```

      ```csharp Pages/Login.cshtml.cs lines theme={null}
      using Auth0.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Authentication;
      using Microsoft.AspNetCore.Mvc.RazorPages;

      namespace SampleBlazorApp.Pages
      {
          public class LoginModel : PageModel
          {
              public async Task OnGet(string redirectUri = "/")
              {
                  var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
                      .WithRedirectUri(redirectUri)
                      .Build();

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

      ```razor Pages/Logout.cshtml lines theme={null}
      @page
      @using Microsoft.AspNetCore.Authorization
      @attribute [Authorize]
      @model LogoutModel
      ```

      ```csharp Pages/Logout.cshtml.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.RazorPages;

      namespace SampleBlazorApp.Pages
      {
          [Authorize]
          public class LogoutModel : PageModel
          {
              public async Task OnGet()
              {
                  var authenticationProperties = new LogoutAuthenticationPropertiesBuilder()
                      .WithRedirectUri("/")
                      .Build();

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

      ```razor Components/_Imports.razor lines theme={null}
      @using System.Security.Claims
      @using Microsoft.AspNetCore.Authorization
      @using Microsoft.AspNetCore.Components.Authorization
      ```

      ```razor Pages/_ViewImports.razor lines theme={null}
      @using SampleBlazorApp.Pages
      @namespace SampleBlazorApp.Pages
      @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
      ```
    </AuthCodeGroup>
  </Step>

  <Step title="Créer la page de profil et mettre à jour le layout" stepNumber={6}>
    Créez une page de profil utilisateur personnalisée pour afficher le nom de l’utilisateur et ses claims, puis mettez à jour la mise en page pour y ajouter des liens de connexion et de déconnexion.

    Tout d’abord, créez le composant Profile :

    <Tabs>
      <Tab title="Mac/Linux">
        ```shellscript theme={null}
        touch Components/Pages/Profile.razor
        ```
      </Tab>

      <Tab title="Windows (PowerShell)">
        ```powershell theme={null}
        New-Item -ItemType File -Force -Path Components/Pages/Profile.razor
        ```
      </Tab>
    </Tabs>

    Ajoutez les extraits de code suivants. Veillez à ajouter le code `MainLayout` dans la section supérieure de votre mise en page, en conservant toutes les autres parties intactes.

    <AuthCodeGroup>
      ```razor Components/Pages/Profile.razor expandable lines theme={null}
      @page "/profile"
      @attribute [Authorize]

      <PageTitle>Profil utilisateur</PageTitle>

      <AuthorizeView>
          <Authorized>
              <div class="profile-container">
                  <img src="@context.User.FindFirst("picture")?.Value" 
                       alt="Photo de profil" 
                       class="profile-picture" />
                  
                  <h3>Bienvenue, @context.User.Identity?.Name!</h3>
                  
                  <div class="profile-details">
                      <p><strong>Courriel :</strong> @context.User.FindFirst("email")?.Value</p>
                      <p><strong>Courriel vérifié :</strong> @context.User.FindFirst("email_verified")?.Value</p>
                      <p><strong>ID utilisateur Auth0 :</strong> @context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value</p>
                  </div>

                  <h4>Tous les claims :</h4>
                  <table class="table">
                      <thead>
                          <tr>
                              <th>Type de claim</th>
                              <th>Valeur du claim</th>
                          </tr>
                      </thead>
                      <tbody>
                          @foreach (var claim in context.User.Claims)
                          {
                              <tr>
                                  <td>@claim.Type</td>
                                  <td>@claim.Value</td>
                              </tr>
                          }
                      </tbody>
                  </table>
              </div>
          </Authorized>
          <NotAuthorized>
              <p>Vous devez vous connecter pour voir cette page.</p>
              <a href="/Login?redirectUri=/profile">Se connecter</a>
          </NotAuthorized>
      </AuthorizeView>
      ```

      ```razor Components/Layout/MainLayout.razor lines theme={null}
      <div class="top-row px-4">
          <AuthorizeView>
              <NotAuthorized>
                  <a href="/Login">Se connecter</a>
              </NotAuthorized>
              <Authorized>
                  <span>Bonjour, @context.User.Identity?.Name!</span>
                  <a href="/Profile">Profil</a>
                  <a href="/Logout">Se déconnecter</a>
              </Authorized>
          </AuthorizeView>
      </div>
      ```

      ```razor Components/Routes.razor lines theme={null}
      <CascadingAuthenticationState>
          <Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
              <Found Context="routeData">
                  <AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
                  <FocusOnNavigate RouteData="routeData" Selector="h1" />
              </Found>
          </Router>
      </CascadingAuthenticationState>
      ```
    </AuthCodeGroup>
  </Step>

  <Step title="Lancez votre application" stepNumber={7}>
    ```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 **Connexion** dans le menu de navigation. Vous serez redirigé vers la page de connexion d’Auth0.
    Après vous être connecté, vous serez redirigé vers votre application et vous devriez voir votre nom dans le menu de navigation.
  </Step>
</Steps>

<Check>
  **Checkpoint**

  Vous devriez maintenant avoir une application Blazor Server protégée par Auth0 entièrement fonctionnelle, 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="Personnaliser les paramètres de connexion">
  Vous pouvez transmettre des paramètres personnalisés à la page de connexion Auth0 :

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

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

<Accordion title="Stocker les 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";
      options.UseRefreshTokens = true;
  });
  ```

  Récupérez ensuite le jeton d’accès :

  ```csharp theme={null}
  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();
  ```
</Accordion>

<Accordion title="Configurer les organisations">
  Configurez la prise en charge des organisations pour les scénarios B2B :

  ```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"];
      options.Organization = builder.Configuration["Auth0:Organization"];
  });
  ```

  Ou indiquez l’organisation au moment de la connexion :

  ```csharp Pages/Login.cshtml.cs theme={null}
  var authenticationProperties = new LoginAuthenticationPropertiesBuilder()
      .WithOrganization("org_abc123")
      .WithRedirectUri("/")
      .Build();
  ```
</Accordion>

***

<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 Domain est correct et n’inclut pas `https://`. La library construit automatiquement l’autorité.

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

    Assurez-vous également de ce qui suit :

    * Aucune barre oblique finale dans la valeur du domaine
    * Votre application a accès à Internet pour joindre Auth0
    * Le format du domaine correspond à la région de votre tenant (`.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 semblable.

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

    ```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 précéder `UseAuthorization()` :

    ```csharp Program.cs theme={null}
    app.UseRouting();
    app.UseAuthentication();  // Doit être avant UseAuthorization
    app.UseAuthorization();
    app.MapControllerRoute(...);
    ```
  </Accordion>
</AccordionGroup>

***

<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 de la communauté" icon="comments" href="https://community.auth0.com/">
    Obtenez de l’aide auprès de la communauté Auth0
  </Card>
</CardGroup>

***

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

Vous trouverez ci-dessous une application d’exemple qui montre l’intégration d’Auth0 à ASP.NET Core MVC :

<Card title="Application Blazor ASP.NET Core" icon="github" href="https://github.com/auth0-samples/auth0-aspnetcore-blazor-server-samples/tree/main/Quickstart/Sample">
  Comprend des exemples de connexion, de déconnexion, de profil d’utilisateur, etc.
</Card>

Clonez et exécutez :

```bash theme={null}
git clone https://github.com/auth0-samples/auth0-aspnetcore-blazor-server-samples/tree/main/Quickstart/Sample

# Mettez à jour appsettings.json avec votre configuration Auth0
dotnet run
```

***
