With the ASP.NET form single authentication, users can indicate their identity by entering credentials (usernames and passwords) on the web form. After receiving these credentials, the web application checks the user name and password to verify the user's identity.
This "How to Do" This section describes how to verify the user by using the Lightweight Directory Access Protocol (LDAP). Here also describes how to retrieve the security groups and distribution groups belong to the user; how to store such information in the GenericPrincipal object, and how to store it in the httpcontext.current.user property (passing to the ASP.NET web application with the request) in). It can then be used for .NET based on role-based authorization.
demand
The following items describe the recommended hardware, software, network infrastructure, skills, and knowledge, and the service pack you need.
● Microsoft WINDOWS? 2000 operating system
● Microsoft Visual Studio? Net development system
The process of "how to do" also requires you to have relevant knowledge of Microsoft Visual C #? Development tools.
to sum up
"How to do" includes the following procedure:
1. Create a web application with a login page
2. Configure format authentication for web applications
3. Develop LDAP authentication code to find users in Active Directory
4. Develop the LDAP group retrieval code to find the user's group member identity
5. Verify the user's identity and create a table single authentication ticket
6. Implement authentication request handler to construct genericprincipal objects
7. Test application
1. Create a web application with a login page
This process creates a simple C # web application that contains a login page (the user can enter the username and password in it) and a default page (displays the identity name and group member identity information associated with the current web request).
u Create a web application with a login page
1. Start Visual Studio .NET and create a new 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
label
domain name:
- label
username:
- label
password
- Text box
- TXTDOMAINNAME
Text box
- TXTUSERNAME
Text box
- TXTPASSWORD
Button
log in
Btnlogon
label
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, enter DEFAULT.ASPX, and then click Open.
8. In the Solution Explorer, right-click DEFAULT.ASPX, and then click Set to Start Page.
9. Double-click DEFAULT.ASPX to display the page load event handler.
10. 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);
2. Configure format authentication for web applications
This process edits the application's web.config file to configure the form of the application.
u Configure format verification for web applications
1. Use the Solution Explorer to open Web.config.
2. Find
3. Add the
forms>
authentication>
4. Add the following
authorization>
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 click Properties.
8. Click the Directory Security tab and click the Edit button in the Anonymous Access and Verification Control group.
9. Select the "Anonymous Access" check box and clear the "Allow IIS Control Password" checkbox.
10. Because the default anonymous account IUSR_MACHINE does not access the Active Directory permissions, create a new account with the least privilege, and then enter the details of the account in the Authentication Method dialog box.
11. Click OK, then click OK to close the Properties dialog.
12. Return to Visual Studio .NET, then add
Since this configuration is used, all application requests are running in the security context of the configured anonymous account. Users will provide credentials through a web form to perform Active Directory authentication, but the account used to access the Active Directory is an anonymous account configured.
3. Develop LDAP authentication code to find users in Active Directory
This process adds a new helper class to a web application to encapsulate LDAP code. This class initially provides the ISAUTHENTICATED method to verify the domain, username, and password provided for Active Directory user objects.
u Develop an LDAP authentication code to find users in Active Directory 1. Add new C # class files named ldaPAUThentication.cs.
2. Add a reference to the System.DirectoryServices.dll assembly.
3. Add the following USING statement to the top of the ldaPAPAUThentication.cs.
Using system.text;
Using system.collections;
Using System.directoryServices;
4. Rename the existing namespace to Formsauthad.
5. Add two dedicated strings to the LDAPAUThentication class; a LDAP path for saving to Active Directory, and saves the Filter Properties for Searching Active Directory.
Private string _path;
Private string _filterattribute;
6. Adding a public constructor that can be used to initialize the Active Directory path.
Public ldapauthentication (String Path)
{
_path = path;
}
7. Add the following to use the domain name, username, and password as a parameter and return BOOL's ISAUThenticated method to indicate whether there is a user with a matching password in Active Directory. This method initially tried to use the provided credentials to bind to Active Directory. If this is successful, the method uses the DirectorySearcher host hosted class to search for the specified user object. If found, update _path members to point to the user object, and use the general name property of the user object to update the _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 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;
}
4. Develop the LDAP group retrieval code to find the user's group member identity
This procedure extends the LDAPAUThentication class to provide a getGroups method that retrieves the list of groups where the current user is located. The getGroups method returns a list of lists to the string separated by the pipeline (as shown below).
"Group1 | Group2 | Group3 |"
u Develop the LDAP group search code to find the user's group member identity
1. 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 (); } 5. Verify the user's identity and create a table single authentication ticket This process implements the BTNLogon_Click event handler to verify the identity of the user. For authenticated users, you will then create a form that contains a list of user groups verification tickets. Then, redirect the user to the original page they requested (before being redirected to the login page). u Verify the user's identity and create a form of authentication ticket 1. Return to the Logon.aspx form and double-click the "Login" button to create an empty Bartnlogon_Click event handler. 2. In the existing USING statement at the top of the file, add the following Using statement. It 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 below below). Remember to change the path to point 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: a. Active Directory authentication for the caller. b. Retrieve the group list where the user is located. c. Create a FormsAuthenticationalTicket containing the group list. d. Encrypt the ticket. e. Create a new cookie that contains a plus ticket. f. Add the cookie 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; } 6. Implement authentication request handler to construct genericprincipal objects This process implements the Application_AuthenticateRequest event handler in Global.asax and creates the genericprincipal object to the currently verified user. It will contain a list of users where the user is located, which 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. u Implement authentication request handler to construct GenericPrincipal objects 1. Use the Solution Explorer to open Global.asax.cs. 2. Add the following USING statement to 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 passed with the request. // 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 the group name dacope separation of the user to the ticket when the user initially authenticates. // 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 the genericIdentity object with the user name obtained from the ticket name and create the genericprincipal object containing the identity and 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 current httpContext ObjectContext.user = principal; 7. 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 successful authentication, your browser will be redirected to the DEFAULT.ASPX page that is requested. This will extract and display the group list to which the authenticated user belongs from the genericprincipal object (identity verification process has been associated with the current request). u Test application 1. In the "Build" menu, click Build Solutions. 2. In the Solution Explorer, right-click DEFAULT.ASPX, and then click "View in your browser". 3. Enter a valid domain name, username, and password, and then click Login. 4. If the authentication is successful, you will be redirected back to DEFAULT.ASPX. The code on this page should display the username of authenticated users. To see a list of groups belonging to authenticated users, add the following code to the end of the Application_AuthenticateRequest event handler in the global.aspx.cs file. Response.write ("Groups:" authticket.userdata "
");