Search code examples
asp.net-mvc.net-coreactive-directorywindows-authenticationasp.net-core-6.0

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


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


Solution

  • 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/