Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 635
aman Avatar asked Dec 27 '17 03:12

aman


People also ask

How do you check if a user belongs to an ad group?

You can check group membership with the Active Directory Users and Computers (ADUC) console snap-in by finding the user or group of interest and drilling down into the object's properties and clicking the “Members” or “Member Of” tab.

How do I get a list of users from ad group?

Use Get-ADGroupMember cmdlet to List Members of an Active Directory Group. The PowerShell Get-ADGroupMember cmdlet is used to list the members of an Active Directory group. You can just type the cmdlet in a PowerShell window and you'll be prompted to enter the name of the group you want to use.

Is there a way to check ad group membership for a computer?

You can check active directory group membership using the command line net user or dsget or using the Get-AdGroupMember PowerShell cmdlet to check ad group membership. Active Directory groups are a great way to manage and grant access permissions to users like access to specific servers, and computers.

How to check Active Directory group membership through command line?

Right-click on the domain root and select Find; Enter a username and click Find Now; Open the user properties and go to the Member of tab; This tab lists the groups the selected user is a member of. You can also check Active Directory group membership through command-line. Run the command: net user USERNAME /domain.

How to check if the current user is part of Ad Group?

Create a new class in your .NET Core web application and have a method to check if the current user is a part of AD Group or not. In my example, I have created a class with the name “Security”. In your Controller, you can call this method to check the user and then, based on the output, you can extend the functionality. }.

How do I See which groups a particular user belongs to?

To See Which Groups a Particular User Belongs to: Open the command prompt by navigating to Start → Run (or pressing Win + R) and entering "cmd". Type the following command in the command line, specifying the user account you want to find group membership for:

How do I see all users in Active Directory?

The easiest and most clear way to get a list of user groups in AD is to use the graphical snap-in Active Directory Users & Computers (ADUC). This tab lists the groups the selected user is a member of. You can also check Active Directory group membership through the command-line.


2 Answers

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.

like image 58
Robin Wilson Avatar answered Oct 20 '22 00:10

Robin Wilson


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 
        // ...
    }
    
like image 39
Serg.ID Avatar answered Oct 20 '22 01:10

Serg.ID