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
After some more googling I found way it works for me
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); } }
Add Singleton to builder in Program.cs
builder.Services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
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();
}
}