I have a ASP Core MVC application which uses AD authentication which is working well. I want to add an extra step to the signin, after the user is authenticated on AD, I want to verify if the user is authorized on a database, as my application can only be used by authenticated and authorized users.
This is want I have currently on Startup.cs:
// Authentication:
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddAzureAd(options =>
{
Configuration.Bind("AzureAd", options);
AzureAdOptions.Settings = options;
})
.AddCookie(options =>
{
options.EventsType = typeof(CustomCookieAuthenticationEvents);
});
I've implemented a custom class to override the sign in:
public override async Task SigningIn(CookieSigningInContext context)
{
var email = context.Principal.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress")?.Value;
// Verifies if the user is configured on the database, if it's not access must be denied.
try
{
var user = _managementDbContext.Users.Single(u => u.Email == email);
// Add tenant and role information to the claims list
context.Principal.Claims.Append(new Claim("organization", user.Tenant.Name));
context.Principal.Claims.Append(new Claim("role", user.Role.Name));
await base.SigningIn(context);
}
catch (InvalidOperationException)
{
//TODO redirect to another page
}
}
When I run the code (which database is configured to return an error and fail the authentication) the flow falls into the exception, but the authentication cookie is created either-way.
I was expecting to be able to prevent that. I'm wondering if I'm overriding the correct event.
Thank you in advance.
PS: I'm using .NET Core 2.2