TECHNET Home>
Security Center>
Safety Guide Center
How to verify form authentication for Active Directory
Update Date: April 20, 2004
This page
Target applications How to use this chapter Abstract Create a web application with a login page to configure a web application's Form authentication development LDAP authentication code to find users to develop LDAP group retrieval code in Active Directory to find users. Member authentication user identity and creation form authentication ticket realistic authentication request handler to construct the GenericPrincipal object test application
aims
The goal of this chapter is:
•
Create a web application that uses Form authentication to authenticate the user's identity for Active Directory.
•
Gets a list of groups and distribution groups belonging through authenticated users from Active Directory.
•
Create a GenericPrincipal object associated with a user web request using the HTTPCONTEXT.CURRENT.USER attribute.
Back to top
Scope of application
This chapter applies to the following products and technologies:
•
Microsoft Windows® XP or Windows 2000 Server (Service Pack 3) and Higher Version Operating System
•
Active Directory
•
Microsoft .NET Framework version 1.0 (Service Pack 2) and later
•
Microsoft Visual Studio® 1.0 .NET and higher
•
Microsoft Visual C # ® .NET
•
Microsoft SQL Server® 2000 (Service Pack 2) and later
Back to top
How to use this chapter
To learn this chapter:
•
You must have experience using Visual C # .NET and Visual Studio .NET.
•
You must have experience in developing web applications using the ASP.NET.
•
You must have experience using Active Directory.
•
You must access an Active Directory instance for testing your application. This instance cannot be a production system.
•
Read Chapter 3 Authentication and Authorization in this guide. This chapter provides detailed information on various authentication mechanisms and discusses security based on .NET role.
•
Read Chapter 8 ASP.NET Security in this guide. This chapter provides details about ASP.NET Web Form authentication.
Back to top
Summary
With ASP.NET Form authentication, users can indicate their identity by entering credentials (usernames and passwords) in the web form. After receiving these credentials, the web application checks the credentials for the data source to verify the identity of the user.
This chapter describes how to verify the user's identity by using the Light Directory Access Protocol (LDAP). Here is how to retrieve the list of security groups and distribution groups belonging to the user, and how to configure genericprincipal objects for authorization based on .NET role.
Back to top
Create a web application with a login page
This process creates a simple Visual C # web application, which contains a user who can enter a login page for a username and password, and a default page that displays the identity name and group member identity information associated with the current web request.
•
Create a web application with a login page
1.
Start Visual Studio .NET and create a new Visual C # ASP.NET web application called Formsauthad.
2.
Use the Solution Explorer to rename WebForm1.aspx to logon.aspx.
3. Add a new System.DirectoryServices.dll assembly reference. This provides access to the System.DirectoryServices namespace, which contains managed types for Active Directory queries and operations.
4.
Add the controls listed in Table 1 to Logon.aspx to create a simple login form.
Table 1: Logon.aspx control
Control Type Text ID Tag Domain Name: - Tag User Name: - Tag Password - Text Box - TXTDOMainName Text Box - TXTUSERNAME text box - TXTPASSWORD button Log in BTNLOGON Tag LBLERROR
5.
Set the TXTPassword's TextMode property to Password.
6.
In the Solution Explorer, right-click "Formsauthad", point to Add, and then click Add Web Form.
7.
In the Name field, type "Default.aspx" and click Open.
8.
In the Solution Explorer, right-click "Default.aspx" and click Set to Benefits.
9.
Double-click the "default.aspx" display page load event handler.
10.
Add the following code to the event handler, display the identity name associated with the current web request:
Response.write (httpContext.current.user.Identity.name);
Back to top
Form authentication for configuring web applications
This procedure edits the application's web.config file to configure the application's form authentication.
•
Form authentication for configuring web applications
1.
Use the Solution Explorer to open Web.config.
2.
Find
3.
Add the
forms>
authentication>
4.
Add the following
authorization>
5.
Save Web.config.
6.
Start IIS Microsoft Management Console (MMC) management unit.
7.
Right click on the virtual directory of the application and click Properties.
8.
Click the Directory Security tab and click the Edit button in the Anonymous Access and Authentication Control group.
9.
Check the "Anonymous Access" check box and clear the "Allow IIS Control Password" check box.
10.
Because the default anonymous account IUSR_MACHINE does not access the Active Directory permissions, create a new account with the lowest authority and enter the account details in the Authentication Method dialog. 11.
Click OK, then click "OK" to close the Properties dialog.
12.
Return to Visual Studio .NET, add the
Once this is executed, all application requests run in the security context of the configured anonymous account. The user will provide credentials via the web form to perform Active Directory authentication, but the account used to access the Active Directory will be configured anonymous account.
Back to top
Develop LDAP authentication code to find users in Active Directory
This process adds a new help class to the web application for encapsulating the LDAP code. This class will initially provide an isauthenticated method for verifying the domain, username, and password for the Active Directory user object.
•
Develop LDAP authentication code to find users in Active Directory
1.
Add a new C # class file called LDAPAUTHENTICATION.CS.
2.
Add a System.directoryServices.dll assembly reference.
3.
Add the following USING statement at the top of ldaPauthentication.cs:
Using system.text;
Using system.collections;
Using System.directoryServices;
4.
Rename the existing namespace to Formsauthad.
5.
Add two private strings to the LDaPAuthentication class: a LDAP path that saves Active Directory and saves the filter properties for searching Active Directory.
Private string _path;
Private string _filterattribute;
6.
Add a common constructor for initializing the Active Directory path.
Public ldapauthentication (String Path)
{
_path = path;
}
7.
Add the following ISAUTHENTICATED method, which uses the domain name, username, and password as a parameter and returns a Boolean value indicating whether there is a user with a matching password in Active Directory. This method initially attempted to bind to Active Directory using the provided credentials. If successful, this method will use the DirectorySearcher host to search for the specified user object. If found, update _path members to point to the user object, and use the user object's public name property update _filterattribute member.
Public Bool Isauthenticated (String Domain, String UserName, String PWD)
{
String domainandusername = domain @ "/" usrname
DirectoryEntry Entry = New DirectoryEntry (_PATH,
Domainandusername, PWD); TRY
{
// Bind to this unit 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 of the user in the directory
_Path = result.path;
_filterattribute = (string) Result.properties ["cn"] [0];
}
Catch (Exception EX)
{
Throw New Exception ("error is wrong when authenticating the user." ex.Message);
}
Return True;
}
Back to top
Develop the LDAP group retrieval code to find the user's group member identity
This process extends the LDAPAUThentication class, providing a getGroups method for retrieving a list of groups where the current user is located. The GetGroups method will return to the group list as the string separated by the pipeline, as shown below:
"Group1 | Group2 | Group3 |"
•
Develop the LDAP group retrieval code to find the user's group member identity
1.
Add the following implementation to the LDAPAUThentication class:
Public String getGroups ()
{
DirectorySearcher Search = New DirectorySearcher (_PATH);
Search.filter = "(CN =" _filterattribute ")";
Search.propertiestold.Add ("Memberof");
Stringbuilder groupnames = new stringbuilder ();
Try
{
SearchResult result = search.findone ();
INT PropertyCount = Result.properties ["MEMBEROF"]. count;
String DN;
Int EqualsIndex, CommaIndex;
For (int propertycounter = 0; propertycounter PropertyCounter ) { DN = (String) Result.properties ["MEMBEROF"] [PropertyCounter]; EqualsIndex = dn.indexof ("=", 1); Commaindex = DN.Indexof (",", 1); IF (-1 == EqualsIndex) { Return NULL; } Groupnames.Append (DN.Substring (EqualsIndex 1), (COMMAINDEX - EqualsIndex) - 1)); Groupnames.Append ("|"); } } Catch (Exception EX) { Throw new exception ("Get the group name error." ex.Message); } Return Groupnames.toString (); } Back to top Verify user identity and create form authentication ticket This process implements the BTNLogon_Click event handler that verifies user identity. For users via authentication, a form authentication ticket containing the user group list will then be created. Then, redirect the user to the original page they requested (before redirecting to the login page). • Verify user identity and create form authentication ticket 1. Return to the Logon.aspx form, double-click the "Login" button to create an empty btnlogon_click event handler. 2. In the existing USING statement at the top of the file, add the following USING statement. This provides access to the FormsAuthentication method. Using system.web.security; 3. Add code to create a new instance of the initialized LDaPAuthentication class to point to LDAP Active Directory, as shown in the following code. Remember to change the path to point to the Active Directory server. // The path of your LDAP directory server. / / Contact your network administrator to get a valid path. String adpath = "ldap: //yourcompanyname.com/dc=yourcompanyname, dc=com"; LDAPAUTHENTICATION ADAUTH = New LDAPAUTHENTICITION (Adpath); 4. Add the following code to perform the following steps: 1. Active Directory authentication is performed on the caller. 2. Retrieve the list of users where the user is located. 3. Create a FormsAuthenticationalTicket containing a group list. 4. Encrypt tickets. 5. Create new cookies with encrypted tickets. 6. Add a cookie to the cookie list returned to the user browser. Try { IF (true == adAuth.isauthenticated (txtdomainname.text, TXTUSERNAME.TEXT, TXTPASSWORD.TEXT)))) { // Retrieve user group String groups = adAuth.getGroups (); // Create an authentication ticket FormsAuthenticationalTicket Authticket = New FormsauthenticationTicket (1, // version TXTUSERNAME.TEXT, Datetime.now, Datetime.now.addminutes (60), False, Groups); // Now encrypt the ticket. String encryptedticket = formsauthentication.encrypt (authticket); // Create a cookie and add the encrypted ticket to // This cookie is used as data. Httpcookie authcookie = New httpcookie (Formsauthentication.FormScookiename, Encryptedticket; // Add this cookie to the outgoing cookie collection. Response.cookies.add (authcookie); // Redirect the user to the initial request page response.Redirect Formsauthentication.getredirectURL (txtusername.text, False); } Else { lblerror.text = "Authentication failed, check the username and password." } } Catch (Exception EX) { LBLERROR.TEXT = "Authentication error." ex.Message; } Back to top Implement authentication request handler to construct GenericPrincipal objects This process implements the Application_AuthenticateRequest event handler in GLOBAL.ASAX and creates a genericprincipal object for users currently verified by authentication. This will contain a list of users where the user is located. The group list is retrieved from the FormsAuthenticationalTicket included in the authentication cookie. Finally, associate the genericprincipal object with the current HTTPContext object created for each web request. • Implement authentication request handler to construct GenericPrincipal objects 1. Use the Solution Explorer to open Global.asax.cs. 2. Add the following USING statement at the top of the file: Using system.web.security; Using system.security.principal; 3. Find the Application_AuthenticateRequest event handler and add the following code to get the cookie containing the encrypted FormSauthenticationalTicket from the cookie collection that is sent together. / / Extract Form Authentication Cookie String cookiename = formsauthentication.formscookiename; HTTPCOOKIE Authcookie = Context.Request.cookies [cookiename]; IF (NULL == Authcookie) { // No authentication cookie Return; } 4. Add the following code, extract the FormsAuthenticationTicket from the cookie and decrypt: FormsauthenticationalticKet Authticket = NULL; Try { Authticket = formsauthentication.Decrypt (authcookie.value); } Catch (Exception EX) { // Record an abnormal situation details (for easy start, omitted) Return; } IF (null == authticket) { // Unable to decrypt the cookie. Return; } 5. Add the following code, parsing When the user is initially attached to the ticket, the group name list is separated by the ticket: // After creating a ticket, specify one for the UserData property // Separate the group name string separated by a pipe. String [] groups = authticket.userdata.split (new char [] {'|'}); 6. Add the following code to create a GenericIdentity object using the username obtained from the ticket name and create a genericprincipal object that contains this identity and the user group list: // Create a logo object GenericIdentity ID = new genericidentity (authticket.name); "ldapauthentication"); // The body will pass throughout the request. GenericPrincipal Principal = New GenericPrincipal (ID, Groups); // Attach the new body object to the current HTTPCONTEXT object CONTEXT.USER = Principal; Back to top Test application This process uses the web application request default.aspx page. You will be redirected to the login page for authentication. After the authentication is successful, the browser will be redirected to the DEFAULT.ASPX page of the original request. This extracts and displays a list of groups belonging through authenticated users from GenericPrincipal objects (this object associated with the current request during authentication). • Test application 1. On the Generate menu, click Generate Solutions. 2. In the Solution Explorer, right-click "Default.aspx", then click "View in your browser". 3. Enter a valid domain name, user name, and password, and then click Login. 4. After successfully verify, you will be redirected back to DEFAULT.ASPX. The code on this page will display the username through the authentication. To see a list of groups where the user is located, add the following code at the end of the Application_AuthenticateRequest event handler in the global.aspx.cs file: Response.write ("Group:" authticket.userdata "
);