Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PrincipalContext in .NET Core 2.0

I have created a web application in .NET Core 2.0 where I would like to use a PrincipalContext from namespace System.DirectoryServices.AccountManagement.

I want to validate user agains Active Directory like this:

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;
            }
        }

How can I use the PrincipalContext (System.DirectoryServices.AccountManagement) in .NET Core 2.0?

like image 720
Jenan Avatar asked Aug 22 '17 11:08

Jenan


1 Answers

It is possible get the preview version of System.DirectoryServices.AccountManagement for .NET Core 2.0.

From myget. It is possible get via Nuget package via this feed. The extended discussion about that is here.

Update: Latest working preview is here.

like image 137
Jenan Avatar answered Sep 18 '22 17:09

Jenan