Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 29

Protecting a Web Site and Accessing Data with Web Forms

After completing this chapter, you will be able to:

Restrict access to a Web site by using Microsoft ASP.NET Login controls and

Forms-based authentication.

Create Web forms that present data from a database using a GridView control.

Build Web applications that need to display potentially large volumes of data while minimizing resource use.

Update a database from a Web form.

Build applications that can pass data between Web forms.

In the previous two chapters, you have seen how to build a Web site that enables the user to enter information and validate the data that was entered. You’ve also seen in earlier chapters how to build a non-Web-based application that displays and updates data from a database.

In this chapter, you’ll learn about creating Web applications that display data from a database and that can update the database with any changes made by the user. You will see how to do this in an efficient manner that minimizes use of shared resources, such as the network and the database.

Security is always an important issue, especially when building applications that can be accessed over the Internet, when a Web application accesses sensitive resources such as your company’s databases. Therefore, you will start by learning how to configure a Web forms application to use Forms-based security to verify the identity of the user.

Managing Security

Applications built by using the Microsoft .NET Framework have a range of mechanisms available for ensuring that the users who run those applications have the appropriate user rights. Some of the techniques rely on authenticating users based on some form of identifier and password, whereas others are based on the integrated security features of the Microsoft Windows operating system. If you are creating a Web application that will be accessed over the Internet, using Windows security is probably not an option—users are unlikely to be members of any Windows domain recognized by the Web application and might be running

597

598

Part VI Building Web Applications

 

an operating system other than Windows, such as UNIX. Therefore, the best option to use in

 

this environment is Forms-based security.

Understanding Forms-Based Security

With Forms-based security, you can verify the identity of a user by displaying a login form that prompts the user for an ID and a password. After the user has been authenticated, the various Web forms that make up the application can be accessed, and the user’s security credentials can be examined by the code running in any page if additional authorization is needed. (A user might be able to log in to the system but might not have access to every part of the application.)

To use ASP.NET Forms-based security, you must configure the Web application by making some changes to the web.config file, and you must also supply a login form to validate the user. This login form will be displayed whenever the user tries to gain access to any page in the application if the user has not already been validated. The user will be able to proceed to the requested page only if the logic in the login form successfully verifies the user’s identity.

Important To the uninitiated, it might seem that ASP.NET Forms-based security is excessive. It’s not. Don’t be tempted to simply create a login form that acts as an entry point to your application and assume that users will always access your application through it. Browsers can cache forms and URLs locally on users’ computers. Another user might be able to gain access to the browser cache depending on how the computer itself is configured, find the URLs of the sensitive parts of your application, and navigate directly to them, bypassing your login form. You have control over your Web server (hopefully), but you have almost no control over the user’s computer. The ASP.NET Forms-based mechanism is robust, and assuming that your Web server is well protected, it should be adequate for most of your applications.

Implementing Forms-Based Security

In the first set of exercises in this chapter, you will create and configure a Web application that implements Forms-based security. The application will ultimately enable a user to view and modify customer information in the Northwind database.

Create the Northwind Web site

1.Start Microsoft Visual Studio 2008 if it is not already running.

2.If you are using Visual Studio 2008 Professional Edition or Enterprise Edition, on the File menu, point to New, and then click Web Site.

3.If you are using Microsoft Visual Web Developer 2008 Express Edition, on the File menu, click New Web Site.

Chapter 29 Protecting a Web Site and Accessing Data with Web Forms

599

4.In the New Web Site dialog box, click the ASP.NET Web Site template. Select File System in the Location drop-down list box, and specify the \Microsoft Press\Visual CSharp Step By Step\Chapter 29\Northwind folder under your Documents folder. Set the Language to Visual C#, and then click OK.

5.In Solution Explorer, right-click Default.aspx, click Rename, and rename the form to

CustomerData.aspx.

6.Right-click CustomerData.aspx, and click Set As Start Page.

7.In the Code and Text Editor window displaying the HTML source code for the Web form, click the Design button.

8.Using the Toolbox, add a Label control from the Standard category to the Web form. Set the Text property of the label to This form will be implemented later.

In the next exercises, you will build a login form to authenticate the user and configure Forms-based security for the Web application. When configured to use Forms-based security, the ASP.NET runtime will redirect to the login form attempts made by an unauthenticated user to access the application.

Implementing a login form for Forms-based security is such a common task that Microsoft has implemented a set of Login controls to simplify matters. You will use one of these controls now.

Build the login form

1.On the Website menu, click Add New Item.

2.In the Add New Item dialog box, ensure that the Web Form template is selected, and type LoginForm.aspx for the name. Verify that the Language drop-down list box is set to Visual C#, the Place code in separate file check box is selected, and the Select master page check box is cleared, and then click Add to create the form.

The new Web form is created, and the HTML code for the form is displayed in the Code and Text Editor window.

3.Click the Design button to display LoginForm.aspx in the Design View window.

4.In the Properties window, set the Title property of the DOCUMENT object to Northwind Traders – Log In.

5.In the Toolbox, expand the Login category. Add a Login control to the Web form.

The Login control is a composite control that is composed of several labels, two text boxes for the user to type a name and a password, the Remember me next time check

box, and a button to click to log in. You can configure most of these items by using the Properties window for this control, and you can also modify the style of the control.

600

Part VI Building Web Applications

6.In the Common Login Tasks menu displayed by the Login control, click Auto Format on the Login Tasks menu that appears.

Tip If the Common Login Tasks menu is not displayed, click the Login control, and then click the smart tag icon on the top edge of the control, near the right-hand corner.

The Auto Format dialog box appears. You can use this dialog box to change the look and feel of the Login control by selecting a predefined scheme. You can also define your own layout by creating a template using the Convert to Template command on the

Common Login Tasks menu for the Login control.

7.In the Auto Format dialog box, click the Classic scheme, and then click OK. Click the smart tag icon on the Login control to hide the Login Tasks menu.

8.In the Properties window, change the properties of the Login control by using the values in the following table.

Property

Value

DisplayRememberMe

False

 

 

FailureText

Invalid User Name or Password. Please enter a valid User

 

Name and Password.

 

 

TitleText

Northwind Traders – Log In

 

 

DestinationPageUrl

~/CustomerData.aspx

 

 

The Login control should look like this:

When the user clicks the Log In button, the user must be authenticated. If the user name

and password are valid, the user should be allowed to proceed to the form specified by the DestinationPageUrl property; otherwise, the error message stored in the FailureText property of the Login control should be displayed and the user prompted to log in again. How do you

perform these tasks? You have at least two options:

Write code that handles the Authenticate event for the Login control. This event is

raised whenever the user clicks the Log In button. You can examine the values in the UserName and Password properties, and if they are valid, allow the user to proceed to the page identified by the DestinationPageUrl property. This strategy is highly customi-

zable but requires that you maintain your own secure list of user names and passwords to authenticate against.

Chapter 29 Protecting a Web Site and Accessing Data with Web Forms

601

Use the built-in features of Visual Studio 2008 with the ASP.NET Web Site Administration Tool to manage user names and passwords, and let the Login control perform its default processing to validate users when the user clicks the Log In button. The ASP.NET Web Site Administration Tool maintains its own database of user names and passwords, and it provides a wizard to help you add users to your Web site.

You will use the second option in the following exercise. (You can investigate the first option on your own time.)

Configure Web site security, and activate Forms-based security

1.On the Website menu, click ASP.NET Configuration.

The ASP.NET Configuration command opens Windows Internet Explorer and starts a Web application called the ASP.NET Web Site Administration Tool, which uses its own instance of the ASP.NET Development Server, independent from your Web application.

By using this tool, you can add and manage users for your Web site, specify application settings that you want to be stored in the application configuration file, and specify how security information such as user names and passwords are stored. By default, the ASP.NET Web Site Administration Tool stores security information in a local Microsoft SQL Server database called ASPNETDB.MDF that it creates in the App_Data folder of your Web site. You can configure the ASP.NET Web Site Administration Tool to store security information elsewhere, but that is beyond the scope of this book.

2. In the ASP.NET Web Site Administration Tool, click the Security tab.

602 Part VI Building Web Applications

The Security page appears. You can use this page to manage users, specify the authentication mechanism that the Web site uses, define roles for users (roles are a convenient mechanism for assigning rights to groups of users), and specify access rules for controlling access to the Web site.

Note The first time you click the Security tab, the ASP.NET Web Site Administrator Tool creates the ASPNETDB.MDF database, so it might take a little time for Internet Explorer to display the next page.

3.In the Users section, click the Select authentication type link.

A new page appears, asking how users will access your Web site. You have two options available: From the internet and From a local network. The From a local network option is selected by default. This option configures the Web site to use Windows authentication; all users must be members of a Windows domain that your Web site can access.

The Northwind Web site will be available over the Internet, so this option is probably not very useful.

4.Click From the internet, and then click Done.

This option configures the application to use Forms-based security. You will make use of the login form you created in the preceding exercise to prompt the user for a name and password.

You return to the Security page.

5.In the Users section, notice that the number of existing users that can access your Web site is currently zero. Click the Create User link.

6.In the Create User page, add a new user with the values shown in the following table.

Prompt

Response

User Name

John

 

 

Password

Pa$$w9rd

 

 

Confirm Password

Pa$$w9rd

 

 

E-mail

john@northwindtraders.com

 

 

Security Question

What was the name of your first pet

 

 

Security Answer

Thomas

 

 

Note You must supply values for all fields in this screen. The E-mail, Security Question, and Security Answer fields are used by the PasswordRecovery control to recover or reset a user’s password. The PasswordRecovery control is available in the Login category of the Toolbar, and you can add it to a login page to provide assistance to a user who has

forgotten his or her password.

Chapter 29 Protecting a Web Site and Accessing Data with Web Forms

603

7.Ensure that the Active User box is selected, and then click Create User.

The message “Complete. Your account has been successfully created” appears on a new page.

8.Click Continue.

The Create User page reappears so that you can add more users.

9.Click Back to return to the Security page. Verify that the number of existing users is now set to 1.

Note You can use the Manage users link on this page to change the e-mail addresses of

users and add descriptions, and remove existing users. You can let users change their passwords and recover their passwords if they forget them by adding the ChangePassword and PasswordRecovery controls to the login page of the Web site. For more information, see

the topic “Walkthough: Creating a Web Site with Membership and User Login” in the Microsoft Visual Studio 2008 documentation.

10.In the Access Rules section, click Create access rules.

The Add New Access Rule page appears. You use this page to specify which users can access which folders in the Web site.

11.Under Select a directory for this rule, ensure that the Northwind folder is selected by clicking it.

12.Under Rule applies to, ensure that user is selected, and type John.

13.Under Permission, click Allow, and then click OK.

This rule grants John access to the Web site. The Security screen reappears.

14.In the Access Rules section, click Create access rules again.

15.On the Add New Access Rule page, under Select a directory for this rule, ensure that the Northwind folder is selected. Under Rule applies to, click Anonymous users. Under Permission, ensure that Deny is selected, and then click OK.

This rule ensures that users who have not logged in will not be able to access the Web site. The Security screen reappears.

16.Close the Internet Explorer window displaying the ASP.NET Web Site Administration Tool, and return to Visual Studio 2008.

17.Click the Refresh button on the Solution Explorer toolbar.

The database file ASPNETDB.MDF appears in the App_Data folder.

18.Double-click the web.config file in the project folder to display it in the Code and Text Editor window.

604

Part VI Building Web Applications

This file was updated by the ASP.NET Web Site Administration Tool and should contain an <authorization> and an <authentication> element in the <web.config> section that

look like this:

<system.web>

...

<authorization>

<allow users=”John” /> <deny users=”?” />

</authorization>

...

<authentication mode=”Forms” />

...

</system.web>

The <authorization> element specifies the users who are granted and denied

access to the Web site (“?” indicates anonymous users). The mode attribute of the <authentication> element indicates that the Web site uses Forms-based authentication.

19.Modify the <authentication> element, replace the terminating delimiter (/>) with an ordinary closing delimiter (>), and add a <forms> child element, as shown here in bold type. Make sure you add a closing </authentication> element:

<authentication mode=”Forms”>

<forms loginUrl=”LoginForm.aspx” timeout=”5” cookieless=”AutoDetect” protection=”All” />

</authentication>

The <forms> element configures the parameters for Forms-based authentication. The attributes shown here specify that if an unauthenticated user attempts to gain access to any page in the Web site, the user will be redirected to the login page, LoginForm.aspx. If the user is inactive for 5 minutes, she will have to log in again when next accessing a page in the Web site.

In many Web sites that use Forms-based authentication, information about the user is stored in a cookie on the user’s computer. However, most browsers allow users to

specify that they don’t want to use cookies. (Cookies can be abused by malicious Web sites and are frequently considered a security risk.) By inserting cookieless=”AutoDetect”,

you can specify that the Web site can use cookies if the user’s browser has not disabled them; otherwise, the user information is passed back and forth between the Web site and the user’s computer as part of each request. The user information includes the user

name and the password. Obviously, you don’t want this to be clearly visible to everyone. You can use the protection attribute to encrypt this information, which is what this

example does.

20.On the Debug menu, click Start Without Debugging.

Internet Explorer opens. The start page for the application is CustomerData.aspx, but because you have not yet logged in you are directed to LoginForm.aspx instead.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]