Tuesday, May 12, 2009

Windows Authentication(Active Directory/LDAP) in ASP.Net

Sometimes, there may be requirement to get user name from end user information and authenticate against active directory group/LDAP in ASP.Net.

Following are the ways to achieve that
  • can be accomplished by enabling windows Integrated authentication in IIS server and disabling Anonymous access for this application. By doing the above config changes in IIS server, the user will be shown a Login window in the browser and prompting for windows user credentials.

  • Alternate way is to get the logon crdentials using C# code and validate again user information. Below is the code snippet which is used to capture the login info using windows integrated authentication and validate against AD group.


Write the following code sample in the Session start event and based on user validation, session will be started

using System.Security.Principal;
using System.Security.Permissions;

protected void Session_Start(Object sender, EventArgs e)
{
// Get the current loged in User information
WindowsPrincipal user = (WindowsPrincipal)Thread.CurrentPrincipal;

//Storing the user name in the session. If you remove the domain name, u can get user name alone
Session["userName"] =user.Identity.Name.Replace("DOMAINName\\",string.Empty);

// This session variable is used further to verify the user
Session["SecurityIsApproved"] = "false";

// Check for valid user in the AD group
if(user.IsInRole("Active Directory group name"))
{
Session["SecurityIsApproved"] = "true";
}
else
{
throw new Exception("Invalid user");
}
}