Cant find users or groups with System.DirectoryServices.AccountManagement - c#

I'm trying to integrate a system with Active Directory using the System.DirectoryServices.AccountManagement stuff. Our IT people have setup an AD box and my dev box is not part of this (or any) domain.
So far, I have 3 lines of code as a test:
var pc = new PrincipalContext(ContextType.Domain, "machine", "CN=Administrator,CN=Users,DC=domain,DC=com", "Password");
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "Administrator");
var gp = GroupPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "Admins");
Creating the PrincipalContext works as listed above, but if I try to use the domain name instead of the server name then I get an error : The server could not be contacted. So, I left this on the machine name.
When getting the user or group, I get an error : A local error has occurred.
For the user, I also tried this with the same result:
var user = UserPrincipal.FindByIdentity(pc, IdentityType.DistinguishedName, "cn=Administrator,ou=users,dc=domain,dc=com");
So, overall, I'm confused :(
Does anyone have any suggestions?
As a side note, I'd like to kick the programmer who thought that 'a local error has occurred' would be a useful error message!
Cheers
PS: I can use the SysInternals AD Explorer just fine from my machine and I can see the dn's I'm trying to use.
PPS: If I use machine.domain.com for the name when creating the PrincipalContext, it also fails to connect.

So this is one of those things that makes perfect sense AFTER you hack through to the solution. The problem was the Context was trying to use a Negotiated security context which is not configured. When I used SimpleBind it works just fine:
var pc = new PrincipalContext(ContextType.Domain, "machine", "DC=domain,DC=com", ContextOptions.SimpleBind, "CN=Administrator,CN=Users,DC=domain,DC=com", "Password");
Cheers
PS: A more useful error message would have saved me a days head scratching!

To do the search using the credentials of the current user, specify the domain as such:
new PrincipalContext(ContextType.Domain, "xyz.mycorp.com:3268", "DC=mycorp,DC=com");
From
When do I need a Domain Name and a Domain Container to create a PrincipalContext?

Related

Active Directory: How to determine whether account is service account?

Question: Is it possible to determine whether an account is a service account in Active Directory using C# LDAP? If yes, how?
Context: I have a program that is retrieving all objects of schema class type USER, GROUP, COMPUTER, FOREIGN SECURITY PRINCIPAL, and CONTACT. Currently, a service account is identified by string parsing the canonical name for 'service account'. I do not like this solution because string parsing is dependent on a folder location in the hierarchy that literally says 'service account'. It seems possible that a service account could be created and then placed in a folder path that does not include the string 'service account'. Unfortunately, I cannot test this because I am not an AD admin.
I have browsed around online without any luck so I am not sure if it is even possible.
Update:
Per Microsoft, it appears that the service account is contained in objectClass msDS-ManagedServiceAccount. However, when I set the DirectoryEntry filter to msDS-ManagedServiceAccount, no results are returned.
directoryEntry = new DirectoryEntry(strActiveDirectoryHost, null, null, AuthenticationTypes.Secure);
string strDsFilter = "(objectClass=msDS-ManagedServiceAccount)";
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry)
{
Filter = strDsFilter,
SearchScope = SearchScope.Subtree,
PageSize = intActiveDirectoryPageSize,
};
return searchResultCollection = directorySearcher.FindAll();
I have testing your code, and it does in fact return results in my environment. A few things to note:
Be sure that strActiveDirectoryHost is formatted correctly. The format should be LDAP://DC=contoso,DC=com
Check that you are searching from the root (or high enough to find the accounts you are looking for). MSAs are under the Managed Service Accounts container under the domain NC (i.e. LDAP://CN=Managed Service Accounts,DC=contoso,DC=com)
In my tests, I call new DirectoryEntry() with only the path. Not sure if passing AuthenticationTypes.Secure is causing an issue for you
The objectClass you have is correct.
So I am working on this to get the MSA as well as create them. I am able to get the MSA using the System.DirectoryServices.AccountManagement namespace, still working on creating it (unsure if this is really possible)
But for finding the accounts which are MSAs you can use the below code
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sDefaultOU, ContextOptions.SimpleBind, sServiceUser, sServicePassword);
GroupPrincipal currentGroup = GroupPrincipal.FindByIdentity(oPrincipalContext, "YourGroupName");
foreach (Principal a_principal in currentGroup.GetMembers())
{
if (a_principal.StructuralObjectClass == "msDS-ManagedServiceAccount")
{
Console.Write(a_principal.SamAccountName); //To get the name
ComputerPrincipal oComputerPrincipal = ComputerPrincipal.FindByIdentity(oPrincipalContext, a_principal.Name); //creating a computerprincipal to get more details about the MSA
}
}
You can use the above logic and create a Principal for the user account and get the structural object class for that account to find out if it is MSA.
Something like this:
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
if (oUserPrincipal.StructuralObjectClass == "msDS-ManagedServiceAccount")
{
Console.Write(oUserPrincipal.SamAccountName); //To get the samaccountname
}

How can I get a UserPrincipal for a user in a different domain?

The following code works great for users in my domain (e.g., "TESTER" instead of "DEVELOPER"), but I can't figure out how to search higher than the current domain. I tried variation combinations of searches with the PrincipalSearcher class, but I'm not sure how to pass in a search by email address or username to look for other domains within my organization even though they're all in a single forest.
var name = "DEVELOPER\\JULIANI99";
var p = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), name);
FindByIdentity doesn't work well for searching a forest.
I tried something like this:
var d = new PrincipalContext(ContextType.Domain, "domain.com:3268", "DC=com");
var p = UserPrincipal.FindByIdentity(d, IdentityType.SamAccountName, username);
But I keep getting an error saying a referral was returned. It might be different for you. The "3268" port tells it to use the global catalog (forest-wide search). The root (which I have as "DC=com") has to be the common across all the domains in your forest. So if all your domains are sub-domains of "domain.com", then you could put "DC=domain,DC=com". But if you have "domain.com" and "otherdomain.com" part of the same AD forest, then that wouldn't work.
FindByIdentity also won't work for searching by email address, so you may just be better off using PrincipalSearcher.
If you get the same referral error I got, you can tell it to follow the referral:
PrincipalSearcher srch = new PrincipalSearcher(User);
((DirectorySearcher) srch.GetUnderlyingSearcher()).ReferralChasing = ReferralChasingOption.All;

How can I access Active Directory data without exposing the password

I am just learning to access my Active Directory and need to figure out if it is possible to access the information without having the user account password in the code. This code works:
DirectoryEntry SharePointUpdate = new DirectoryEntry("LDAP://" + "comm2k8-dc3", "juser01", "password", AuthenticationTypes.Secure);
When I try this code:
String strPath = "LDAP:// DC=MYOrganization"
DirectoryEntry SharePointUpdate = new DirectoryEntry(strPath);
I get this error
"A referral was returned from the server.\r\n
Am I missing something??
I do not want to have the user name and password in the code. Is there anyway I can do this?
Is this code running in the context of either a domain service account or Network Service/Local System on a domain joined machine? If so, you can use that security context to access AD.
Your LDAP://DC=MYOrganization looks potentially strange. Is your domain really a single label domain called "MyOrganization", or does it have a legal FQDN? If it's called MyOrganization.net, for example, you would connect to LDAP://DC=MyOrganization,DC=net.

Unable to extract information

I'm trying to query a domain to determine if:
User is a valid user (and has the correct password)
User is enabled
User belongs to group x
My development machine does not belong to this domain.
I want to specify the username and password via my application
I'm using the System.DirectoryServices.AccountManagement namespace as this seems to be the most efficient way doing this, however I've struggling to get even the most basic of information out of my domain controller.
I can explore LDAP via another tool.
First test is to collect user information, the code below returns null on user.
The user however is valid.
What am I doing wrong?
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "server","CN=Users,DC=doom,DC=home", "ldapuser","password");
// get user contect
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.Name, username);
//is user locked?
var locked = user.Enabled;
Update:
Having defined the bind method as below, I now receive error
"Information about the domain could not be retrieved (1355)."
var ctx = new PrincipalContext(ContextType.Domain, "server", "DC=doom,DC=home", ContextOptions.SimpleBind, "ldapuser", "password");
Sorted.
This answer resolves the two issues I came across when attempting to connect to a domain controller that I am not a member of.
This article get me the final answer:
http://elegantcode.com/2009/03/21/one-scenario-where-the-systemdirectoryservices-accountmanagement-api-falls-down/
you need to define the Bind in the context (i.e. ContextOptions.SimpleBind)
You must set up the domain server in your Network adaptors DNS settings as the first DNS server to use.
I can now connect to my AD and collect data.

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')!
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.
I had the same problem, I solved it by supplying the domain name when creating the PrincipalContext:
var domain = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);
var user = UserPrincipal.FindByIdentity(domain, Environment.UserName);
0x80005000 = E_ADS_BAD_PATHNAME so you supply an invalid adspath somewhere, maybe you must add LDAP:// prefix or opposit are doing this twice? Set a breakpoint and inspect value...
EDIT:
AdsPath should be a value like "LDAP://CN=Administator,CN=Users,DC=contoso,DC=com", you seem to have a misformed path.

Categories

Resources