Active Directory connection Failure - c#

I need a small help. I am new to active directory. I want to connect my active directory with c#. Here is the sample code i have wrote.
public void GetConnection()
{
var username = "xxxx";
var domain = "xxxx";
var password = "xxxx";
var path = "LDAP://xxxx/CN=xx";
DirectoryEntry de = new DirectoryEntry(sDomain + "/" + sDefaultOU, sUsername, sServicePassword, AuthenticationTypes.ServerBind);
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectClass=Users))";
var sr = ds.FindAll();
if (sr != null)
{
MessageBox.Show("success");
}
else
{
MessageBox.Show("error");
}
}
}
There is a COMException was unhandled near
var sr = ds.FindAll();
The error is:
An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in System.DirectoryServices.dll
Additional information: Unspecified error
Can I have some help in fixing the issue? Thanks in advance

Step 1
static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
//This is for ssl secure port for non secure port just make 636 as 389 and //change Authentication as None
DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://mysystem.domain.com:636","Admin","Domain123",AuthenticationTypes.SecureSocketsLayer);
return ldapConnection;
}
**
Step 2
**
In the main function u need to write below function
DirectorySearcher _searcher = null;
SearchResult result_user = null;
DirectoryEntry de = createDirectoryEntry();
object o = de.SchemaEntry;
_searcher = new DirectorySearcher(de, "(&(objectClass=user)(SAMAccountName=" + "user1" + "))");
if (_searcher != null)
{
result_user = _searcher.FindOne();
de.Close();
}

Related

How to authenticate in LDAP in C#?

I am new to LDAP related coding and today I am asked to develop a code to check the users authentication against LDAP.
The tutorials I have found online are so simple but our company's Directory is so complicated that I don't know how to write a code for that. Here is the info of the LDAP . I have changed the company name to hide the name.
string domain = "ou=People,dc=my,dc=com";
string LDAP_Path= "dc01.my.com;
string LDAPconnect= "LDAP://dc01.my.com/";
Here is a code I have developed but it gives me error when run " LdapResult = LdapSearcher.FindOne();":
string domain = "ou=People,dc=my,dc=com";
string password = "";
string userName = "";
// define your connection
LdapConnection ldapConnection = new LdapConnection(LDAP_Path);
try
{
// authenticate the username and password
using (ldapConnection)
{
// pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(userName, password, domain);
// if we're using unsecured port 389, set to false. If using port 636, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
// since this is an internal application, just accept the certificate either way
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
// to force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, just use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
// authenticate the user
ldapConnection.Bind(networkCredential);
Response.Write( "connect ldap success");
}
}
catch (LdapException ldapException)
{
Response.Write(ldapException + " <p>Ad connect failed</p>");
//Authentication failed, exception will dictate why
}
string strTmp0 = LDAPconnect + domain;
string user = "memberId";
string pwd = "memberPwd";
System.DirectoryServices.DirectoryEntry LdapEntry = new System.DirectoryServices.DirectoryEntry(strTmp0, "cn=" + user, pwd, AuthenticationTypes.None);
DirectorySearcher LdapSearcher = new DirectorySearcher(LdapEntry);
LdapSearcher.Filter = "(cn=" + user + ")";
string value = string.Empty;
SearchResult LdapResult=null;
try
{
LdapResult = LdapSearcher.FindOne();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
// .............get Error msg : username an password uncorrect
}
if ((LdapResult != null))
{
Response.Write("ldapresult not null");
}
Could anybody help plz?
In ldap connection setting , OP should use own configuration.
// Ldap connection setting. this should setup according to organization ldap configuration
int portnumber = 12345;
LdapConnection ldapConnection = new LdapConnection(new LdapDirectoryIdentifier("ldap.testxxxx.com", portnumber));
ldapConnection.AuthType = AuthType.Anonymous;
ldapConnection.Bind();
SearchRequest Srchrequest = null;
SearchResponse SrchResponse = null;
SearchResultEntryCollection SearchCollection = null;
Hashtable UserDetails = new Hashtable();
Srchrequest = new SearchRequest("distniguishged name e.g. o=testxxx.com", string.Format(CultureInfo.InvariantCulture, "preferredmail=test#testxxxx.com"), System.DirectoryServices.Protocols.SearchScope.Subtree);
SrchResponse = (SearchResponse)ldapConnection.SendRequest(Srchrequest);
SearchCollection = SrchResponse.Entries;
foreach (SearchResultEntry entry in SearchCollection)
{
foreach (DictionaryEntry att in entry.Attributes)
{
if (((DirectoryAttribute)(att.Value)).Count > 0)
{
UserDetails.Add(att.Key.ToString(), ((DirectoryAttribute)(att.Value))[0].ToString());
}
else
{
UserDetails.Add(att.Key.ToString(), string.Empty);
}
}
}
if (UserDetails.Count > 1)
{
Console.WriteLine("User exists");
}
else
{
Console.WriteLine("User does not exist");
}
You can use the DirectoryInfo conrstructor that has user and password arguments. That way, you don't need to do a query to the LDAP, you can simplify your code.
string username = "frederic";
string password = "myFanciPassword99";
string domain = "ou=People,dc=my,dc=com";
string LDAPconnect= "LDAP://dc01.my.com/";
string connectionString = LDAPconnect + domain;
bool userValid = false;
// Note: DirectoryEntry(domain, username, password) would also work
DirectoryEntry entry = new DirectoryEntry(connectionString, username, password);
try
{
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
userValid = true;
}
catch (Exception ex)
{
}

Accessing Active Directory with Unity

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.

Creating LDAP Connection on .NET

I am trying to Create LDAP Cnnection using c# .
I found this server which gives LDAP Server to Test
http://www.forumsys.com/en/tutorials/integration-how-to/ldap/online-ldap-test-server/
I have googled many post and Tried to create a consolidated Code
string domain = "ldap://ldap.forumsys.com/ou=mathematicians";
string username = "cn=read-only-admin,dc=example,dc=com";
string password = "password";
string LdapPath = "Ldap://ldap.forumsys.com:389/ou=scientists,dc=example,dc=com";
string domainAndUsername = domain + #"\" + username;
DirectoryEntry entry = new DirectoryEntry(LdapPath, domainAndUsername, password);
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();
// Update the new path to the user in the directory
LdapPath = result.Path;
string _filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
throw new Exception("Error authenticating user." + ex.Message);
}
This code is not connecting it is giving unexpected error ..
I also Tried some other Credentials , But they are not helping either ...
AUTH_LDAP_SERVER_URI = “ldap://ldap.forumsys.com”
AUTH_LDAP_BIND_DN = “cn=read-only-admin,dc=example,dc=com”
AUTH_LDAP_BIND_PASSWORD = “password”
AUTH_LDAP_USER_SEARCH = LDAPSearch(“ou=mathematicians,dc=example,dc=com”,
ldap.SCOPE_SUBTREE, “(uid=%(user)s)”)
--------------------
$config[‘LDAP’][‘server’] = ‘ldap://ldap.forumsys.com';
$config[‘LDAP’][‘port’] = ‘389’;
$config[‘LDAP’][‘user’] = ‘cn=read-only-admin,dc=example,dc=com';
$config[‘LDAP’][‘password’] = ‘password';
-------------------------
$config[‘LDAP’][‘server’] = ‘ldap://ldap.forumsys.com/ou=mathematicians';
$config[‘LDAP’][‘port’] = ‘389’;
$config[‘LDAP’][‘user’] = ‘gauss';
$config[‘LDAP’][‘password’] = ‘password';
--------------------------
OpenDSObject/GetObject functions, but don’t see a way to run a query with the ASDI objects.
Set LDAP = GetObject(“LDAP:”)
Set root = LDAP.OpenDSObject(“LDAP://ldap.forumsys.com:389″, “cn=read-only-admin,dc=example,dc=com”, “password”, 0)
Set ou = LDAP.OpenDSObject(“LDAP://ldap.forumsys.com:389/ou=mathematicians,dc=example,dc=com””, “cn=read-only-admin,dc=example,dc=com”, “password”, 0)
Set user = LDAP.OpenDSObject(“LDAP://ldap.forumsys.com:389/uid=riemann,dc=example,dc=com”, “cn=read-only-admin,dc=example,dc=com”, “password”, 0)
I need some suggestion what I am missing . any resource will be helpful
I had a somewhat similar issue with this server and google sent me here.
One issue I see is that case sensitive issue in LDAP path. Also we should specify the AuthenticationType as well.
Please check following code block which should work.
string ldapServer = "LDAP://ldap.forumsys.com:389/ou=scientists,dc=example,dc=com";
string userName = "cn=read-only-admin,dc=example,dc=com";
string password = "password";
var dirctoryEntry = new DirectoryEntry(ldapServer, userName, password, AuthenticationTypes.ServerBind);
try {
object nativeObject = dirctoryEntry.NativeObject;
//Rest of the logic
} catch (Exception ex) {
//Handle error
}
Trying using PrincipalContext to connect to the LDAP server. Here is a good how-to article I referenced when I was getting started: http://ianatkinson.net/computing/adcsharp.htm
ctx = new PrincipalContext(
ContextType.Domain,
"contoso.local",
"OU=Security Groups,OU=Contoso Inc,DC=contoso,DC=local",
"contoso\sysadmin",
"P#ssword1");
Namespace - using System.DirectoryServices.Protocols;
methode -
private bool ldapValidateUser(string fullname, string password)
{
try
{
LdapDirectoryIdentifier ldap = new LdapDirectoryIdentifier("Directory Host", true, false);
LdapConnection connection = new LdapConnection(ldap);
connection.AuthType = AuthType.Basic;
string ldapuser = "cn=" + fullname + ",ou=Org Unit,dc=Value,dc=local";
connection.Credential = new System.Net.NetworkCredential(ldapuser, password);
connection.Bind();
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}

Update active directory account properties

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

C#: code error while changing the active directory user's password

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.

Categories