How to authenticate in LDAP in C#? - 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)
{
}

Related

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.

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

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

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

How to programmatically change Active Directory password

I have a set of test accounts that are going to be created but the accounts will be setup to require password change on the first login. I want to write a program in C# to go through the test accounts and change the passwords.
You can use the UserPrincipal class' SetPassword method, provided you have enough privileges, once you've found the correct UserPrincipal object. Use FindByIdentity to look up the principal object in question.
using (var context = new PrincipalContext( ContextType.Domain ))
{
using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName ))
{
user.SetPassword( "newpassword" );
// or
user.ChangePassword( "oldPassword", "newpassword" );
user.Save();
}
}
Here's a great Active Directory programming quick reference:
Howto: (Almost) Everything In Active Directory via C#
See the password reset code near the end.
public void ResetPassword(string userDn, string password)
{
DirectoryEntry uEntry = new DirectoryEntry(userDn);
uEntry.Invoke("SetPassword", new object[] { password });
uEntry.Properties["LockOutTime"].Value = 0; //unlock account
uEntry.Close();
}
Try this code. It works for me,
public void ChangeMyPassword(string domainName, string userName, string currentPassword, string newPassword)
{
try
{
string ldapPath = "LDAP://192.168.1.xx";
DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainName + "\\" + userName, currentPassword);
if (directionEntry != null)
{
DirectorySearcher search = new DirectorySearcher(directionEntry);
search.Filter = "(SAMAccountName=" + userName + ")";
SearchResult result = search.FindOne();
if (result != null)
{
DirectoryEntry userEntry = result.GetDirectoryEntry();
if (userEntry != null)
{
userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
userEntry.CommitChanges();
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Here is the solution:
string newPassword = Membership.GeneratePassword(12, 4);
string quotePwd = String.Format(#"""{0}""", newPassword);
byte[] pwdBin = System.Text.Encoding.Unicode.GetBytes(quotePwd);
UserEntry.Properties["unicodePwd"].Value = pwdBin;
UserEntry.CommitChanges();
It is possible to set a new password to a domain account, by using .NET Framework 2.0.
See working code bellow:
string domainfqdn="mydomain.test.gov" //fqdn of the domain
string ldapPath =GetObjectDistinguishedName (objectClass.user,returnType.distinguishedName, args[0].ToString(),domainfqdn);
ldapPath="LDAP://" + domainfqdn + :389/"+ldapPath;
DirectoryEntry uEntry = new DirectoryEntry(ldapPath,null,null,AuthenticationTypes.Secure);
uEntry.CommitChanges();
Console.WriteLine(ldapPath);
string password="myS3cr3tPass"
uEntry.Invoke("SetPassword", new object[] { password });
uEntry.Properties["LockOutTime"].Value = 0; //unlock account
uEntry.CommitChanges();
uEntry.Close();
it is very importan to check the parameters at uEntry, the code will run under the current thread security context, unless the null values are specified
public void ResetPassword(string userName, string Password, string newPassword)
{
try
{
DirectoryEntry directoryEntry = new DirectoryEntry(Path, userName, Password);
if (directoryEntry != null)
{
DirectorySearcher searchEntry = new DirectorySearcher(directoryEntry);
searchEntry.Filter = "(samaccountname=" + userName + ")";
SearchResult result = searchEntry.FindOne();
if (result != null)
{
DirectoryEntry userEntry = result.GetDirectoryEntry();
if (userEntry != null)
{
userEntry.Invoke("SetPassword", new object[] { newPassword });
userEntry.Properties["lockouttime"].Value = 0;
}
}
}
}
catch (Exception ex)
{
Log.Error("Password Can't Change:" + ex.InnerException.Message);
}
}

Categories