Adding Authentication and Authorization to an ASP.NET Core Web App – the Minimalist Approach

I like to do stuff with as little code as possible. Faced with the issue of forcing authentication (using a Microsoft account) I first looked at some tutorials/guidelines but they involved an identity database accessed using Entity Framework, which I was not interested in. I just wanted to force authentication, I didn’t want users to register. So here is the minimal approach I ended up with. The web app is using razor pages and .NET 6 by the way.

  • Add Microsoft’s identity package: install-package Microsoft.Identity.Web
  • In Program.cs, add services to the container and configure the http request pipeline:
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization(options =>
    options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireUserName("user.email@outlook.com").Build());
...
app.UseAuthentication();
app.UseAuthorization();

In the lambda for AddAuthorization, I create a fallback policy, which means that pages lacking [Authorize] or [Anonymous] attributes will get that policy. This particular policy only allows a single, hard-coded user.

  • In appsettings.json, add an AzureAd section:
"AzureAd": {
    "ClientId": "...",
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "consumers",
    "CallbackPath": "/signin-oidc"
  }

For generating a client ID, go to Azure Active Directory App Registrations. Under Redirect URIs, add signin-oidc and the root for all environments, e.g. https://localhost:7235/signin-oidc and https://localhost:7235/.