Using UserPrincipal.FindByIdentity and PrincipalContext with nested OU

XXX picture XXX · Sep 27, 2012 · Viewed 16.8k times · Source

Here is what I am trying to achieve: I have a nested OU structure that is about 5 levels deep.

OU=Portal,OU=Dev,OU=Apps,OU=Grps,OU=Admin,DC=test,DC=com

I am trying to find out if the user has permissions/exists at OU=Portal.

Here's a snippet of what I currently have:

PrincipalContext domain = new PrincipalContext(
    ContextType.Domain,
    "test.com",
    "OU=Portal,OU=Dev,OU=Apps,OU=Grps,OU=Admin,DC=test,DC=com");

UserPrincipal user = UserPrincipal.FindByIdentity(domain, myusername);
PrincipalSearchResult<Principal> group = user.GetAuthorizationGroups();

For some unknown reason, the value user generated from the above code is always null. However, if I were to drop all the OU as follows:

PrincipalContext domain = new PrincipalContext(
    ContextType.Domain,
    "test.com",
    "DC=test,DC=com");

UserPrincipal user = UserPrincipal.FindByIdentity(domain, myusername);
PrincipalSearchResult<Principal> group = user.GetAuthorizationGroups();

this would work just fine and return me the correct user. I am simply trying to reduce the number of results as opposed to getting everything from AD.

Is there anything that I am doing wrong? I've Googled for hours and tested various combinations without much luck.

Answer

TGlatzer picture TGlatzer · Sep 27, 2012

Well, if

UserPrincipal.FindByIdentity(context, identityType, username) == null

then the user has not been found, which in your case probably is, because the user isn't defined in the OU= you are setting as container in your Context.