Use ASP. NET 2.0 to enhance Website Security

Source: Internet
Author: User
Tags microsoft access database

This article is based on ASP. NET March 2004 in 2.0 community technology preview. All information contained in this document may be changed.

This article discusses:

Enhanced security in ASP. NET 2.0

Server-side Security Control

User and role Database

Form authentication without cookie

This article uses the following technologies:

ASP. NET, Authentication

Content on this page
Promote form Authentication
Getting started
Server-side security controls
Define roles
Password Recovery
Adjust the provider
Widget Adjustment
Member and role Programming
Form authentication without cookie
Some Preventive Measures
Summary

The new security feature is an important improvement in ASP. NET 2.0. These functions include the membership service for Managing User Account databases, the hash password, and the role manager for Managing User role member identities, and five new server-side controls that are easier to implement form authentication. ASP. NET 2.0 also provides a program model that allows you to fully control the implementation of Membership and Role services and cookie-free form authentication. You can also easily perform Web-based local and remote management of user accounts and roles, and gain enhanced control over other non-security-related settings.

Promote form Authentication

Form authentication is one of the most widely used functions in ASP. NET 1.0, because it encapsulates the best practices that are missing from many specific implementations. For example, do you know how many form authentication implementations can protect the integrity of cookies used to store client credencookie? Form authentication not only writes the user name to the cookie, but also adds a message authentication code (a hash value based on the cookie and a secret value only known by the Web server ). This prevents malicious clients from increasing privileges or modifying the name in their cookies to view data of another user. If you pay attention. the various news groups and list servers launched by Web developers. You will understand that people are implementing the same thing over and over again: roles cached in user databases and cookies, controls for capturing user names and passwords, and tools for managing users and roles. ASP. NET groups already provide built-in solutions for almost all of these problems. When studying the initial beta build of ASP. NET 2.0, I was shocked by the fact that it completely reduced the amount of code used to build websites that use form authentication in a manageable manner.

Back to Top

Getting started

When I take you through some experiments, you will see how easy it is to start using these new features. If you have an internal beta version of ASP. NET 2.0 (available for download by MSDN Universal subscribers), you can perform these tests.

First, you must have a virtual directory pointing to an empty directory. Make sure that the ASP. NET auxiliary process has the permission to read, execute, and write to this directory. If you are running Windows 2000 or Windows XP, You need to grant these permissions to the ASPNET local account, and under Windows Server 2003, You need to grant permissions to the Network Service account.

I will use form authentication, so I need to enable it through the web. config file. If I show you how to use ASP. NET 1.1 now, I will show you how to open a text editor and start typing XML manually. However, in ASP. NET 2.0, one of my favorite features is the interactive configuration file editor, which is directly built on the IIS console. You can go to the "ASP. NET tab. Press the "Edit configuration" button to bring up the editor.

Figure1Configuration Editor

Figure 1 shows the new editor. You will see that I have selected form authentication instead of the default option: Windows authentication. Perform the same operation in your own virtual directory. When you use the configuration tool, set the default language of the Web application to C #, because it will save some of the subsequent input for you. The Page Language Default setting is the first drop-down option on the Application tab. After applying these changes, you will find the web. config file in the directory with all the settings.

You need to register some users with the Membership service to start, so the first page you write is the page that allows you to add users. This test version provides a server control. With this control, you can use the following three lines of code to implement this page:

<form runat='server'><asp:createuser runat='server'/></form>

However, since I was using the initial internal beta version, I had to use the Membership class to manually write code for this special form. Now, you only need to use the ASPX page shown in Figure 2. I will discuss the Membership class later in this article. Figure 3 shows what you see when you direct your browser to this page. Continue the test. Now add some users and passwords. Your work should be much easier, because it is doing exceptionally well!

Figure3Membership page

After adding a user, check the virtual directory carefully. You should see a new subdirectory named "DATA" with a Microsoft Access database. This is where Membership and Role services store their data by default, but I will show you how to override the default storage mechanism to use SQL Server or your own custom data repository later. It is time to use the security control provided in ASP. NET 2.0.

Back to Top

Server-side security controls

Figure 4 lists the five new security controls provided in ASP. NET 2.0. It is a good idea to start exploring the LoginStatus control. First, create a new ASPX page containing the control. For simplicity, call the new page default. aspx:

<form runat='server'><asp:loginstatus runat='server'/></form>

Point the browser to this page and you should see a Login link. If you view the source code of the result page in the browser, you will see that this hyperlink points to a page named login. aspx, and you have not compiled it. This is a Web page implemented with three lines of code. Therefore, we will continue the experiment and create it now:

<form runat='server'><asp:login runat='server'/></form>

If you have manually implemented form authentication, you will appreciate the three lines of code. In the past, the equivalent Implementation of database search requires two times of code.

Now return to your browser and click the Login link, which will take you to the logon page shown in Figure 5. If you try to log on with an invalid user name or password, an appropriate default error message will pop up. This message does not give attackers too much information. An inexperienced developer will never accidentally send a message back to the user, telling him that he has obtained the correct user name. Please try to guess another password!

Figure5Logon page

Continue with the test. enter a valid user name and password-the user name and password you entered on the adduser. aspx page-you should redirect back to the default. aspx page. Because you do not provide any custom operations for the logon control, by default, it only allows you to log on through form authentication, this means that your browser now has an encrypted cookie that stores the user name.

Since you have redirected back to the default. aspx page, what are the differences? The logon Status control should now display Logout instead of Login. Because the form authentication cookie is sent together with the request, FormsAuthenticationModule creates an authenticated user subject and associates it with the request context. The logon Status control will notice this situation and change to allow you to log out. Log out and log on again to view the job.

Now, let's add some code to the default. aspx page:

Refresh this page and you should see the user name you used to log on. Note: the basic object of a user is of the GenericPrincipal type. This is the form that FormsAuthenticationModule represents the user. Once you start Role Manager, you will notice this type change, because when enabled, the new RoleManagerModule replaces the User Generated by FormsAuthentication using its own type.

Now, let's add a LoginView control to the default. aspx page to display the content that can be changed based on the user's logon. The simplest way to use this control is to provide two content blocks: one for anonymous requests (before the user logs on) and the other for identity authentication requests (after the user logs on ):

<asp:loginview runat='server'><anonymoustemplate>

When you log on or log out, you should see that the text in the LoginView control has changed, as we expected. This is a very simple idea, but it does make your code much clearer.

Back to Top

Define roles

I have created a simple page that allows you to use Role Manager to add users to roles, but before you can use it, you need to enable Role Manager for your application. Go back to the configuration tool and find the Authentication tab. Select the check box marked with "Role management enabled" and apply this change.

The Code on the addrole. aspx page is displayed in figure 6, while Figure 7 shows the appearance of the form. Place this page in your virtual directory and point your browser to it, so that you can add some roles. Specify a user name (the user name you added in the adduser. aspx form) and a role name, and then click the button to add the user to the role. The code first adds a role (if it does not exist) and then adds the user to the role. Behind the scenes, Role Manager will track these Role mappings in the same Microsoft Access database used by the Membership service, but this is actually a coincidence. Role Manager can store its data in SQL Server or any other storage without having to use the same mechanism as the Membership service. To support this, Membership and Role Manager provide different models.

Figure7Add role

If you have been in ASP. NET, you will appreciate the built-in Role Manager, because you no longer have to become ASP to Implement Role-based security. NET. Once you have added some roles, you can return to default. aspx and use the LoginView control to do something interesting. Add another part after the element:

<rolegroups><asp:rolegroup roles='ForumModerators'><contenttemplate>

You may not select the same role as me, so you will need to replace my role name with your own role name, and adjust the content to make it suitable for the role. Once you have completed, you can use different user accounts in different roles to log on to your new page, and observe how the page content changes when the role changes. NOTE: If both role groups match the user's role, the first matched role group is always displayed (from top to bottom ).

Although this is not new, remember that you can test the role programmatically through User. IsInRole. Note that you can use the section in web. config to allow or deny access to each page, as shown below:

<authorization><deny users='?'/><allow roles='ForumModerators'/><deny users='*'/></authorization>

The first item tells ASP. NET to prohibit any request without authentication (force authentication ). The second and third items ensure that only ForumModerators can access the contents in the directory tree where the web. config file resides. Remember, the authorization part can be used for the web. config file in the subdirectory or the <location/> element to control access to individual files.

Back to Top

Password Recovery

In this demonstration, I have not displayed the password restoration control for you, because you need to carefully consider its usage. You may know the role of this control: it allows the user to send his password to him by email. Before deciding to send a plaintext password to a user by email, you need to perform risk assessment.

In fact, if you place this control on a page of your existing site, it will not work, because by default, the Membership service will refuse to disclose the plaintext password. It is impossible even if it thinks so, because by default, it only stores the one-way hash value of the password instead of the password itself. When a password is required, the Membership service will hash the submitted password and compare the hash value with its copy. If you want to restore the plaintext password, you can reconfigure the Membership provider to store the password in encrypted form. In this case, the Membership provider uses <machineKey/> to encrypt the password. In this way, the password can be decrypted and sent to the user by email.

If you store the hash password (this is a good idea), you need to prepare a replacement method to authenticate the user. You cannot send the password to the user by email, but if you have asked a few questions in advance, for example, "What is your favorite pet name? ", You can use these answers to authenticate the user and allow him to send you a new password. However, the Membership service does not support retaining questions and answers for each user. It is only used to determine whether a password can be sent via email, so it cannot be used with a hash password. In my opinion, this will take some work.

InBuilding Secure SoftwareOn page 95 (Addison-Wesley, 2002), Vipers and McGraw proposed a password reset model through Q &. This model requires a collection of hundreds of questions. When a user sets her account for the first time, it randomly picks out a group of questions to ask the user. If the user requests to reset the password, you can ask her some of these questions. This requires her to answer many questions correctly in order to continue the operation. If you have successfully answered all the questions, you can select a new set of random questions instead of the previous questions.

Back to Top

Adjust the provider

So far, I have used the default settings to keep it simple, but you need to adjust these settings to suit your environment. For example, if you want the Membership service to store its data in SQL Server, you should select AspNetSqlProvider instead of the default AspNetAccessProvider. This setting is on the Authentication page of the Configuration tool.

But what if you already have an existing user database to be integrated? It certainly does not have the tables and columns required by AspNetSqlProvider. What should I do if it is installed on an AS/400 server or Oracle? Fortunately, both the Membership and Role Manager systems are built on a layered model and I have shown this model in figure 8. You can extend the definition of the abstract MembershipProvider class in the System. Web. Security namespace to completely replace Membership data storage. Similarly, you can extend RoleProvider to replace Role Manager data storage. Rob Howard discussed the Provider Model in more detail in his "'nothin' But ASP. NET" column.

Figure8Provider Model

Indeed, using existing providers is the easiest. In the initial test, there were two models. It works in concert with the Access database. As you can see, it runs exceptionally well. The other is the SQL Server Provider I mentioned earlier. To the beta version, you should also verify the user's Membership provider for Active Directory and find the Role's Role provider from the Authorization Manager.

Even if you select a built-in provider, You can adjust its behavior in web. config. Figure 9 shows the provider settings of the SQL Server Membership provider. Note the passwordFormat settings. You can select among the three options: Hashed (default), Encrypted, and Clear. Then, you can use the enablePasswordRetrieval and requiresQuestionAndAnswer attributes to select a password recovery policy. Of course, if you choose to use a hash password, you must set enablePasswordRetrieval to false. Otherwise, you can ask the user to answer a question before the system sends his password via email.

Figure9Provider settings

The database connection string is directly referenced instead of stored in your web. config file. Note that this attribute is called connectionStringName and points to the machine. config section specifically designed to store the connection string. It is a good idea to save the connection string outside the web. config file, especially when you have to use a password instead of using integrated authentication. ASP. NET 2.0 supports XML encryption on sensitive parts of the configuration file, which is a convenient feature for connection strings in machine. config.

Role Manager can be configured to use cookies or URL munging, And the Role can be cached in cookies to reduce the number of round-trips to the Role database. This cache is intelligent: if the number of cache roles starts to increase, the Role Manager caches recently used roles in the cookie, and dynamically searches for the least used roles. This feature may be triggered by the need to use limited storage space to support mobile devices.

You can also adjust many other settings, but I am going to leave them for your own research. At the same time, let's take a look at how to adjust the previously used server-side security controls.

Back to Top

Widget Adjustment

Using three lines of code to create a logon page is very simple, but in general, you need to customize the logon control to suit your applications. Figure 10 shows some code that you can use to replace the simple logon page created previously. In addition, you can use the properties that you expect the Web Control to have to modify the appearance of these controls. With theme support in ASP. NET 2.0, you do not have to change the code to maintain a consistent appearance throughout the website.

An interesting feature of the logon control is that it does not have to be fixed on its own page as I did in this example. Instead, you can use it as part of the home page so that it will always appear in the blank area of the page. Once a user logs on, you don't actually want to see it any more. Therefore, by default, it disappears when it detects that the authenticated user already exists. You can adjust this behavior through the VisibleWhenLoggedIn attribute. This is an example where developers use ASP. NET 1.1 to manually implement this function. Now it is built in ASP. NET 2.0.

Other controls have similar options. For example, if you want to display a nice button for user Login or logout, you can set the Login (Out) ImageUrl attribute on the logon Status control.

To learn how it works, you can use the Visual Studio 2005 Project Wizard to create an Internet website. This wizard is displayed only when you import the "Web. vssettings" IDE setting file to Visual Studio. You can do this through the Tools-Import/Export Settings dialog box. This wizard includes all the features mentioned so far, and provides rich UI customization to get the appearance and features you desire for a new website.

Back to Top

Member and role Programming

If you want to stay away from the server-side security control, you 'd better know that you can also directly use the class that implements this advanced function. To learn the programming models of these services, You need to analyze two main classes: Membership and Roles. Due to the limited length of the article, I cannot describe them in detail here, but some of the details will definitely change in the process of developing the product to the final version. However, let me try it out first.

From the Membership class, you can create and manage users. Each user is represented by an instance of the MembershipUser class. This class indicates the user configuration file, including attributes such as Email, CreationDate, and PasswordQuestion. When you create and update these user configuration files, you can use the Membership class to do this because it is a hierarchical model, the location and method of storing the configuration file are hidden (see figure 8 ). This class provides a way to change the user password and reset the password to a computer-generated random password. This is a timestamp that tracks user activity, to maintain the number of current users (you can obtain this number by calling the GetNumberOfUsersOnline method in the Membership class ).

To verify a user password, you only need to call the ValidateUser method in the Membership class and input the user name and password. The basic provider will be responsible for all necessary password hashing and decryption. If you forget the user name, you can ask him to provide an email address and send it to the GetUserNameByEmail method to remind him, but this is not a safe choice.

Back to Top

Form authentication without cookie

One of the most common complaints when I teach ASP. NET form authentication is that it requires cookies. Fortunately, there is no such restriction in ASP. NET 2.0. The element in web. config has a new "cookieless" attribute. You can set this attribute to one of the following four values: UseCookies, UseUri, UseDeviceProfile, or AutoDetect.

UseCookies and UseUri respectively force FormsAuthenticationModule to use cookies or URL munging for all requests. UseDeviceProfile is used to view the browser function to determine which mode to use. Finally, AutoDetect tries to set the cookie. If it fails, it uses URL munging instead. A typical URL is shown below after protection (ellipsis is added by me because these URLs may be long): http://www.acme.com/foo/ (F (Cvc... A1)/default. aspx.

The section in the URL brackets contains the data normally contained in the cookie and will be canceled by the module in the HTTP pipeline. Therefore, if you read the Request from the ASPX page. path attribute, you will not see any additional content in the URL. If you redirect a request, the URL is automatically protected. In other words, this code will (correctly) take you back to the page you are currently viewing (when the URL is properly protected ):

Response.Redirect(Request.Path)

This function should make form authentication more widely implemented. However, as the number of websites that use ASP. NET form authentication increases, more and more attackers attempt to discover vulnerabilities. Therefore, it is important to observe some basic rules.

Back to Top

Some Preventive Measures

Without SSL protection, form authentication is not very powerful. At least your login page should be sent to the user through a secure connection and sent back to the Web server to prevent eavesdroppers from stealing the user's plaintext password. But this is usually not enough. Because of the way cookies work, thieves who steal form authentication cookies have stolen login information and therefore cannot perform replay detection. Remember, cookies are usually sent together with each request, even for simple tasks such as requesting GIF files with buttons on the page. Once stolen, attackers can use this cookie to imitate users. To reduce this risk, you need to greatly shorten cookie timeout, or run the entire part of the website through SSL (or better, the entire network ).

For websites that require high security, I prefer the latter. When people complain that SSL is running slowly, I ask why they don't buy hardware to accelerate it. However, some companies only insist on using SSL on some sites. If this is the case, you can reduce the cookie replay attacks by enabling the requireSSL attribute in the element. This adds the "Secure" attribute to the form authentication cookie, which instructs the browser to send the cookie back to the server only through Secure channels. In other words, it will not be sent together with requests that do not run through SSL. This feature is added to the. NET Framework Version 1.1 and is not unique to ASP. NET 2.0. The new feature in ASP. NET 2.0 is that this countermeasure can also be applied to session cookies:

Because secure cookies are not sent together with requests that do not run through SSL, for pages that can be accessed through the original HTTP, you can be sure that User. Identity. IsAuthenticated returns false each time. In other words, you will not know who is running without SSL on any page. Note that even if you decide to run the entire site through SSL, enabling the requireSSL attribute is indeed a good idea if you accidentally allow access to one or two files through the original HTTP.

As a measure to prevent cross-site scripting attacks, the httpOnlyCookies attribute is very useful; it instructs the browser not to access cookies from scripts. It uses a cookie attribute named HttpOnly. Currently, only the new version of Internet Explorer can recognize it, but this is a good idea and I hope other browser vendors will use it. For more information, see Some Bad News and Some Good News.

Back to Top
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.