Creating LDAP Connection on .NET - c#

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

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)
{
}

How to authenticate users in C# LDAP

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.
uri = ldaps://ABC.ad.XYZ.com:636
user_filter = memberOf=CN=TENXAIRFLOWPROD,OU=Security Groups,OU=Normal Users and Groups,OU=Account Management Services,OU=AD Master OU,DC=ABC,DC=ad,DC=XYZ,DC=com
user_name_attr = sAMAccountName
superuser_filter = memberOf=CN=TENXAIRFLOWPROD_ADM,OU=Security Groups,OU=Normal Users and Groups,OU=Account Management Services,OU=AD Master OU,DC=ABC,DC=ad,DC=XYZ,DC=com
bind_user = SCGLOBAL\twiki
bind_password_cmd = python /bns/tenx/airflow/ldap_password.py
basedn = DC=ABC,DC=ad,DC=XYZ,DC=com
search_scope = SUBTREE
Here is a code I have developed but it gives me error:
string username = "myUserName";
string domain = "ldaps://ABC.ad.XYZ.com:636";
string pwd = "myPasword";
try
{
DirectoryEntry entry = new DirectoryEntry(domain, username, pwd);
//Bind to the native AdsObject to force authentication.
object obj = entry.NativeObject;
lblError.Text=("Login Successful");
//search some info of this user if any
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
SearchResult result = search.FindOne();
}
catch (Exception ex)
{
lblError.Text=("Login failed: " + ex.ToString());
}
Could anybody help plz?
Comment: According to the admin , I have been assigned to the group in AD. But how can I make sure I can access it?
It seems like Active Directory. If so, you could just use PrincipalContext.
public bool ValidateCredentials(string domain, string username, string password)
{
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
return context.ValidateCredentials(username, password);
}
}
public bool IsUserInAdGroup(string domain, string username, string adGroupName)
{
bool result = false;
using (var context = new PrincipalContext(ContextType.Domain, domain))
{
var user = UserPrincipal.FindByIdentity(context, username);
if (user != null)
{
var group = GroupPrincipal.FindByIdentity(context, adGroupName);
if (group != null && user.IsMemberOf(group))
result = true;
}
}
return result;
}
Please make sure to reference System.DirectoryServices.AccountManagement.

How to authenticate in LDAP?

I am trying to make a simple authentication system with LDAP in .NET.
I was checking some namespaces in .NET and simply make the standart code snippet as below.
DirectoryEntry de = new DirectoryEntry(path,username,password);
DirectorySearcher s = new DirectorySearcher(de);
s.Filter = "(&(cn=" + username2 + "))";
SearchResult result = s.FindOne();
if (result != null) {
Console.WriteLine("User exists");
} else {
Console.WriteLine("User does not exist");
}
I have an admin username and password, username and password, which I use to authenticate the client application. I have a second username and password, username2 and password2 that needs to be checked in the LDAP to log in.
username is the admin account and username2 is just an user in LDAP. So how can I check username2's password?
A slightly backwards (and clunky) way is to log in as the user and try to retrieve something, then treat an exception as an invalid password:
static bool CheckUser(string userName, string password)
{
var adSettings = ConfigurationManager.ConnectionStrings["ActiveDirectory"];
if (adSettings == null ||
string.IsNullOrWhiteSpace(adSettings.ConnectionString))
{
return false;
}
try
{
using (var de = new DirectoryEntry(adSettings.ConnectionString, userName, password))
{
// This should throw an exception if the password is wrong
object nativeObject = de.NativeObject;
}
}
catch (DirectoryServicesCOMException)
{
// Wrong password
return false;
}
catch (System.Runtime.InteropServices.COMException)
{
// Can't connect
return false;
}
return true;
}
I have something in VB which might help you out i guess. Was working on this few days ago with my collegue. Do let me know---
Code:
Dim cookie As HttpCookie = New HttpCookie("username")
cookie.Value = TextBox1.Text
cookie.Expires = DateAndTime.Now.AddHours(12)
Response.Cookies.Add(cookie)
Dim entry As New DirectoryEntry("LDAP://xyz.com/dc=xyz,dc=com", TextBox1.Text, TextBox2.Text)
Try
Dim obj As New Object
obj = entry.NativeObject
Dim search As New DirectorySearcher(entry)
search.Filter = "(SAMAccountName=" + TextBox1.Text + ")"
search.PropertiesToLoad.Add("cn")
Dim result As SearchResult
result = search.FindOne()
If result.Equals(Nothing) then
MsgBox("Try Again with valid username")
Else
MsgBox("User Found!")
Response.Redirect("~/Dashboard.aspx")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub

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.

Auto Signin with Active Directory Account in c# ASP.Net Website

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

Categories