Sunday, March 3, 2019

c# - Active Directory, enumerating user's groups, COM exception

Answer


Answer




while enumerating current user's groups through AD .NET API I sometimes get



COMException: Unknown error (0x80005000)



Here's my code :



        var userName = Environment.UserName;

var context = new PrincipalContext(ContextType.Domain);
var user = UserPrincipal.FindByIdentity(context, userName);

foreach (var userGroup in user.GetGroups())
{
Console.WriteLine(userGroup.Name);

}


What's the problem? I thought every user can retrieve list of HIS groups?It seems to be strange behavior, sometimes It can be reproduced like this : when running on 'userA' PC, It crashes, but it is enumerating OTHER 'userB' groups successfully (under 'userA')!


Answer



Try using



var context = new PrincipalContext(ContextType.Domain, "yourcompany.com", "DC=yourcompany,DC=com", ContextOptions.Negotiate);



With the ContextOption set to Negotioate the client is authenticated by using either Kerberos or NTLM so even if the user name and password are not provided the account management API binds to the object by using the security context of the calling thread.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...