Can not retrieve Active Directory user in C# - c#

I built a test Active Directory server in Window 2008 and I also run the DNS server on it. On my client machine which runs the C# application, I can authenticate the user against the Active directory server using the function below:
public static UserPrincipal GetUserPrincipal(string usrName,string pswd,string domainName)
{
UserPrincipal usr;
PrincipalContext ad;
// Enter Active Directory settings
ad = new PrincipalContext(ContextType.Domain, domainName,usrName,pswd);
//search user
usr = new UserPrincipal(ad);
usr.SamAccountName = usrName;
PrincipalSearcher search = new PrincipalSearcher(usr);
usr = (UserPrincipal)search.FindOne();
search.Dispose();
return usr;
}
In a separate logic I tried to retrieve a user back from the server using a user name. I used the functions below:
public static DirectoryEntry CreateDirectoryEntry()
{
// create AD connection
DirectoryEntry de = new DirectoryEntry("LDAP://CN=Users,DC=rootforest,DC=com","LDAP","password");
de.AuthenticationType = AuthenticationTypes.Secure;
return de;
}
public static ResultPropertyCollection GetUserProperty(string domainName, string usrName)
{
DirectoryEntry de = CreateDirectoryEntry();
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(SamAccountName=" + usrName + ")";
SearchResult results = deSearch.FindOne();
return null;
}
However, I got no response back from the LDAP server at all, not even an exception. Am I missing certain settings on LDAP server, any of you able to see a flaw in my code (pls don't mind the hard code values, I was testing with this code).
As part of my troubleshooting, I confirmed that I can ping to the rootforest.com from the client machine. I confirmed the user with property samaccountname "LDAP" exists. My path seems to be right because when I go onto the LDAP server and type :
dsquery user -name LDAP*
I got the following:
CN=LDAP L. LDAP,CN=Users,DC=rootforest,DC=com
Any help would be greatly appreciated, I've spent most of my day troubleshooting and researching this little bugger and I think it could be something small which I overlooked.

I don't understand why you're using the new PrincipalContext / UserPrincipal stuff in your first example, but fall back to the hard to use DirectoryEntry stuff in your second example.... doesn't really make sense... also: your second function GetUserProperty seems to return null always - typo or not??
Since you're on already using the System.DirectoryServices.AccountManagement (S.DS.AM) namespace - use it for your second task, too! Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
public static ????? GetUserProperty(string domainName, string usrName)
{
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, usrName);
if(user != null)
{
// return what you need to return from your user principal here
}
else
{
return null;
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD:

I think your code have a few problems:
Why do you return null in your GetUserProperty() function? You should return results instead.
The attribute you are using in your search filter is misspelled. Use sSAMAccountName instead. Furthermore extend your query to search only for user accounts. Here is an example: (&(objectCategory=person)(objectClass=user)(sAMAccountName=usrName))
You could also use the UserPrincipal class to search for an identity in Active Directory. The UserPrincipal class provides a static method called FindByIdentity() to search for a user identity.
Hope, this helps.

Related

WindowsIdentity: Exception: System.Security.SecurityException: The user name or password is incorrect

On Windows Server 2012 R2 we want to get the Security Groups of an user from the Active Directory by C#-code. The application is an ASP.NET MVC5-project and is hosted by an IIS.
At first, we query the user account from the Active Directory by UserPrincipal.FindByIdentity(...). That works fine. At next, we use the WindowsIdentity class to query the Security Groups from the active directory. We use the class WindowsIdentity because the response is very fast.
Here is the code:
var lDomain = "MyDomain";
var lSamAccountName = "Simon";
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, lDomain))
{
// Get User Account from Active Directory
using (UserPrincipal lUserPrincipal = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, lSamAccountName))
{
var lUpn = lUserPrincipal.UserPrincipalName; // get UPN
// get Security Groups of the user
using (WindowsIdentity lWindowsIdentity = new WindowsIdentity(lUpn)) // Exception: System.Security.SecurityException: The user name or password is incorrect
{
var lGroups = lWindowsIdentity.Groups;
}
}
}
The problem: When instanciating the WindowsIdentity class (and passing the UPN) then an exception occurs:
“Upn: 'simon#MyDomain' Exception: System.Security.SecurityException: The user name or password is incorrect.
at System.Security.Principal.WindowsIdentity.KerbS4ULogon(String upn, SafeAccessTokenHandle& safeTokenHandle)
at System.Security.Principal.WindowsIdentity..ctor(String sUserPrincipalName, String type)
at System.Security.Principal.WindowsIdentity..ctor(String sUserPrincipalName)
at ...
This is curious because the query with UserPrincipal.FindByIdentity(...) was successful. Some accounts are working. Some accounts are not working. I cannot find a difference between the working und not working accounts.
Question: Who knows what I am doing wrong?
Additional Notes:
The Applicationpool Identity is: LocalSystem
In the Web.config, there is the following entry: <identity impersonate="false" />
When I query the groups by the following alternative, then no exception occurs and the result is satisfying. That´s curious:
var lResult = new List<SecurityIdentifier>();
DirectorySearcher lDirectorySearcher = new DirectorySearcher();
lDirectorySearcher.Filter = string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)(distinguishedName={0}))", lUserPrincipal.DistinguishedName); // for the object lUserPrincipal, look # code above
lDirectorySearcher.SearchScope = SearchScope.Subtree;
SearchResult lSearchResult = lDirectorySearcher.FindOne();
DirectoryEntry lDirectoryEntry = lSearchResult.GetDirectoryEntry();
lDirectoryEntry.RefreshCache(new string[] { "tokenGroups" });
// get groups
for (int i = 0; i < lDirectoryEntry.Properties["tokenGroups"].Count; i++)
{
SecurityIdentifier lSid = new SecurityIdentifier((byte[])lDirectoryEntry.Properties["tokenGroups"][i], 0);
lResult.Add(lSid);
// Translate into NTAccount to get Domain and SAMAccountname etc...
[...]
}
I really do not know if this helps, but somewhere I found this:
If IIS is set to allow anonymous access you can use the userPrincipleName format (username#domain).
If anonymouse access is NOT enabled in IIS you need to use the username in the form domain\username.
Seems weird though that for some accounts the UPN works and for others it does not..
Resolution 1:
Use ADSI Edit (via MMC.exe) to manually populate the userPrincipalName attribute of the desired Windows Service Account.
The format of a userPrincipalName is
<username>#<fully_qualified_domain_name>
For example, for the example log lines above, the expected UPN value should be
goodadmin#example.com
Allow a few minutes for Active Directory replication to complete before attempting to use the service account credentials.
Resolution 2:
Ensure the Active Directory Service Account information has the necessary permissions on the local BEMS host as Local Administrator and Logon As A Service.
Ensure the Active Directory Service Account information entered is actually valid. For example, ensure the password is entered correctly and that the account is not locked out in Active Directory.
Ensure the Active Directory Service Account information has the necessary Active Directory Group Permissions.
RTCUniversalReadOnlyAdmins
Here you can find how to get groups base on the UserPrincipal
How to create WindowsIdentity/WindowsPrincipal from username in DOMAIN\user format
// find all groups the user is member of (the check is recursive).
// Guid != null check is intended to remove all built-in objects that are not really AD gorups.
// the Sid.Translate method gets the DOMAIN\Group name format.
var userIsMemberOf = p.GetAuthorizationGroups().Where(o => o.Guid != null).Select(o => o.Sid.Translate(typeof(NTAccount)).ToString());
// use a HashSet to find the group the user is member of.
var groups = new HashSet<string>(userIsMemberOf), StringComparer.OrdinalIgnoreCase);
groups.IntersectWith(groupNames);

Connect to Active Directory via LDAP

I want to connect to our local Active Directory with C#.
I've found this good documentation.
But I really don't get how to connect via LDAP.
Can somebody of you explain how to use the asked parameters?
Sample Code:
static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = new DirectoryEntry("rizzo.leeds-art.ac.uk");
ldapConnection.Path = "LDAP://OU=staffusers,DC=leeds-art,DC=ac,DC=uk";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
I just have the Hostname and the IP Address of our Active Directory Server. What does DC=xxx,DC=xx and so on mean?
DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com
You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).
Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
And you're done.
You can also specify a user and a password used to connect:
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");
Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.
The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";
This would match the following AD hierarchy:
com
example
Users
All Users
Specific Users
Simply write the hierarchy from deepest to highest.
Now you can do plenty of things
For example search a user by account name and get the user's surname:
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
PageSize = int.MaxValue,
Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};
searcher.PropertiesToLoad.Add("sn");
var result = searcher.FindOne();
if (result == null) {
return; // Or whatever you need to do in this case
}
string surname;
if (result.Properties.Contains("sn")) {
surname = result.Properties["sn"][0].ToString();
}
ldapConnection is the server adres: ldap.example.com
Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.
OU=Your_OU,OU=other_ou,dc=example,dc=com
You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain
Now i miss a parameter to authenticate, this works the same as the path for the username
CN=username,OU=users,DC=example,DC=com
Introduction to LDAP
If your email address is 'myname#mydomain.com', try changing the createDirectoryEntry() as below.
XYZ is an optional parameter if it exists in mydomain directory
static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
This will basically check for com -> mydomain -> XYZ -> Users -> abcd
The main function looks as below:
try
{
username = "Firstname LastName"
DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(cn=" + username + ")";
....

Check Password Reset on Active Directory Server

I need to reset windows password of any user through my .Net application. I am using the user's username to get its Directory Entry from AD server. I got these two different methods for changing password :
entry.Invoke("ChangePassword", oldPass, newPass);
&
entry.Invoke("SetPassword", "pass#123");
But I am getting the following error when am trying these methods on live AD server :
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
I have 2 AD servers. One of them is live and another is for testing purpose. I just want to check if my code is working or not. Since, access is denied on live server I can not change and check later my own password through code.
And if I am using the test AD server to change password, I don't know how to check whether the pasword is changed or not.
Kindly give any suggestions to check if my code is working properly or not.
Thanks in advance.
I think you're not getting a proper context setup before you call the invoke. Here's what I use for something similar. You'll need to set your own variables:
I'm using System.DirectoryServices.AccountManagement to get the functions.
//Domain related info
string _DCToUse = "myserver.domain.local";
string _ADConDomain = "DC=domain,DC=local";
string _AdDomain = "domain";
string _ADAdminUser = "administrator";
string _ADAdminPass = "password";
//User specific
string _UserName = "jsmith";
string _CurrentPass = "oldPass";
string _NewPass = "newPass";
PrincipalContext principalContext =
new PrincipalContext(ContextType.Domain, _DCToUse,
_ADConDomain, _ADDomain+#"\"+_ADAdminUser, _ADAdminPass);
UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, _UserName);
if (user == null)
{
string ADErrorMsg = "Couldn't find user, check your spelling.";
return Changed;
}
user.ChangePassword(oldPass, newPass);
user.Save();

Check if Active Directory Account is Locked out (WPF C#)

Hello everyone (this is my first post)
I have some simple AD code that i pulled from Codeplex http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C) and i am able to get all of our end user's information from said code. Now, I have been searching and searching and have found some interesting code snippets from here, and around the web regarding "Is the user locked out?"
I would like to use my code that I have been using for 2 years now, and just add a little bit more to it to add in the locked out part... I would be happy if there was a text box that gave me my info, or a check box, or something that just said "user locked" and then I would notify my Exchange team and have the user unlocked...
The code that I have is the following:
string eid = this.tbEID.Text;
string user = this.tbUserName.Text.ToString();
string path = "PP://dc=ds,dc=SorryCantTellYou,dc=com";
DirectoryEntry de = new DirectoryEntry(path);
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectCategory=person)(sAMAccountName=" + eid + "))";
SearchResultCollection src = ds.FindAll();
//AD results
if (src.Count > 0)
{
if (src[0].Properties.Contains("displayName"))
{
this.tbUserName.Text = src[0].Properties["displayName"][0].ToString();
}
}
So, if I can figure out how to use the same directory entry, and searcher to show me the account lockout status that would be amazing.. please assist
If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
Managing Directory Security Principals in the .NET Framework 3.5
MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SamAccountName");
if(user != null)
{
string displayName = user.DisplayName;
if(user.IsAccountLockedOut())
{
// do something here....
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!

How to find an user on a LDAP server

When trying to find an User on a LDAP Server, I get the following error "Unknown error (0x8000500c)"
This is the code I'm using:
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "gandalf.intrafg");
UserPrincipal p = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, "Consultor1");
Indidentally, the following piece of code seems to work (no exception is generated), but the samAccountName comes through as a byte array. Anybody knows why?
DirectoryEntry entry = new DirectoryEntry("LDAP://gandalf.intrafg");
DirectorySearcher searcher = new DirectorySearcher(entry);
//searcher.PropertiesToLoad.Add("givenName");
//searcher.PropertiesToLoad.Add("sn");
searcher.PropertiesToLoad.Add("samAccountName");
searcher.Filter = "(&(objectCategory=person)(samAccountName=Consultor1))";
SearchResult result = searcher.FindOne();
Your second code block works just fine, I however did not pass the domain name in the DirectoryEntry initializer.
Directory entry = new DirectoryEntry();
//other code
result.Properties["samAccountName"][0].ToString();
The code you have should be fine - it works for me, no problem at all.
However: you're not telling us what you fill in for domain_name here:
PrincipalContext domainContext = new PrincipalContext(ContextType.Domain, "domain_name");
or userId here:
UserPrincipal p = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, UserId);
The domain_name must be in the "old" NetBIOS style, e.g. FABRIKAM - no DNS-style like fabrikam.com or AD-style like dc=fabrikom,dc=com or even a full LDAP path.
The userId must be a valid SAM account name, e.g. max. of 20 chars, letters and numerics only (except for a few valid special chars).
Are you complying with these requirements??

Categories