Saturday, 7 May 2016

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



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