What is the headache? Please use ASP.NET 2.0! (Turn MSDN)

zhaozj2021-02-16  91

This article is based on the ASP.NET 2.0 content in the community technology preview in March 2004. All information contained in the text may change.

This article discusses:

• Security enhanced in ASP.NET 2.0? Server-side security control? Users and role databases? Form authentication without cookie

This article uses the following technique:

ASP.NET, authentication

This page

Advancing Form Authentication Getting Started Server Security Control Defining Role Paradox Recovery Adjustment Provider Control Adjusting Members and Role Programming No Cookie Form authentication Some precautions Summary

The new security function is an important improvement in ASP.NET 2.0. These features include the role manager of the Manage User Account Database, Hash Code, Manage User Role Membership, and five new server-side controls that can be more easily implemented. ASP.NET 2.0 also provides a provider model that enables you to fully control MemberShip and Role services and implementation without cookie form authentication. You can also easily perform web-based local and remote management for user accounts and characters, and enhanced control over other non-security related settings.

Promote form authentication

Form authentication is one of the most widely used features in ASP.NET 1.0, as it encapsulates the best practices in which many specific implementations are lacking. For example, you know how many form authentication implementations can protect the cookie integrity of client credentials? Form authentication not only writes the username into the cookie, but also adds a message authentication code (a hash value based on the cookie and the secret value known to only the web server). This makes the malicious client not to improve the privilege or by modifying the names in its cookie to view the data of another user. If you pay attention to the various newsgroups and list servers introduced by the .NET web developer, you will learn that people are achieving the same thing over again: user database, cached roles, capture user names and password controls, management Tools for users and roles. The ASP.NET group has provided built-in solutions for almost all of these issues. When studying the initial test version of ASP.NET 2.0, I feel shocked, it completely reduces the number of code used to build a list of information that uses form authentication in manageable ways.

Back to top

getting Started

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

First, there is a need to have a virtual directory to the empty directory. Must ensure that the ASP.NET assist process has permission to read, execute, and write 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 will need to grant your permissions to the Network Service account.

I will use the form authentication, so I need to enable it through the web.config file. If I present to you now how to use ASP.NET 1.1, I will tell you to open a text editor and start typing XML. But in ASP.NET 2.0, one of my favorite features is the interactive profile editor, which is directly built from the IIS Management Console, and you can find it on the "ASP.NET" tab of the virtual directory. . Press "Edit Configuration" to press New, the editor will pop up.

Figure 1 Configuration Editor

Figure 1 shows this new editor. You will see that I chose the form authentication instead of the default option: Windows authentication. Do the same operation in your own virtual directory. When using the configuration tool, set the default language of the web application to C # because it will save some of the inputs that need to be made back. Page Language Default Settings is the first drop-down option on the Application tab. After applying these changes, you will find the web.config file in the directory and have all settings. You need to register some users to the Membership service to start, so the first page you wrote is to allow you to add the user's page. A server control is provided in this beta, you can use the following three lines of code to implement this page:

However, since I used the original internal beta, I have to use the MemberShip class directly to write code for this special form. Now, just use the ASPX page shown in Figure 2, I will discuss the MEMBERSHIP class later. Figure 3 shows what you see when you point your browser to the page. Continue test, now add some users and passwords. Your work should be much easier, because it is better!

Figure 3 MEMBERSHIP page

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

Back to top

Server-side security control

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

Point your browser to this page and you should see a login link. If you view the source code for the result page in your browser, you will see this hyperlink to point to a page called Login.aspx, and you have not written it. This is another web page that implements three-line code, so we will continue the test and now create it:

If you have manually implemented form authentication, you will appreciate these three lines of code. In the past, the equivalent implementation of the implementation of the database lookup requires twice the number of code.

Go back to your browser now and click the Login link, which will take you to the login page shown in Figure 5. Try to log in with an invalid username or password, you can find that a proper default error message will pop up. This message will not give an attacker too much information. And an unintended developer will never be inadvertently sent back to a message to the user, tell him that the correct username, please try to guess another password!

Figure 5 Login page

Continue test, type a valid username and password - the username and password you entered in front of the AddUser.aspx Page page - you should re-direction back to the DEFAULT.ASPX page. Since you don't provide any custom operations for the login control, it is only possible to log in by the form authentication, which means your browser now has a cookie that stores the username. Since you have already redirected back to the DEFAULT.ASPX page, is you different? Log in status control should now display logout instead of login. Because the form authentication cookie is sent with the request, FormSauthenticationModule creates an authenticated user body and associates it with the context of the request. The login status control will notice this and change to allow you to log out. Try to log out and log in to see this work.

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

user name: <% = user.Identity.Name%>

user type: <% = user.gettype ()%>

Refresh this page, you should see the username you use to log in. Note that the basic object of the user is the genericprincipal type, which is the way for FormSAuthenticationModule represents the user. Once you start the Role Manager, you will notice this type of change, because when you enable, the new roleManagerModule replaces the user generated by the FormsAuthentication using its own type.

Now let's add a LoginView control to the Default.aspx page to display content that can be changed according to the user's login. The easiest way to use this control is to provide two content blocks: one for anonymous requests (before users log in), another for authentication requests (after logging in):

if you see, you've not yet logged in!

Welcome to My Website, !

When you log in or log out, you should see that the text in the LoginView control has changed, just as we expect. This is a very simple idea, but it really makes your code a lot.

Back to top

Define role

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

The code of the AddRole.aspx page is displayed in Figure 6, and Figure 7 shows the appearance of the form. Place this page in your virtual directory and point your browser to it so you can add some characters. Specify a username (you can add a user name to the AddUser.aspx form) and a role name, then press New to add the user to the role. The code first adds a role (if it does not exist), then add the user to the role. After the scene, Role Manager tracks these role mappings in the same Microsoft Access database used by the Membership service, but this is actually just coincidence. Role Manager can store its data in SQL Server or any other store and do not have to use the same mechanism as the MEMBERSHIP service. To support this, the provider model of Membership and Role Manager is completely different. Figure 7 Add a role

If you have implemented a custom role in ASP.NET, you appreciate the built-in Role Manager, because you don't have to achieve the owner of the ASP.NET HTTP pipe in order to achieve role-based security. Once you have added some roles, you can go back to Default.aspx and you can use the LoginView control to do some interesting things. Add another part after the element:

Controls for forum moderators go here .

Welcome, Friend!

You may not have the same role as I, so you will need to use your own role name to replace my role name and adjust the content that makes it suitable for roles. Once you have done it, you can check your new page by logging in with different user accounts in different roles, and observing how the contents of the page when the role changes. Note that if the two role groups match the role of the user, the first matching role group (from top to bottom) is always displayed.

Although this is not fresh, please remember that you can print the role through user.isinrole. It is also important to keep in mind that you can use the part of Web.config to allow or refuse to access each page as follows:

The first item tells the ASP.NET to prohibit incoming requests that have not been authenticated (forced authentication). The second and third items ensure that only ForumModerators can access the contents of the directory tree reside in the web.config file. Remember, the authorization section can be used in the Web.config file in the subdirectory, or it can be used for the element to control access to individual files. Back to top

Password recovery

In this introduction demonstration, I haven't shown a password recovery control to you because it needs to be carefully considered for it. You may know the role of this control: it allows the user to request his password to him via email. You need to do some risk assessments before deciding to send a plain text password to the user via email.

In fact, if you put this control on a page of your existing site, it will not work because of the default, the Membership service will refuse public plain text passwords. Even if it wants to be, it is impossible, because it only stores the password unidirection hash value without storing the password itself. When the password is required to verify the password, the MEMBERSHIP service will have the password submitted by the hash and compare the hash value with its copy. If you want to restore the plain text password, you can reconfigure the Membership provider to store your password in encrypted form. In this case, the MEMBERSHIP provider will encrypt the password using . This can decrypt the password and sent to the user via email.

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

On 95 pages of Building Secure Software (Addison-Wesley, 2002), Viega and McGRAW have proposed a good model for resetting the password by questioning. This model requires a collection of hundreds of questions. When the user sets her account for the first time, it will randomly pick a group of questions to ask the user. If the user requests to reset the password, you can ask some of her problems. This requires her to answer many questions correctly in order to continue operation. If the user has successfully answered all questions, you can also choose a new set of random issues instead of the previously used issues.

Back to top

Adjustment provider

So far, I deliberately use the default settings to keep it simple, but you need to adjust these settings to fit your own 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 the Authentication page of the configuration tool.

But what should I do if you already have an existing user database that needs to be integrated? It does not have a table and column that AspnetSqlProvider needs. Also, what should I do if it is on the AS / 400 server or Oracle installation? Fortunately, both Membership and Role Manager systems are built on the hierarchy model, I have shown this model in Figure 8. You can define the Abstract MembershipProvider class in the System.Web.Security namespace by extended definitions, is fully replaced by Membership data storage. Similarly, you can replace Role Manager data stored by extending roleprovider. Rob Howard discusses the provider model in more detail in his "'Nothin' But ASP.NET" column. Figure 8 Provider model

Indeed, using an existing provider is the easiest. In the initial beta, there are two models. A synergistic work with the Access database, as you can see, it is better. The other is the SQL Server provider I have previously mentioned. When you go to the beta, you should also verify the user's Membership provider, as well as the Role provider for finding the role from the Authorization Manager.

Even if you have selected a built-in provider, you can also adjust its behavior in Web.config. Figure 9 shows the provider settings for the SQL Server MEMBERSHIP provider. Note PasswordFormat settings, where you can choose between three options: Hashed (default), Encrypted and Clear. You can then select a password recovery policy via the EnablePasswordRetrieval and RequireSquestInSwer properties. Of course, if you choose to use the hash certificate, you must set EnablePasswordRetrieVal to false. Otherwise, you can also ask the user to answer a question problem before the system will send his password via email.

Figure 9 Provider setup

The database connection string is not stored in your web.config file, but directly referenced. Note that this property is called ConnectionstringName, and points to the Machine.config section that is specifically designed to store the connection string. Save the connection string outside the web.config file is a good idea that is especially true when you cannot use the integrated authentication. ASP.NET 2.0 is scheduled to support XML encryption for the sensitive part of the profile, which is a convenient function for the connection string part in Machine.config.

The Role Manager can be configured to use cookies or url munging, and you can cocabulate the role in cookies, thereby reducing the number of round-trip role databases. This cache is intelligent: if the number of cache roles becomes large, Role Manager will cache the most recently used roles in the cookie, and dynamically find the least role. This feature may be excited because there is a need to support mobile devices with a limited storage space.

You can also adjust many other settings, but I am going to leave them to study. At the same time, let us see how to use the server-side security controls that can be used to use.

Back to top

Control adjustment

It is very simple to create a login page with a three-line code, but in general, you need to customize some customizable controls to suit your application. Figure 10 shows some code that you can use these code instead of the simple login page created in front. In addition, you can also use the properties you expect Web controls to modify the appearance of these controls. With the topic support in ASP.NET 2.0, you don't have to change the code to maintain a consistent look throughout the website. A interesting feature of the login control is that it doesn't have to fix it in your own page as I am doing in this example. Instead, you can use it as part of the main page so that it will always appear on the blank of the page. Once the user logs in, I don't want to see it again, so it will disappear when it detects authenticated users already exists. You can adjust this behavior through the visiblewhenLoggedin property. This is an example of developers to manually implement this feature using ASP.NET 1.1, and now it is built in ASP.NET 2.0.

Other controls have similar options. For example, if you want to log in or log out for a user, you can set the login (out) ImageURL property on the login status control.

In order to feel its way of work, you can use the Visual Studio 2005 Item Wizard to create an Internet site. For this article, this wizard is displayed only if you import the "web.vssettings" IDE setting file into Visual Studio. You can do this through the Tools-Import / Export Settings dialog. The wizard includes all functions that are talked here, and provide a rich UI customization to get the look and functions of your new website.

Back to top

Member and role programming

When you want to stay away from the server-side security control, you should also know that you can also use classes that implement this advanced feature. To learn the programming model of these services, you need to analyze two primary classes: Membership and Roles. Due to the space of the article, I can't introduce them here, and some of the details will definitely change in the product to the final version, but let me first take you.

From the MEMBERSHIP class, you can create and manage users, where each user is represented by an instance of the MemberShipuser class. This class represents a user profile, including attributes such as email, creeiondate, passwordQuestion. When you create and update these user profiles, you can do this through the Membership class because it is a hierarchical model, hiding details of the location and method of the storage configuration file (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 the user's activity, thereby maintaining the number of current users (you can call GetNumberofusersonline in the MEMBERSHIP class) Methods to get this number).

To verify a user password, simply call the ValidateUser method in the Membership class and pass it into the username and password. The basic provider will be responsible for all necessary password hash and decryption. If the user forgetting its username, you can remind him by requesting him to provide an email address and transfer it to the getUserNameByemail method, but this is not a safe choice.

Back to top

Form authentication without cookie

One of the most complaints encountered when I teach the ASP.NET form authentication is that it needs a cookie. Fortunately, there is no such limit in ASP.NET 2.0. There is a new "cookieless" attribute on the element in web.config. You can set this property to one of the following four values: usecookies, useuri, usdeviceprofile, or autodtect. Usecookies and USEURI are mandatory to require FormsAuthenticationModule to use cookies or url mungings for all requests. UseDeviceProfile is used to view the browser feature to determine which mode is used. Finally, AutodteTect will try to set up cookies, and if it fails, it will be changed to use URL Munging. Typical URLs are as follows after protection (the omitted number is what I added, because these URLs may be very long): http://www.acme.com/foo/ (f (cvc ... a1)) /Default.aspx .

The part in the URL brackets contains the cookie usually included data, and will be canceled by modules in the HTTP pipe, so if you read the request.path property from the ASPX page, you will not see any excess content in the URL. If you redirect requests, the URL will automatically protected. In other words, this code will (correctly) take you back to your currently viewing page (in the case where the URL is properly protected):

Response.Redirect (Request.Path)

This feature should make the form authentication to a large extensive implementation. However, as the website using the ASP.NET form authentication is increasing, more and more attackers will try to find weaknesses, so abide by some basic rules is a good attention.

Back to top

Some precautions

If it is not protected by a secure socket layer (SSL), the form authentication is not very powerful. At least you should send your login page to the user and transfer to the web server via a secure connection to prevent the eavesdropper from stealing the user's plain text password. But usually don't do it. Since the cookies work mode, stealing the form authentication cookie's thief has steal the login information, so it cannot achieve replay detection. Remember, cookie is usually sent with each request, and even a simple thing to make a GIF file like a button request page. Once theft, the attacker can use this cookie to imitate the user. To reduce this risk, you need to get great shortage timeout, or run the website throughout the website (or better, the entire network).

For sites that require high security, I am more willing to choose the latter, when people complain that SSL is slow, I ask them why they don't buy hardware to speed up. However, some companies only adhere to the SSL in some sites. If you are this, you can reduce these cookie replay attacks by enabling the Requiressl property in your element. This will add the "Secure" property to the Form authentication cookie, which indicates that the browser should send the cookie back to the server only via the secure channel. In other words, it does not send it with a request that does not run through SSL. This feature is increasing in the 1.1 version of the .NET framework, so it is not unique to ASP.NET 2.0. New feature in ASP.NET 2.0 is that this countermeasure can also be applied to session cookies:

Since secure cookie does not send a request that does not run through SSL, you can affirm user.Identity.isauthenticated Top will return false. In other words, you will not know who is the user who does not run over the SSL on any page. Note that even if you decide to run the entire site through SSL, enabling the Requiressl property is really a good idea if you have allowed access to one or two files through the original HTTP.

As a measure of preventing cross-site scripting attacks, HttponlyCookies properties are very useful; it indicates that the browser should not access cookies from scripts. It uses a cookie property named httponly, currently only the new version of Internet Explorer can identify it, but this is a very good idea, I hope other browser vendors use it. To learn more, see Some Bad News and some Good News.

Back to top

summary

ASP.NET 2.0 provides important security advantages in terms of using form authentication. By providing the user profile reserve and support for roles, the form authentication will come out of the view of ASP.NET, and is more widely realized. It's hard to go back to me to use the old version!

Keith Brown is an independent consultant specializing in application security. Keith is scheduled to be awarded to developor, in which he is responsible for safety courses. He combined with people with Programming Windows Security (Addison-Wesley, 2000) and is writing a new book related to .NET security. You can read it online, the URL is: http://www.pluralsight.com/keith.

This article is taken from MSDN Magazine 2004 June 2004. This magazine can be purchased through newsstands from all over the country or subscribe.

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

New Post(0)