In my application I have the following method which I pass the AD Username to it (example: Domain1\User1) and try to find the groups that user belongs to in Active Directory.
public ActionResult Login(string userName)
{
PrincipalContext up = new PrincipalContext(ContextType.Domain);
UserPrincipal users = UserPrincipal.FindByIdentity(up,IdentityType.SamAccountName, userName);
PrincipalSearchResult<Principal> groups = users.GetGroups();
IEnumerable<string> userGroupList = groups.Select(p =>p.SamAccountName);
return userGroupList ;
}
The code works perfectly, However I am guessing this code will failto work in an environment where there are multiple domains. For example: 1) User try to login with (Domain1\User1) and it will go through, 2) User try to login with (Domain2\User2) the app will try to look for User2 in Domain1, and becasue there is no such user in Domain1 it will fail.
Is this true? if yes, how can I resolve this issue so it will works with multiple domain?
I needed to pass the Domain name as the second parameter when trying to instantiate new PrincipalContext object. By doing this I was able to retrieve user groups with multiple domains. So the code will be something like this :
PrincipalContext up = new PrincipalContext(ContextType.Domain,"DomainName");