.NET Core 6 Windows auth and Active Directory group based permissions
Asked Answered
F

2

5

How does one get user data (user name and surname, and user groups) from company's Active Directory (WinServer) in dotnet core 6?

I have Identity package installed, but the app needs to work with Windows Auth and Active Directory groups for permissions.

How

Fortyniner answered 12/3, 2022 at 10:22 Comment(2)
Have you read this?: Configure Windows Authentication in ASP.NET CoreOl
Thank you for your answer! Yes, but i failed. Could not get AD groups from WinServerFortyniner
F
13

After some more googling I found way it works for me

  1. Create a new class which would extend the IClaimsTransformation.

    public class ClaimsTransformer : IClaimsTransformation  
    {  
        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)  
        {  
            var wi = (WindowsIdentity)principal.Identity;  
            if (wi.Groups != null)  
            {  
                foreach (var group in wi.Groups) //-- Getting all the AD groups that user belongs to---  
                    {  
                        try  
                        {  
                            var claim = new Claim(wi.RoleClaimType, group.Value);  
                            wi.AddClaim(claim);                          
                        }  
                        catch (Exception ex)  
                        {  
                           throw ex;  
                        }  
                     }  
             }              
              return Task.FromResult(principal);  
        }  
    }
    
  2. Add Singleton to builder in Program.cs

    builder.Services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
    
  3. Use [Authorize(Roles = "YourGroupName")] in your controllers

For single link:

[Authorize(Roles = "YourGroupName")]
public IActionResult Privacy()
{
   return View();
}

For whole controller:

[Authorize(Roles = "YourGroupName")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
    
}

Guide from: https://www.c-sharpcorner.com/article/authorization-using-windows-active-directory-groups-in-net-core-2-razor-pages/

Fortyniner answered 14/5, 2022 at 14:14 Comment(2)
Yes, this is a good way. Note that hardcoding your group name is not a best practice. You can make it a constant at least, but that won't allow you to use different groups for lower environments versus production. What I do is this: -create a set of constants for the different roles (possibly only one if you only have one group per environment -put the allowable group(s) in appsettings -inject an appsettings class into the claims transformer -claims transformer has logic to map appsettings groups to constants and puts the constants in the claims -the Authorize tag references the constantsCockswain
Thank you for your comment. In production i made separate class with Static Details, where i put all my groups i need. Sadly my knowledge level is not enough for injecting, but when i learn this topic, ill return to your suggestionFortyniner
L
2

for connecting to AD

   using(  PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN")){}

put your group in "YourDomain"

for geting information from AD use this code

using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        foreach (var result in searcher.FindAll())
        {
            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
            Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
            Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
            Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
            Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
            Console.WriteLine();
        }
    }
}
Console.ReadLine();

by this code you will get All user information

if you want login or Edit User information from Active Directory i will send you the full code

Limicoline answered 7/5, 2022 at 8:1 Comment(1)
Thank you for your code! I do not need to edit user, just get user and user groups. And if i need to restrict access by active directory groups? I have, for example, user, supervisor and admin. I have Areas in my MVC app. Also, i am using Microsoft Identity for accounts for now, i need to save some additional info. There are some external libraries as Facebook, Twitter, etc, but no Active Directory.Fortyniner

© 2022 - 2024 — McMap. All rights reserved.