Home > Software engineering >  Customizing Windows Authentication in ASP.NET Core
Customizing Windows Authentication in ASP.NET Core

Time:06-22

I noticed that I can enable Windows Auth in my ASP.NET Core app by enabling windowsAuthentication parameter in my launchSettings.json file:

  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      // ...
    }

Is there an easy way to make the authentication a bit more restrictive and allow only users who belong to a specific group in my domain?

I remember implementing this once manually and now I wonder if a feature like this is supported by .NET automatically.

I use .NET6.

EDIT

Something I have in mind (it's not a valid code, rather loud-thinking):

app.UseRouting();

app.Use(async (context, next) =>
{
    if (userBelongsToGroup(@"MySuperGroup"))
    {
        await next();
    }
    else
    {
        context.Response.StatusCode = 401;
        return;
    }
});

app.UseAuthorization();

CodePudding user response:

Maybe you could try with authorize filter as below;

public class AdminRequired : IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationFilterContext context)
        {
             var claims = context.HttpContext.User.Claims.ToList();
            if (somelogic)
            {
                UnauthorizedResult result = new UnauthorizedResult();
            }
        }
    }

add [TypeFilter(typeof(AdminRequired))] on the target action

enter image description here

CodePudding user response:

I decided to implement my own IApplicationBuilder extension and return 401 if a user does not belong to a specified group:

public static class CheckAuthorizationMiddleware
{
    [SupportedOSPlatform("windows")]
    public static IApplicationBuilder EnsureADGroup(this IApplicationBuilder app, string groupName)
    {
        return app.Use(async (context, next) =>
        {
            var groups = (context.User.Identity as System.Security.Principal.WindowsIdentity).Groups;
            var names = groups.Select(group => group.Translate(typeof(System.Security.Principal.NTAccount)).ToString());

            if (names.Contains(groupName))
            {
                await next();
            }
            else
            {
                context.Response.StatusCode = 401;
                return;
            }
        });
    }
}

In my case it works just fine, but if there are better ways of implementing this, don't hesitate to post a comment and tell me about it :).

  • Related