aman
aman

Reputation: 6262

Check if user belongs to an AD group .net core

I have an app where on login I want to check if the user is a part of a particular AD group or not. If yes then continue with the application, if not then show error: "I do have the LDAP connection address for the AD".

I am not sure how can we do this .NET core as there are not any examples to do so.

Upvotes: 10

Views: 13594

Answers (2)

Robin Wilson
Robin Wilson

Reputation: 390

I tried something similar to the above code which I was having some issues with and then realised I could just add this code to ConfigureServices in Startup.cs:

//Required for checking Active Directory Group Membership
services.AddAuthentication(IISDefaults.AuthenticationScheme);

Then in a code behind Razor page I want to restrict access to I can then add this line above the class definition:

[Authorize(Roles = "NAME OF ACTIVE DIRECTORY GROUP")]

Where NAME OF ACTIVE DIRECTORY GROUP is the name of the group you want to check membership for - e.g. Domain Admins.

This was all the code I needed in order to get this working then it uses the setting in IIS for the 403 Access Denied Page which can be customised so if a user is in a group the page is loaded and if not they are directed to the 403 error page.

I'm wondering if there is a downside to this approach given all the solutions I have found have much more code. Of course this would not be cross-platform but then I'm thinking if code is checking for Active Directory group membership them it would probably be running on IIS.

Upvotes: 3

Serg.ID
Serg.ID

Reputation: 1967

I had a similar problem and solved it by using a middleware.

  1. I added to appsettings.json line with user and groups for authentication (or which ones will be authorized), example:

    {
        "AuthenticationGroupsAndUsers": "domain\\group,domain\\username",
        "Logging": {
            "LogLevel": {
                "Default": "Warning"
            }
        }
    }
    
  2. Add a new class which will read the config and check does the current user belong to the authorized groups/users

    public class AdAuthorizationMiddleware
    {
    
        private readonly string _groupsAndUsersConfigField = "AuthenticationGroupsAndUsers";
        private readonly List<string> _authorizedGroupAndUsers;
        private IConfigurationRoot _configuration { get; }
    
        private readonly RequestDelegate _next;
    
        public AdAuthorizationMiddleware(RequestDelegate next)
        {
            // Read and save app settings
            _configuration = GetConfiguration();
            _authorizedGroupAndUsers = _configuration[_groupsAndUsersConfigField].Split(',').ToList();
    
            _next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            // Check does user belong to an authorized group or not
            var isAuthorized = _authorizedGroupAndUsers.Any(i => context.User.IsInRole(i));
            // Return error if the current user is not authorized
            if (!isAuthorized){
                context.Response.StatusCode = 403;
                return;
            }
            // Jump to the next middleware if the user is authorized
            await _next.Invoke(context);
        }
    
        private static IConfigurationRoot GetConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json");
    
            Console.WriteLine("Configuration is loaded");
            return builder.Build();
        }
    }
    
  3. Add an extension class for this middleware

    public static class AdAuthorizationMiddlewareExtension
    {
        public static IApplicationBuilder UseAdAuthorizationMiddleware(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<AdAuthorizationMiddleware>();
        }
    }
    
  4. Call this static method of the extension class in Startup.cs -> Configure method:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // ...
        //some code 
    
        app.UseAuthentication();
        app.UseAdAuthorizationMiddleware();
    
        // some routing 
        // ...
    }
    

Upvotes: 17

Related Questions