Sunday, July 11, 2010

Active Directory Authentication from ASP .NET

Any ASP.Net application which requires authenticating a user from Active directory would required LDAP (Lightweight Directory Access protocol).
To achieve this you would require the following.

1. Add the below two namespaces.
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

2. Use the below function to authenticate the user with Active directory.

public static bool AuthenticateWithAD(string activeDirectoryServer, string userName,string password)
{
bool authentic = false;
try
{
DirectoryEntry entry = new DirectoryEntry(activeDirectoryServer, userName, password);
object nativeObject = entry.NativeObject;
authentic = true;
}

catch (DirectoryServicesCOMException)
{
return false;
}

catch (Exception ex)
{
return false;
}
return authentic;
}

//Below lines
AuthenticateWithAD("LDAP://spserver","username","password");


This does fantastic, I hope it will help you a lot when doing forms authenticate with AD.
Thanks

2 comments:

  1. Sorry to ask again.i am new to this type of authentication..............
    For now i am using the asp.net configuration authentication.

    How can i add LDAP authentication.....
    Where should i add these namespaces.

    and i cant add these webservices,will i have to get reference to dll or some thing,please let me know how i can do it.

    thanx

    ReplyDelete
  2. Definitely you need to add references of the Assembly System.DirectoryServices.dll
    This is .Net assembly, Right click on Reference->Add Reference->Choose .Net Tab and select the above mention System.DirectoryServices.dll

    Let me know if you have any issue or concern.

    ReplyDelete