How to use Forms authentication with Active Directory

xiaoxiao2021-03-06  41

How to use Forms authentication with Active Directory

Release Date: 10/28/2004

| Update Date: 10/28/2004

Browse all the "Security Guide" topics

Microsoft Corporation

aims

This module is used in:

• Create a web application that uses Forms authentication to authenticate users for Active Directory. • Get the list of group lists and distribution groups belonging through authenticated users from Active Directory. • Create a GenericPrincipal object associated with the user's Web request with the httpContext.current.user property.

Applicable to:

This module is suitable for the following products and technologies:

• Microsoft Windows_ XP or Windows 2000 Server (with Service Pack 3) and Higher Versions • Active Directory • Microsoft .NET Framework Version 1.0 (with Service Pack 2) and later • Microsoft Visual Studio_ 1.0 .NET development system And higher version • Microsoft Visual C # _ .NET Development Tools • Microsoft SQL ServerTM 2000 (with Service Pack 2) and later

How to use this module

To maximize this module:

• There must be experience in using Visual C # .NET and Visual Studio .NET. • There must be experience in developing web applications using ASP.NET. • There must be experience in using Active Directory. • An instance of Active Directory that can be accessed to test applications - this instance should not be a production system. • Read the module "Authentication and Authorization". This module provides detailed information about the various authentication mechanisms and discusses security based on .NET role. • Read the module "ASP.NET Security". This module provides detailed information about ASP.NET Web Forms authentication.

This page

Summary Create a web application with a login page to configure the web application for Forms authentication development in Active Directory LDAP Authentication Code Development Finding User's Group member identity LDAP group retrieval code to authenticate the user and create Forms Authentication Ticket Implementation Authentication Request Processor to construct GenericPrincipal object test application

Summary

ASP.NET FORMS Authentication allows users to enter credentials (usernames and passwords) to a web form to identify themselves. When these credentials are received, the web application can check these credentials based on the data source to authenticate the user.

This module describes how to identify users according to Microsoft Active Directory_Directory services by using Lightweight Directory Access Protocol (LDAP). It also describes how to retrieve the security group list and distribution list of users belong to the user and the genericprincipal objects configured with the .NET-based role authorization.

Back to top

Create a web application with a login page

This process creates a simple Visual C # web application that contains a login page and a default page. The login page allows the user to enter the username and password, and the default page displays the identity name and group member identity information associated with the current web request.

To create a web application with a login page, perform the following steps:

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 assembly reference to System.directoryServices.dll. This operation provides access to System.directoryServices namespace, and this namespace contains managed types, which helps 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 Label Domain Name: - Label User Name: - Label Password - Text Box - TXTMAINNAME TEXT BOX - TXTUSERNAME TEXT BOX - TXTUSERNAME TEXT BOX - TXTPASSWORD BUTTON LOG ON BTNLOGON LABEL - LBLERROR

1. Set the TXTPASSWORD TextMode property to Password. 2. In the Solution Explorer, right-click FormSauthad, point to Add, and then click Add Web Form. 3. In the Name field, type DEFAULT.ASPX, and then click Open. 4. In the Solution Explorer, right-click DEFAULT.ASPX, and then click Set As Start Page. 5. Double-click the DEFAULT.ASPX Display page Load Event Handler. 6. Add the following code to the event handler to display the identity name associated with the current web request. Response.write (httpContext.current.user.Identity.name);

Back to top

Configure web applications for Forms authentication

This process configures the application by editing the web.config file of the application for Forms authentication.

To configure a web application for Forms authentication, perform the following steps:

1. Use the Solution Explorer to open Web.config. 2. Locate to Elements and change the Mode property to Forms. 3. Add the following elements to the child elements of the authentication element and set the LoginURL, Name, Timeout, and Path properties, as shown in the following code.

4. Add the following elements to Elements. The purpose of this step is to allow only authenticated users to access applications. Previously established elements LoginURL attributes will be redirected to the Logon.aspx page without authentication request.

5. Preserve Web.config. 6. Start the IIS Microsoft Management Console (MMC) management unit. 7. Right-click on the virtual directory of the application, and then click Properties. 8. Click the Directory Security tab, and then click the Edit button in the Anonymous Access and Authentication Control group. 9. Check the Anonymous Access check box and clear the Allow Iis to Control Password check box. 10. Since the default anonymous account IUSR_MACHINE does not access the Active Directory permissions, create a new minimum privilege account and enter the account details in the Authentication Methods dialog. 11. Click OK, then click OK to close the Properties dialog. 12. Return to Visual Studio .NET, add the element to the element in Web.config and set the analog property to true. This will result in ASP.NET simulation anonymous accounts specified earlier. The result of this configuration is that all requests to the application will run in the security context of this configured anonymous account. The user will provide credentials via the web form to authenticate Active Directory, but the account used to access the Active Directory will be a configured anonymous account.

Back to top

Developed in Active Directory to find users' LDAP authentication code

This process adds a new Helper class to a web application to encapsulate LDAP code. This class initially provides an IsAuthenticated method to verify the domain, username, and password provided for Active Directory user objects.

To develop LDAP authentication code for users in Active Directory, do the following:

1. Add a new C # class file called LDAPAUTHENTICATION.CS. 2. Add a reference to the System.DirectoryServices.dll assembly. 3. Add the following USING statement at the top of the ldaPAUThentication.cs. Using system.text;

Using system.collections;

Using System.directoryServices;

4. Rename the existing namespace as FormSauthad. 5. Add two private strings to the LDAPAUThentication class; a string is stored in the LDAP path of Active Directory, and the other string is set to search for the Active Directory filter properties. Private string _path;

Private string _filterattribute;

6. Add a common constructor that can be used to initialize the Active Directory path. Public ldapauthentication (String Path)

{

_path = path;

}

7. Add the following iSAuthenticated method, this method accepts the domain name, username, and password as the parameters, and returns BOOL to indicate whether there is a user with a matching password in Active Directory. This method initially tried to bind to Active Directory using the supplied credentials. If this is successful, this method uses the DirectorySearcher managed class search for specified user objects. If found, the _path member is updated to point to the user object, and _filterattribute is updated using the public name property of the user object. Public Bool IsAuthenticated (String Domain, String Username, String PWD) {

String domainandusername = domain @ "/" usrname

DirectoryEntry Entry = New DirectoryEntry (_PATH,

DomainanduserName, PWD);

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

_Path = result.path;

_filterattribute = (string) Result.properties ["cn"] [0];

}

Catch (Exception EX)

{

"" Error Authenticating User. " ex.Message);

}

Return True;

}

Back to top

Develop LDAP group retrieval code for finding user group membership

This process extends the LDAPAUThentication class to provide a getGroups method. This method will retrieve the current user is a list of groups. The getGroups method returns a group list in a manner separated by a pipeline, as shown below.

"Group1 | Group2 | Group3 |"

To develop the LDAP group retrieval code for finding the user's group member identity, do the following:

• Add the following implementations of the getGroups method 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)

{

"" ERROR OBTAING GROUP NAMES. " EX.MESSAGE);

}

Return Groupnames.toString ();

}

Back to top

Authenticate the user and create a Forms authentication ticket

This process implements the BTNLogon_Click event handler to authenticate the user. For users who have already authenticated, a Forms authentication ticket that contains a list of users. Then, redirect the user to the initial page (before redirect to the login page).

To authenticate the user and create a Forms authentication ticket, do the following:

1. Return to the Logon.aspx form and double-click the LOG ON button to create an empty btnlogon_click event handler. 2. Add the following USING statements to an existing USING statement at the top of the file. This action provides access to the FormSauthentication method. Using system.web.security;

3. Add code to create an instance of a new LDaPAuthentication class, which is initialized to point to LDAP Active Directory, as shown in the following code. Remember to change the path to the Active Directory server. // path to you LDAP Directory Server.

// Contact Your Network Administrator to Obtain 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:

• Verify the identity of the caller according to the Active Directory. • Search users are a list of groups of their members. • Create a FormSAuthenticationalTicket containing a group list. • Collipite encrypted. • Create a new cookie that contains a packed ticket. • Add cookies to the cookie list returned to the user browser. Try

{

IF (true == adAuth.isauthenticated (txtdomainname.text, txtusername.text,

TXTPASSWORD.TEXT))))

{

// Retrieve The User's Groups

String groups = adAuth.getGroups ();

// Create the Authet Ticket

FormsAuthenticationalTicket Authticket =

New FormsauthenticationalTicket (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 the

// cookie as data.

Httpcookie authcookie =

New httpcookie (Formsauthentication.FormScookiename,

Encryptedticket;

// add the cookie to the outgoing cookies collection.

Response.cookies.add (authcookie);

// redirect the user to the Originally Requested Page

Response.Redirect

Formsauthentication.getredirectURL (txtusername.text,

False);

}

Else

{

lblerror.text =

"Authentication Failed, Check Username and Password."

}

}

Catch (Exception EX)

{

LBLERROR.TEXT = "Error Authenticating." 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 genericprincipal objects for the current authenticated user. This will contain a list of users whose users are their members and retrieved from the FormsAuthenticationalTicket containing authentication cookies. Finally, associate GenericPrincipal objects with the HTTPContext object that is currently created for each web request.

To implement an authentication request handler to construct the genericpricipal object, perform the following steps:

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. Locate the Application_AuthenticateRequest event handler and add the following code to get the cookie that contains the encrypted formsauthenticationalTicket from the Cookie collection that is delivered. // Extract the Forms Authentication Cookie

String cookiename = formsauthentication.FormScookiename; httpcookie authcookie = context.request.cookies [cookiename];

IF (NULL == Authcookie)

{

// there is no authentication cookie.

Return;

}

4. Add the following code to extract and decrypt the FormsAuthenticationalTicket from the cookie. FormsauthenticationalticKet Authticket = NULL;

Try

{

Authticket = formsauthentication.Decrypt (authcookie.value);

}

Catch (Exception EX)

{

// log exception details (OMITIted for simplicity)

Return;

}

IF (null == authticket)

{

// cookie failed to decrypt.

Return;

}

5. Add the following code to resolve a list of group names that are attached to the ticket on the ticket when authenticating the user. // when Ticket Was Created, The UserData Property Was Assigned A

// pipe delimited string of group name.

String [] groups = authticket.userdata.split (new char [] {'|'});

6. Add the following code to create a GenericIdentity object and a genericprincipal object. The previous object is a username of the ticket name, and the latter object contains this identity with the user group list. // Create An Identity Object

GenericIdentity ID = new genericidentity (authticket.name,

"Ldapauthentication");

// this Principal Will Flow Throughout The Request.

GenericPrincipal Principal = New GenericPrincipal (ID, Groups);

// attach the new principal object to the capital httpContext Object

CONTEXT.USER = Principal;

Back to top

Test application

This process uses a web application to request the default.aspx page. You will be redirected to the login page for authentication. After the authentication is successfully authenticated, the browser will be redirected to the Default.aspx page initially requested. This operation extracts and displays a list of groups belonging and displaying authenticated users from the genericprincipal object associated with the current request proposed by the authentication process.

To test an application, perform the following steps:

1. On the Build menu, click Build Solution. 2. In the Solution Explorer, right-click DEFAULT.ASPX, and then click View in Browser. 3. Enter a valid domain name, username, and password, and then click LOG ON. 4. If you have successfully verified, you should be redirected back to DEFAULT.ASPX. The code on this page should display the username of authenticated users. To learn a list of identified users is the group of its members, add the following code at the end of the Application_AuthenticateRequest event handler in the global.aspx.cs file. Response.write ("Groups:" Authticket.userData "
");