Forms Authentication with Active Directory
This article and sample code explains how you can take advantage of Active Directory in Web applications for authenticate and authorize the Web site users.
Configure the Web Application for Forms Authentication:
a) IIS Configuration:
In Virtual Directories properties
- Click the Directory Security tab, and then click the Edit button in the Anonymous access group.
- 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
- 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.
<forms loginUrl="logon.aspx" name="adAuthName" timeout="60" path="/"> </forms>
Modify <authorization> element as following.
<deny users="?" />
<allow users="*" />
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);
// Bind to the native AdsObject to force authentication.
Object obj = entry.NativeObject;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + username + ")";
SearchResult result = search.FindOne();
if(null == result)
// Update the new path to the user in the directory
LDAPPATH = result.Path;
catch (Exception ex)
throw new Exception("Error authenticating user." + ex.Message);
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
- Create a FormsAuthenticationTicket that contains the userdata (UserData can contain roles for the user).
- Encrypt the ticket.
- Create a new cookie / session that contain the encrypted ticket.
- Add the cookie / session to the list of cookies / sessions returned to the user's browser.
- 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);
if(true == adAuth.AuthenticateUser(txtDomainName.Text, txtUserName.Text, txtPassword.Text))
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);
lblError.Text = "Authentication Failed please check UserName & Password";
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:
Public void Create()
if(HttpContext.Current.User.IsInRole() == "Create")
//Statements to create
Response.write("You are not authorized to Create.");
// Permission Attribute
[PrincipalPermissionAttribute(SecurityAction.Demand, Role = "Create")]
Public void Create()
//Statements to create