0

I am developing a Razor Pages application with Azure Active Directory authentication. There is no page in the application which is available without authentication. I need to check whether the user authenticated by AD is present in my DB. So I need to add a validation after the user has been approved by AD.

I have created a ASP.NET core Web App C# project in Visual Studio 2022 and added Microsoft Identity Platform to Connected Services. Visual Studio added the appropriate packages, modified appsettings.json and modified Program.cs. In this file I have

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages()
    .AddMicrosoftIdentityUI();

I added app.MapRazorPages().RequireAuthorization(); to ensure that authorization is required to all pages.

I can modify authorization policy by adding

var pb = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();
pb.RequireAssertion(ctx => ctx.User?.Identity?.Name == "PreferedUserName") ;
options.DefaultPolicy =pb.Build();

to AddAuthorization action. The problem is that the user is authenticated but not authorized and when an unwanted user logs in the result is:

unwanted user log in

I want the unwnated user to be prevented from logging in and not only disallowing access to the pages.

The question is:

How to validate the user as part of the authentication?

The presented validation is rather trivial but I hope that it illustrates the problem.

IvanH
  • 5,039
  • 14
  • 60
  • 81

0 Answers0