I'm trying to update some AD accounts using C#. I have:
void UpdateADUser(string emailaddress)
{
try
{
DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(cn=" + emailaddress + ")";
search.PropertiesToLoad.Add("title");
SearchResult result = search.FindOne();
if (result != null)
{
DirectoryEntry entryToUpdate = result.GetDirectoryEntry();
Response.Write("Current title : " +
entryToUpdate.Properties["title"][0].ToString());
}
else Response.Write("User not found!");
}
catch (Exception e)
{
Response.Write("Exception caught:\n\n" + e.ToString());
}
}
static DirectoryEntry createDirectoryEntry()
{
DirectoryEntry ldapConnection = new DirectoryEntry("leasing-vm1.**********.com");
ldapConnection.Path = "LDAP://OU=leasing options,DC=leasing,DC=local";
ldapConnection.AuthenticationType = AuthenticationTypes.None;
ldapConnection.Username = "administrator";
ldapConnection.Password = "D**********s";
return ldapConnection;
}
I'm getting an error:
The specified domain either does not exist or could not be contacted.
Any help appreciated. One potential issue is that my development machine is not part of the domain concerned. Is that the problem?
Thanks
If current machine is not joined to domain, you have to specify the domain/DC to connect in the LDAP path.
e.g. LDAP://leasing.local/OU=leasing options,DC=leasing,DC=local
Related
I am trying to access Active Directory, which I can successfully do in Visual Studio using basically the same code as below. However, I'm getting an error with this line of code when using Unity: "DirectoryEntry ldapConnection = new DirectoryEntry("xxxxxxx");"
String username = "xxxxx xxxxxxx";
try
{
DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(cn=" + username + ")";
SearchResult result = search.FindOne();
if (result != null)
{
print("user found");
}
else
{
print("user not found");
}
}
catch (Exception e)
{
print("Exception caught:" + e.ToString());
}
}
static DirectoryEntry createDirectoryEntry()
{
DirectoryEntry ldapConnection = new DirectoryEntry("xxxxxxx");
ldapConnection.Path = "LDAP://OU=xxxxxx,DC=xxxxxx,DC=xxxxx,DC=xxxxx";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
The error is: "Invalid IL code in System.DirectoryServices.DirectoryEntry:.cctor (): method body is empty."
Any help on the reason for this or a possible solution would be greatly appreciated.
I need to authenticate LDAP user in c# with input username and password.
DirectoryEntry entry =
new DirectoryEntry("LDAP://" + ServerName + "/OU=managed users,OU=KK”, + LDAPDomain, AdminUsername, Adminpassword);
DirectorySearcher search = new DirectorySearcher(entry);
search.SearchScope = SearchScope.Subtree;
search.Filter = "(|(&(objectCategory=person)(objectClass=user)(name=" + inputUsername + ")))";
search.PropertiesToLoad.Add("cn");
var searchresult = search.FindAll();
And here I get the required record (could see the details)
However when I try to authenticate it using below code, it always said authentication failure
if (searchresult != null)
{
foreach (SearchResult sr in searchresult)
{
DirectoryEntry myuser = sr.GetDirectoryEntry();
myuser.Password = inputPassword;
try
{
object nativeObject = myuser.NativeObject;
if (nativeObject != null)
isValid = true;
}
catch(excecption ex)
{
isValid = false;
//Error message
}
}
}
It always result in catch block with error message
Logon failure: unknown user name or bad password. failure: unknown user name or bad password.
I'm sure that the given password is correct.
Please suggest.
As suggest by Saad,
I changed by code
public static bool IsAuthenticated()
{
var isValid = false;
string adServer = ConfigurationManager.AppSettings["Server"];
string adDomain = ConfigurationManager.AppSettings["Domain"];
string adminUsername = ConfigurationManager.AppSettings["AdminUsername"];
string adminpassword = ConfigurationManager.AppSettings["Password"];
string username = ConfigurationManager.AppSettings["Username"];
string selection = ConfigurationManager.AppSettings["Selection"];
string[] dc = adDomain.Split('.');
string dcAdDomain = string.Empty;
foreach (string item in dc)
{
if (dc[dc.Length - 1].Equals(item))
dcAdDomain = dcAdDomain + "DC=" + item;
else
dcAdDomain = dcAdDomain + "DC=" + item + ",";
}
string domainAndUsername = dcAdDomain + #"\" + adminUsername;
DirectoryEntry entry = new DirectoryEntry("LDAP://" + adServer, domainAndUsername, adminpassword);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
Console.WriteLine("And here is the result = " + result);
if (null == result)
{
isValid = false;
}
//Update the new path to the user in the directory.
var _path1 = result.Path;
var _filterAttribute = (string)result.Properties["cn"][0];
Console.WriteLine("And here is the _path1 = " + _path1);
Console.WriteLine("And here is the _filterAttribute = " + _filterAttribute);
isValid = true;
}
catch (Exception ex1)
{// your catch here
Console.WriteLine("Exception occurred " + ex1.Message + ex1.StackTrace);
}
return isValid;
}
Still it is giving error
Exception occurred Logon failure: unknown user name or bad passwor
d.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_NativeObject()
at Portal.LdapTest.Program.IsAuthenticated()
I think I am confused with which parameter to give where.
I have
LDAP server address something like 123.123.12.123
Domain Name like abc.com
Admin username and password and
Username and password which is needs be authenticated. (which is in OU=new users,OU=KK )
I am creating directory entry using servername, domain, admin username and password
How do I validate the username with given password?
This code works for me,try it and let me know (modify the filters and properties to suit your needs):
public bool IsAuthenticated(string domain, string username, string pwd){
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch(Exception e){// your catch here
}
}
public bool AuthenticateUser(string EmailAddress, string password,out string msg)
{
msg = string.Empty;
if (password == null || password == string.Empty || EmailAddress == null || EmailAddress == string.Empty)
{
msg = "Email and/or password can't be empty!";
return false;
}
try
{
ADUserInfo userInfo = GetUserAttributes(EmailAddress);
if (userInfo == null)
{
msg = "Error: Couldn't fetch user information!";
return false;
}
DirectoryEntry directoryEntry = new DirectoryEntry(LocalGCUri, userInfo.Upn, password);
directoryEntry.AuthenticationType = AuthenticationTypes.None;
string localFilter = string.Format(ADSearchFilter, EmailAddress);
DirectorySearcher localSearcher = new DirectorySearcher(directoryEntry);
localSearcher.PropertiesToLoad.Add("mail");
localSearcher.Filter = localFilter;
SearchResult result = localSearcher.FindOne();
if (result != null)
{
msg = "You have logged in successfully!";
return true;
}
else
{
msg = "Login failed, please try again.";
return false;
}
}catch (Exception ex)
{
//System.ArgumentException argEx = new System.ArgumentException("Logon failure: unknown user name or bad password");
//throw argEx;
msg = "Wrong Email and/or Password!";
return false;
}
}
C# code
> error--->>>Unknown name. (Exception from HRESULT: 0x80020006
> (DISP_E_UNKNOWNNAME))
and the code is this
using (DirectoryEntry entry = new DirectoryEntry("LDAP://admin-jyt69gl7t.hello/CN=Users,DC=hello"))
{
entry.Username = username;
entry.Password = strOldPassword;
DirectorySearcher searcher = new DirectorySearcher(entry);
try
{
searcher.FindOne();
entry.AuthenticationType = AuthenticationTypes.Secure;
entry.Invoke("ChangePassword", new object[] { strOldPassword, strNewPassword });
// oDE.Invoke("SetPassword", new object[] { strNewPassword });
entry.CommitChanges();
}
catch (Exception excep)
I am getting this exception
> Unknown name. (Exception from HRESULT: 0x80020006
> (DISP_E_UNKNOWNNAME))
Simply follow the code under
using System.DirectoryServices;
private DirectoryEntry GetUser(string UserName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;
deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserName + "))";
deSearch.SearchScope = SearchScope.Subtree;
SearchResult results = deSearch.FindOne();
if (!(results == null))
{
// **THIS IS THE MOST IMPORTANT LINE**
de = new DirectoryEntry(results.Path, "username", "password", AuthenticationTypes.Secure);
return de;
}
else
{
return null;
}
}
private DirectoryEntry GetDirectoryObject()
{
DirectoryEntry oDE;
oDE = new DirectoryEntry("LDAP://192.168.1.101", "username", "password", AuthenticationTypes.Secure);
return oDE;
}
public static bool ChangePassword(string UserName, string strOldPassword, string strNewPassword)
{
bool passwordChanged = false;
DirectoryEntry oDE = GetUser(UserName, strOldPassword);
if (oDE != null)
{
try
{
// Change the password.
oDE.Invoke("ChangePassword", new object[] { strOldPassword, strNewPassword });
passwordChanged = true;
}
catch (Exception ex)
{
Debug.WriteLine("Error changing password. Reason: " + ex.Message);
}
}
return passwordChanged;
}
This error says that you didn't find the user by your LDAP query. Check the code that finds the user, and run your query again.
The DISP_E_UNKNOWNNAME makes it appear that the active directory is responding to the attempt, but it can't locate the user based on the name supplied in the directory entry. Some things to try/verify:
Verify that your directory entry is populated with the proper information.
Verify that the username of your entry actually exists in the AD.
Verify that the OU the username belongs to is reflected in your query.
I've received this error in the past, and universally (for me) it revolved around a disconnect between the directory entry and the ultimate location of the user within the AD. OU differences can make or break the connection.
We have a website which can be used as intranet for Staffs and internet for outside people. All our staffs accounts are in Active Directory. So, when the internal staffs browse the URL (For eg. http://app.abc.com), they should be automatically signed in by using their AD accounts.
However, for external users, they have to use their username and password. I could do this part easily just by looking up the database and make authentication.
I would like to know how I could auto sign in the AD users into the website.
You would use the Windows authentication provider to use Windows authentication (which is the AD authentication).
http://msdn.microsoft.com/en-us/library/907hb5w9.aspx
However, what you're talking about is mixed-mode authentication... That's a bit more tricky. But it's covered here: http://msdn.microsoft.com/en-us/library/ms972958.aspx and here http://www.15seconds.com/issue/050203.htm
public bool Authenticate(string userName, string passwd)
{
//Domain .
string domain = "YOUR_DOMAIN_NAME";
string domainAndUsername = domain + #"\" + userName;
//Path of Active Directory Entry e.g. path="LDAP://DC=onecity,DC=corp,DC=fabrikam,DC=com";
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, passwd);
try
{
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + userName + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (string)result.Properties["cn"][0];
}
catch (Exception ex)
{
PageLogger.AddToLogError("AUTH_ERROR", ex);
return false;
}
return true;
}
private string GetGroups()
{
DirectorySearcher search = new DirectorySearcher(_path);
search.Filter = "(cn=" + _filterAttribute + ")";
search.PropertiesToLoad.Add("memberOf");
StringBuilder groupNames = new StringBuilder();
try
{
SearchResult result = search.FindOne();
int propertyCount = result.Properties["memberOf"].Count;
string dn;
int equalsIndex, commaIndex;
for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
{
dn = (string)result.Properties["memberOf"][propertyCounter];
equalsIndex = dn.IndexOf("=", 1);
commaIndex = dn.IndexOf(",", 1);
if (-1 == equalsIndex)
{
return null;
}
groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
groupNames.Append("|");
}
}
catch (Exception ex)
{
throw new Exception("Error obtaining group names. " + ex.Message);
}
return groupNames.ToString();
}
I know that this type of question has been asked before, but other methods are failing me right now.
As it stands our windows service polls AD, given an LDAP (i.e. LDAP://10.32.16.80) and a list of usergroups within that AD server to search for.
It retrieves all users within those given groups, recursively searching those groups for more groups as well.
Each user is then added to another applications authenticated users list.
This part of the application is running successfully. However, we're in need of each user's friendly domain name (i.e. the part of their login DOMAIN/username)
So if there is a user that is part of TEST domain, named Steve: TEST/steve is his login.
I'm able to find steve in the AD, however I also need "TEST" to be stored along with his AD information.
Again, I can find 'steve' fine by using a directory searcher and the LDAP IP I'm given, but given the LDAP IP, how can I find the friendly domain name?
When I try the following code I'm given an error when attempting to access the 'defaultNamingContext':
System.Runtime.InteropServices.COMException (0x8007202A): The authentication mechanism is unknown.
Here is the code:
private string SetCurrentDomain(string server)
{
string result = string.Empty;
try
{
logger.Debug("'SetCurrentDomain'; Instantiating rootDSE LDAP");
DirectoryEntry ldapRoot = new DirectoryEntry(server + "/rootDSE", username, password);
logger.Debug("'SetCurrentDomain'; Successfully instantiated rootDSE LDAP");
logger.Debug("Attempting to retrieve 'defaultNamingContext'...");
string domain = (string)ldapRoot.Properties["defaultNamingContext"][0]; //THIS IS WHERE I HIT THE COMEXCEPTION
logger.Debug("Retrieved 'defaultNamingContext': " + domain);
if (!domain.IsEmpty())
{
logger.Debug("'SetCurrentDomain'; Instantiating partitions/configuration LDAP entry");
DirectoryEntry parts = new DirectoryEntry(server + "/CN=Partitions,CN=Configuration," + domain, username, password);
logger.Debug("'SetCurrentDomain'; Successfully instantiated partitions/configuration LDAP entry");
foreach (DirectoryEntry part in parts.Children)
{
if (part.Properties["nCName"] != null && (string)part.Properties["nCName"][0] != null)
{
logger.Debug("'SetCurrentDomain'; Found property nCName");
if ((string)part.Properties["nCName"][0] == domain)
{
logger.Debug("'SetCurrentDomain'; nCName matched defaultnamingcontext");
result = (string)part.Properties["NetBIOSName"][0];
logger.Debug("'SetCurrentDomain'; Found NetBIOSName (friendly domain name): " + result);
break;
}
}
}
}
logger.Debug("finished setting current domain...");
}
catch (Exception ex)
{
logger.Error("error attempting to set domain:" + ex.ToString());
}
return result;
}
edit
I added this sample method in order to attempt a suggestion but am getting an exception: "Unspecified error" when I hit the "FindAll()" call on the searcher.
The string being passed in is: "CN=TEST USER,CN=Users,DC=tempe,DC=ktregression,DC=com"
private string GetUserDomain(string dn)
{
string domain = string.Empty;
string firstPart = dn.Substring(dn.IndexOf("DC="));
string secondPart = "CN=Partitions,CN=Configuration," + firstPart;
DirectoryEntry root = new DirectoryEntry(secondPart, textBox2.Text, textBox3.Text);
DirectorySearcher searcher = new DirectorySearcher(root);
searcher.SearchScope = SearchScope.Subtree;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.Filter = "(&(nCName=" + firstPart + ")(nETBIOSName=*))";
try
{
SearchResultCollection rs = searcher.FindAll();
if (rs != null)
{
domain = GetProperty(rs[0], "nETBIOSName");
}
}
catch (Exception ex)
{
}
return domain;
This article helped me much to understand how to work with the Active Directory.
Howto: (Almost) Everything In Active Directory via C#
From this point forward, if you require further assitance, please let me know with proper questions in comment, and I shall answer them for you to the best of my knowledge.
EDIT #1
You had better go with this example's filter instead. I have written some sample code to briefly show how to work with the System.DirectoryServices and System.DirectoryServices.ActiveDirectory namespaces. The System.DirectoryServices.ActiveDirectory namespace is used to retrieve information about the domains within your Forest.
private IEnumerable<DirectoryEntry> GetDomains() {
ICollection<string> domains = new List<string>();
// Querying the current Forest for the domains within.
foreach(Domain d in Forest.GetCurrentForest().Domains)
domains.Add(d.Name);
return domains;
}
private string GetDomainFullName(string friendlyName) {
DirectoryContext context = new DirectoryContext(DirectoryContextType.Domain, friendlyName);
Domain domain = Domain.GetDomain(context);
return domain.Name;
}
private IEnumerable<string> GetUserDomain(string userName) {
foreach(string d in GetDomains())
// From the domains obtained from the Forest, we search the domain subtree for the given userName.
using (DirectoryEntry domain = new DirectoryEntry(GetDomainFullName(d))) {
using (DirectorySearcher searcher = new DirectorySearcher()){
searcher.SearchRoot = domain;
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("sAMAccountName");
// The Filter is very important, so is its query string. The 'objectClass' parameter is mandatory.
// Once we specified the 'objectClass', we want to look for the user whose login
// login is userName.
searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", userName);
try {
SearchResultCollection results = searcher.FindAll();
// If the user cannot be found, then let's check next domain.
if (results == null || results.Count = 0)
continue;
// Here, we yield return for we want all of the domain which this userName is authenticated.
yield return domain.Path;
} finally {
searcher.Dispose();
domain.Dispose();
}
}
}
Here, I didn't test this code and might have some minor issue to fix. This sample is provided as-is for the sake of helping you. I hope this will help.
EDIT #2
I found out another way out:
You have first to look whether you can find the user account within your domain;
If found, then get the domain NetBIOS Name; and
concatenate it to a backslash (****) and the found login.
The example below uses a NUnit TestCase which you can test for yourself and see if it does what you are required to.
[TestCase("LDAP://fully.qualified.domain.name", "TestUser1")]
public void GetNetBiosName(string ldapUrl, string login)
string netBiosName = null;
string foundLogin = null;
using (DirectoryEntry root = new DirectoryEntry(ldapUrl))
Using (DirectorySearcher searcher = new DirectorySearcher(root) {
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("sAMAccountName");
searcher.Filter = string.Format("(&(objectClass=user)(sAMAccountName={0}))", login);
SearchResult result = null;
try {
result = searcher.FindOne();
if (result == null)
if (string.Equals(login, result.GetDirectoryEntry().Properties("sAMAccountName").Value))
foundLogin = result.GetDirectoryEntry().Properties("sAMAccountName").Value
} finally {
searcher.Dispose();
root.Dispose();
if (result != null) result = null;
}
}
if (!string.IsNullOrEmpty(foundLogin))
using (DirectoryEntry root = new DirectoryEntry(ldapUrl.Insert(7, "CN=Partitions,CN=Configuration,DC=").Replace(".", ",DC="))
Using DirectorySearcher searcher = new DirectorySearcher(root)
searcher.Filter = "nETBIOSName=*";
searcher.PropertiesToLoad.Add("cn");
SearchResultCollection results = null;
try {
results = searcher.FindAll();
if (results != null && results.Count > 0 && results[0] != null) {
ResultPropertyValueCollection values = results[0].Properties("cn");
netBiosName = rpvc[0].ToString();
} finally {
searcher.Dispose();
root.Dispose();
if (results != null) {
results.Dispose();
results = null;
}
}
}
Assert.AreEqual("FULLY\TESTUSER1", string.Concat(netBiosName, "\", foundLogin).ToUpperInvariant())
}
The source from which I inspired myself is:
Find the NetBios Name of a domain in AD
Since I could not find any example code I would like to share my own solution. This will search the parents of the DirectoryEntry object until it hits the domainDNS class.
using System.DirectoryServices;
public static class Methods
{
public static T ldap_get_value<T>(PropertyValueCollection property)
{
object value = null;
foreach (object tmpValue in property) value = tmpValue;
return (T)value;
}
public static string ldap_get_domainname(DirectoryEntry entry)
{
if (entry == null || entry.Parent == null) return null;
using (DirectoryEntry parent = entry.Parent)
{
if (ldap_get_value<string>(parent.Properties["objectClass"]) == "domainDNS")
return ldap_get_value<string>(parent.Properties["dc"]);
else
return ldap_get_domainname(parent);
}
}
}
Use it like this:
string[] _properties = new string[] { "objectClass", "distinguishedName", "samAccountName", "userPrincipalName", "displayName", "mail", "title", "company", "thumbnailPhoto", "useraccountcontrol" };
string account = "my-user-name";
// OR even better:
// string account = "my-user-name#DOMAIN.local";
using (DirectoryEntry ldap = new DirectoryEntry())
{
using (DirectorySearcher searcher = new DirectorySearcher(ldap))
{
searcher.PropertiesToLoad.AddRange(_properties);
if (account.Contains('#')) searcher.Filter = "(userPrincipalName=" + account + ")";
else searcher.Filter = "(samAccountName=" + account + ")";
var user = searcher.FindOne().GetDirectoryEntry();
Console.WriteLine("Name: " + Methods.ldap_get_value<string>(user.Properties["displayName"]));
Console.WriteLine("Domain: " + Methods.ldap_get_domainname(user));
Console.WriteLine("Login: " + Methods.ldap_get_domainname(user) + "\\" + Methods.ldap_get_value<string>(user.Properties["samAccountName"]));
}
}
I haven't got a forest to test it on but in theory this should cut it.
You can retrieve the name of the domain that the current user is on using the Environment.UserDomainName Property.
string domainName;
domainName = System.Environment.UserDomainName;
Maybe not entirely correct but...
DirectoryEntry dirEntry = new DirectoryEntry();
DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry);
dirSearcher.SearchScope = SearchScope.Subtree;
dirSearcher.Filter = string.Format("(&(objectClass=user)(|(cn={0})(sn={0}*)(givenName={0})(sAMAccountName={0}*)))", userName);
var searchResults = dirSearcher.FindAll();
foreach (SearchResult sr in searchResults)
{
var de = sr.GetDirectoryEntry();
string user = de.Properties["SAMAccountName"][0].ToString();
string domain = de.Path.ToString().Split(new [] { ",DC=" },StringSplitOptions.None)[1];
MessageBox.Show(domain + "/" + user);
}
Because the value of de.Path is
LDAP://CN=FullName,DC=domain,DC=local