Authenticate User By Active Directory using LDAP
In a Realtime project it maximum time required security and Authentication of user. Microsoft Active Directory Provides Autheticate User From Active Directory using LDAP (Lightweight Data Access Protocol). I have Created a simple from with Two Textbox for User Name and Password.
Required NameSpaces are
using System.Net
using System.DirectoryServices
Note: For System.DirectoryServices Add System.DirectoryServices.dll from your Framework Directory.
Button Click Code :
private void btnLogin_Click(object sender, EventArgs e)
{
string strDomain="YourDomain.com"
NetworkCredential _objNetWorkC = new NetworkCredential(txtUserID.Text, txtPassword.Text, strDomain);
if (AuthenticateAndGetUserDataFromAD(txtUserID.Text, strDomain, txtPassword.Text))
{
MessageBox.Show("Hi You are autheticated user");
}
else
{
MessageBox.Show("Your are not Authorized User !!!!");
}
}
Here I have used NetWorkCredential Class for Creating Cerdential For User using User Name , Password and Domain Name.
Domain Name : In which domain user working or by which user will be authenticated, may be as example DotNetSpider.Com is a domain. user may be Autheticated from that domain while login into this sites.
Now , I have Written a seperatefunction for Authentication
public bool AuthenticateAndGetUserDataFromAD(string strusername, string strDomain, string strPassword)
{
string strRootDN = string.Empty;
DirectoryEntry objDseSearchRoot = null, objDseUserEntry = null;
DirectorySearcher objDseSearcher = null;
SearchResultCollection objResults = null;
string strLDAPPath = string.Empty;
try
{
/* Give LDAP Server IP along with OU
* e.g : LDAP://29.29.29.29:389/DC=YourDomain,DC=com"
*/
strLDAPPath = "Your LDAP ServerPath";
string strDomainname = strDomain;
objDseSearchRoot = new DirectoryEntry(strLDAPPath, strDomainname + "\\" + strusername, strPassword, AuthenticationTypes.None);
strRootDN = objDseSearchRoot.Properties["defaultNamingContext"].Value as string;
objDseSearcher = new DirectorySearcher(objDseSearchRoot);
objDseSearcher.CacheResults = false;
objResults = objDseSearcher.FindAll();
if (objResults.Count > 0)
{
objDseUserEntry = objResults[0].GetDirectoryEntry();
}
if (objDseUserEntry == null)
{
return false;
}
}
catch (Exception e)
{
return false; ;
}
finally
{
//Dipose Object Over Here
}
return true;
}
try this:
http://manindra.net/post/2010/03/29/What-is-Active-Directory-Of-Windows.aspx