Friday, September 25, 2009

Authenticate user via Active Directory - ASP.NET - C#

Authentication is one of most important process of asp.net application ,there are four modes which can be defined in web.config file, "Passport", "Windows", "Forms" and "None".
many applications use Forms Mode which means you should design a login.aspx page and user enter username and password , however many useres suffer to memorize many user name and password for working with applications, one of the most suitable way to release from this problem is used the same user name and password which users use to logon to his/her computer , I mean the same user name and password in Active Directory. using this class provides this facility for the application. just create an instance of the class and call IsExistedDomainUser function.

using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.DirectoryServices;


///
/// User can be authenticated with existing User Name and password in Active Directory
/// LdapPath such as LDAP://ServerName/DC=MyCompany,DC=COM
///
public class LDAPAuthentication
{
string _LdapPath;
string _FilterAttribute;


public LDAPAuthentication(string LdapPath)
{
_LdapPath = LdapPath;

}

public bool IsExistedDomainUser(System.Web.HttpResponse Response, string strUsername, string strDomain, string strPassword, bool isCookiePersistent)
{

if (IsAuthenticated(strDomain, strUsername, strPassword) == true)
{

//Create the ticket, and add the groups.
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, strUsername, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, FormsAuthentication.FormsCookiePath);

//Encrypt the ticket.
string strEncryptedTicket = FormsAuthentication.Encrypt(authTicket);

//Create a cookie, and then add the encrypted ticket to the cookie as data.
HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);

if (isCookiePersistent == true)
authCookie.Expires = authTicket.Expiration;

//Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);

//If user registerd in Doamin
return true;
}
else
//If user does not registerd in Doamin
return false;

}

private bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + "\\" + username;
DirectoryEntry entry = new DirectoryEntry(_LdapPath, domainAndUsername, pwd);
try
{
object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if ((result == null))
{
return false;
}
_LdapPath = result.Path;
_FilterAttribute = ((string)result.Properties["cn"][0]);
}
catch
{
throw new Exception("Incorrect User name or passowrd, try again!");
}
return true;
}
}
//-----------------------------------------------------------------
changing Web.Config and set your logon form name with the following syntax
Logon page in this example is Logon.aspx in the
authentication tag
forms name="AuthCookie" loginUrl="Logon.aspx"

No comments:

Post a Comment

Thank you for sharing your knowledge and experiences with this weblog.