如何在 .NET Core 2.0 中使用 PrincipalContext

How to use PrincipalContext in .NET Core 2.0

我在 .NET Core 2.0 中创建了一个 Web 应用程序,我想在其中使用来自命名空间 System.DirectoryServices.AccountManagement.

PrincipalContext

我想像这样在 Active Directory 中再次验证用户:

private static ClaimsIdentity ValidateUser(string userName, string password)
        {
            var domain = GetDomainByLogin(userName);

            using (var pc = new PrincipalContext(ContextType.Domain, domain, null, ContextOptions.Negotiate))
            {
                if (!pc.ValidateCredentials(userName, password)) return null;

                var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, userName);
                if (user == null)
                {
                    throw new Exception(UserNotFound);
                }

                var id = new ClaimsIdentity();

                id.AddClaim(new Claim(JwtClaimTypes.Subject, userName));
                id.AddClaim(new Claim(JwtClaimTypes.Name, userName));

                var groups = user.GetGroups();
                var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Name));

                id.AddClaims(roles);

                return id;
            }
        }

如何在 .NET Core 2.0 中使用 PrincipalContext (System.DirectoryServices.AccountManagement)?

.NET Core 2.0.

有可能获得 System.DirectoryServices.AccountManagement 的预览版

来自 myget. It is possible get via Nuget package via this feed。 对此的扩展讨论是 here.

更新: 最新的工作预览是 here