Forms Authentication with Active Directory

Configure the Web Application for Forms Authentication:

a) IIS Configuration:

In Virtual Directories properties

  1. Click the Directory Security tab, and then click the Edit button in the Anonymous access group.
  2. Select the Anonymous access check box and click on Edit button and clear the Allow IIS to control password check box. Because the default anonymous account IUSR_MACHINE does not have permission to access Active Directory, create a new least privileged account and enter the account details in the Authentication Methods dialog box.

b) Modifications in Web.Config:

In Web.config in the <authentication> element and change the mode attribute to Forms

  1. Add the following <forms> element as a child of the authentication element and set the loginUrl, name, timeout, and path attributes as shown in the following.

    <authentication mode="Forms">
    <
    forms loginUrl="logon.aspx" name="adAuthName" timeout="60" path="/"> </forms>
    </
    authentication>

  2. Modify <authorization> element as following.

    <authorization>
    <deny users="?" />
    <
    allow users="*" />
    </
    authorization>

  3. Add <Identity> element and set it's impersonate value to true.

    <Identity impersonate = "true" />

Develop LDAP Authentication Code to Look Up the User in Active Directory

1. Develop a component having a method AuthenticateUser which will check / validate the supplied credentials (Username, Password, and Domain Name) against an AD (Active Directory). 

public bool AuthenticateUser(string domain, string username, string password)
{
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();
if(null == result)
{
return false;
}
// Update the new path to the user in the directory
LDAPPATH = result.Path;
}
catch (Exception ex)
{
throw new Exception("Error authenticating user." + ex.Message);
}
return true;
}

2. Add GetRoles method which will retrieve roles for the User if you want to set authorization for accessing methods as per user role.

Web Page For Authenticating The User And Creating Forms Authentication Ticket

Develop webpage say login page which will authenticate user by calling IsAuthenticated method of the component.

On successful authentication

  1. Create a FormsAuthenticationTicket that contains the userdata (UserData can contain roles for the user).
  2. Encrypt the ticket.
  3. Create a new cookie / session that contain the encrypted ticket.
  4. Add the cookie / session to the list of cookies / sessions returned to the user's browser.
  5. Redirect User to the original page what he requested.

The sample code is as given:

string adPath = LDAP://LDAPServer/DC=doamin,DC=com;
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if(true == adAuth.AuthenticateUser(txtDomainName.Text, txtUserName.Text, txtPassword.Text))
{
Response.Write("Autheticated");
String role = (adAuth.GetRoles(txtDomainName.Text, txtUserName.Text, txtPassword.Text));
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, txtUserName.Text, DateTime.Now, DateTime.Now.AddMinutes(60), false,userdata );
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie authCookie = new HttpCookie( FormsAuthentication.FormsCookieName , encryptedTicket);
Response.Cookies.Add(authCookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUserName.Text,false));
}
else
{
lblError.Text = "Authentication Failed please check UserName & Password";
}
}
catch(Exception ex)
{
Response.Write("Error authenticating. " + ex.Message);
}

Implement an Authentication Request Handler to Construct a GenericPrincipal Object

Implements the Application_AuthenticateRequest event handler within global.asax and creates a GenericPrincipal object for the currently authenticated user. This will contain roles for that user, retrieved either from the FormsAuthenticationTicket contained in the authentication cookie / session or in the event itself by calling GetRoles method of component. Then associate the GenericPrincipal object with the current HttpContext object that is created for each Web request (since the event is fired for each request).

GenericIdentity id=new GenericIdentity(authTicket.Name, "Authentication");
GenericPrincipal principal = new GenericPrincipal(id, roles);

Using Permissions for Authorizing Methods Access

Now since we have added roles to Principal object we can give access to execute method / events according to the roles. We can secure our method / events depending on the roles. This can be done programmatically by checking HttpContext.Current.User.IsInRole() method or by adding Permission Attribute before the methods / events.

The example is as shown below:

//Programmatically
Public void Create()
{
if(HttpContext.Current.User.IsInRole() == "Create")
{
//Statements to create
}
else
{
Response.write("You are not authorized to Create.");
}
}
// Permission Attribute
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Create")]
Public void Create()
{
//Statements to create
}