Skip to content

existing web app

Jean-Marc Prieur edited this page Oct 28, 2024 · 4 revisions

Add authentication to an existing web app

  1. Add an "AzureAd" section in the appsettings.json:

    {
     "AzureAd" :
     {
      "Instance" : "https://login.microsoftonline.com",
      "TenantId" : "GUID"
      "ClientId" : "your application ID from the Entra ID app registration"
     }
    }
  2. Add the nuget Microsoft.Identity.Web NuGet package

  3. Add the following usings at the top of the file

    using Microsoft.AspNetCore.Authentication.OpenIdConnect;
    using Microsoft.Identity.Web;
  4. In the Program.cs file, after var app = builder.Build();, add:

    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
           .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
  5. Replace services.AddRazorPages() by:

      services.AddRazorPages().AddMvcOptions(options =>
      {
       var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
                 options.Filters.Add(new AuthorizeFilter(policy));
      }).AddMicrosoftIdentityUI();
     }
  6. After app.UseAuthentication(), use:

      app.UseAuthentication();
      app.UseAuthorization();
    
      // More code
      app.UseEndpoints(endpoints =>
      {
       endpoints.MapRazorPages();  // If Razor pages
       endpoints.MapControllers(); // Needs to be added
      });
     }
  7. In the controllers, add an [Authorize] attribute.

Getting started with Microsoft Identity Web

Token cache serialization

Web apps

Web APIs

Daemon scenario

Advanced topics

FAQ

News

Contribute

Other resources

Clone this wiki locally