I need to implement custom authorization based on some information in on-premise Active Directory. After doing some research, I figured that best approach would be to write a custom Authentication Filter and add that information from AD to the list of claims.
So after users are authenticated by IIS using Windows Authentication, I plan to read some information and put that among the list of claims:
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, userPrincipal.Name));
claims.Add(new Claim(ClaimTypes.Role, "client"));
claims.Add(new Claim("Accounts", "[List of accounts from AD]"));
var identity = new ClaimsIdentity(claims);
var principal = new ClaimsPrincipal(new[] { identity });
context.Principal = principal;
Thread.CurrentPrincipal = context.Principal;
}
I believe that this approach will allow me to access the list of accounts from any controller. However, I am unable to add my IAuthenticationFilter implementation to the list of global filters using the following approach.
builder.Services.AddControllers(config =>
{
config.Filters.Add(new ApiAuthenticationFilter())
});
This method required IFilterMetaData interface, while I have implemented IAuthenticationFilter. In previous Web API versions, we were able to access HttpConfiguration in Application_Start() method, but in ASP.NET Core 6 Web API, I am unable to find a way to add my filter to HttpConfiguration.
Could you please tell me if that's the right approach, or I should try implementing the IActionFilter interface? Or a different approach altogether.
Thanks!
I figured
IAuthenticationFilteris not the right approach anymore to add Claims to theClaimsPrincipal. There's another interfaceIClaimsTransformationthat does exactly what I wanted.The example posted on ASP.NET website was creating a new
ClaimsIdentityinstance to theClaimsPrincipalwhile I was able to achieve that by just adding to existing list of claims:Another advantage of using
IClaimsTransformationis to be able to inject dependencies through .Net core DI container.In my Program.cs, I was unable to make it work using the recommended Authentication method:
builder.Services.AddAuthentication(IISDefaults.AuthenticationScheme);However, using Negotiate worked for me:
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();Finally, add our custom
IClaimsTranformationimplementation to services:In the past, it had to be done inside
ConfigureServices()methodMore details about IClaimsTransformation are available here: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/claims?view=aspnetcore-6.0