I have problems with UserPrincipal.GetGroups() and GetAuthorizationGroups() method. Sometimes it works, sometimes not. The problem is that in the unsuccesfull cases the method contacts bad AD domain. My dev PC is connected to company
domain and I want to get groups for user in other, test domain, where the PC isn’t in.
My code:
var ctx = new PrincipalContext(ContextType.Domain, "test.int", "user1@test.int", "pwd123");
ctx.ValidateCredentials("user1@test.int", "pwd123"); //returns always true
var adUser = UserPrincipal.FindByIdentity(ctx, IdentityType.UserPrincipalName, "user1@test.int");
var groups = adUser.GetAuthorizationGroups(); //sometimes exception...
It raises ActiveDirectoryServerDownException – RPC server is unavailable. It is because
in this case the method call wanted to communicate with a company DC server, not with the
test domain!
My dev environment:
– server: DC+DNS server W2003, single-DC domain “test.int”, the DNS has “company.int” DNS as its forwarders, but same problem, if the forwarders are disabled.
- my PC: connected to “company.int” domain, uses only DNS server of the test DC, same LAN network as the server
I didn’t found way, how to force to connect always to the test DC server.
GetAuthroizationGroups()won’t work if you are from an untrusted domain. It is because underlying it’s calling Authz.dll. I just tried it in my two test domains without trust. It fails and throws me exception with the following callstackI disassemble
System.DirectoryServices.AccountManagement.dll. Here is the code. I think it’s failing atAuthzInitializeContextFromSid.As you can see above, the
NetCred credentialsis passed in and never used. It’s calling the AuthzInitializeContextFromSid right away. If you check MSDN, they have the following disclaimer.I cannot explain why it sometimes works on your environment and sometimes doesn’t. It’s always not working in my environment. I guess one possible reason is that you visited the untrusted domain controller from your workstation and pressed “stored credentials”. This will store the network credentials and whenever you contact that particular machine, Windows will automatically uses the stored credentials for you. Another possible reason is that you are using the same password with the same username in those two domains.
To walkaround the problem, I simply use
GetGroups()on the users and then callingGetGroups()on all its groups. Repeat it until you reach the top level group. You may also like to check if it’s a security group. You may like to simply skip all the distribution groups. TheGetGroup()method returns you both security groups and distribution group.