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 the nuget Microsoft.Identity.Web NuGet package

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

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

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

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

      app.UseAuthentication();
      app.UseAuthorization();
    
      // More code
      app.UseEndpoints(endpoints =>
      {
       endpoints.MapRazorPages();  // If Razor pages
       endpoints.MapControllers(); // Needs to be added
      });
     }

Getting started with Microsoft Identity Web

Token cache serialization

Web apps

Web APIs

Daemon scenario

Advanced topics

Extensibility

Credential providers

FAQ

News

Contribute

Other resources

Clone this wiki locally