.NET Core 6 Windows 身份验证和基于 Active Directory 组的权限

Ser*_*que 5 asp.net-mvc active-directory windows-authentication .net-core asp.net-core-6.0

如何从 dotnet core 6 中公司的 Active Directory (WinServer) 获取用户数据(用户名和姓氏以及用户组)?

我安装了 Identity 包,但该应用程序需要与 Windows Auth 和 Active Directory 组一起使用以获得权限。

如何

Ser*_*que 13

经过更多谷歌搜索后,我找到了适合我的方法

  1. 创建一个新类来扩展 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);  
        }  
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将 Singleton 添加到 Program.cs 中的构建器

    builder.Services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
    
    Run Code Online (Sandbox Code Playgroud)
  3. 在控制器中使用 [Authorize(Roles = "YourGroupName")]

对于单个链接:

[Authorize(Roles = "YourGroupName")]
public IActionResult Privacy()
{
   return View();
}
Run Code Online (Sandbox Code Playgroud)

对于整个控制器:

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

指南来自: https://www.c-sharpcorner.com/article/authorization-using-windows-active-directory-groups-in-net-core-2-razor-pages/