How to verify form authentication for Active Directory

xiaoxiao2021-03-06  62

This page Content Target Application Scope How to Use the content summary of this chapter to create a web application for 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 User Group member authentication user identity and creation Form authentication ticket implementation authentication request handler to construct GenericPrincipal object test applications

Target this chapter is:

• Create a web application that uses Form authentication to authenticate the user identity for Active Directory. • Get 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 property.

Back to top Applicable Scope This chapter applies to the following products and technologies:

• Microsoft Windows® XP or Windows 2000 Server (Service Pack 3) and Higher Versions • Active Directory • Microsoft .NET Framework Version 1.0 (Service Pack 2) and later • Microsoft Visual Studio® 1.0 .NET and more High Versions • Microsoft Visual C # ® .NET • Microsoft SQL Server® 2000 (Service Pack 2) and Higher Versions How to use this chapter to learn this chapter content:

• You must have experience using Visual C # .NET and Visual Studio .NET. • You must have experience in developing web applications using 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. 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 Creating a web application with a login page This procedure creates a simple Visual C # web application, which contains a user who can enter a username and password login page, and a name display associated with the current web request and Group member identity information default page.

• 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 a touch of the control 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 - txtusename text box - TXTPASSWORD button Log in BTNLOGON tab LBLERROR 5. Set TXTPassword's TextMode property Set 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 to display the identity name associated with the current web request:

Response.write (httpContext.current.user.Identity.name);

Configuring a web application Form authentication This procedure edits the application's web.config file to configure the application's form authentication.

• Configure form authentication for web applications

1. Use the Solution Explorer to open Web.config. 2. Find Elements and change the MODE attribute to Forms. 3. Add the element to the child element of the Authentication element, and set LoginURL, Name, Timeout, and Path properties as shown below:

4. Add the following element below Element. This will only allow users to access the application through authentication. The LoginURL attribute established for the previous element will redirect to the logon.aspx page without requesting requests.

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 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 box. 11. Click OK, then click "OK" to close the Properties dialog. 12. Return to Visual Studio .NET, add the element below the element in Web.config, and set the ImperSonate property to True. This will make the ASP.NET simulate the previously specified anonymous account.

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 Developing an LDAP authentication code to find a new helper class in the Active Directory to add a new helper 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 to the top of LDaPAUThentication.cs:

Using system.text; using system.directoryServices;

4. Rename the existing namespace as FormSauthad. 5. Add two private strings to the LDaPAuthentication class: a LDAP path that saves Active Directory and the other 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 @ "/" username; DirectoryEntry entry = new DirectoryEntry (_path, domainAndUsername, pwd); try {// to bind to native AdsObject Forced 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;

Develop LDAP group retrieval code to find the user's group member identity This process extends the LDaPAuthentication class, provides a getGroups method to retrieve the current user's group. 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.PropertiesToLoad.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

Verifying User Identity and Creating Form authentication ticket This procedure enables 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. Add the following USING statement below the existing USING statement at the top of the file. 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 to your LDAP directory server. / Contacts your network administrator to get a valid path. String adpath = "ldap: //yourcompanyname.com/dc=yourcompanyname, dc=com"; ldapauthentication adAuth = new ldapauthentication (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 the group list. 4. Encrypt tickets. 5. Create new cookies with encrypted tickets. 6. Add the cookie to the cookie list that is 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 FormsAuthenticationTicket 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 as data. Httpcookie authcookie = new httpcookie (formsauthentication.formie (formsauthentication.formet); // Add the cookie to the outgoing cookie collection. Response.cookies.add (AuthCookie); // Redirect the user to the initial request page response.Redirect (txtusername.text, false);} else {lblerror.text = "Authentication failed, check users Name and password. ";}} Catch (exception ex) {lblerror.text =" authentication error. " Ex.Message;

Implement the authentication request handler to construct the GenericPrincipal object this process to implement the Application_AuthenticateRequest event handler in Global.asax and create a genericprincipal object for the current authenticated user. 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. Locate Application_AuthenticateRequest event handler and add the following code to set cookie transmitted together with the request acquired from the cookie contains encrypted FormsAuthenticationTicket of: extracting // Forms Authentication cookiestring cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request .Cookies [cookiename];

IF (null == authcookie) {// No authentication cookie return;}

4. Add the following code to extract FormSauthenticationalTicket from the cookie and decrypt:

FormsauthenticationalTicket Autovet = NULL; try {authticket = formsauthentication.decrypt (authcookie.value);} catch (exception ex) {// Record abnormal situation details (for simplicity, omitted) Return;}

IF (null == authticket) {// Unable to decrypt cookie. Return;}

5. Add the following code, resolve the list of group names separated by the tag that the user is initially attached to the ticket after authentication:

// After creating a ticket, specify a group name string separated by a pipe symbol for the UserData property. 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 ID and the user group list:

// Create a logo object genericIndentity ID = new genericIdentity (authticket.name, "ldaPAuthentication");

// The body will pass throughout the request. GenericPrincipal Principal = New GenericPrincipal (ID, groups); // Additional new subject objects to current HTTPCONTEXT objects context.user = principal;

Test Application This procedure uses a 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 initial 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" and click "View in your browser". 3. Enter a valid domain name, username, 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 "
"); from MSDN

转载请注明原文地址:https://www.9cbs.com/read-84301.html

New Post(0)