Accessing Active Directory with Unity - c#

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.

Related

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

Active Directory connection Failure

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();
}

LDAP authentication on server

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 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