Chapter 31. Developing a Login System with ASP.NET

<feature><title>In this chapter</title> </feature>

Web Site Login Systems

There are generally two types of Web sites. One type offers the same information to everyone. The other type offers information that is somehow specific to the person using the Web site. It’s becoming more and more common to see Web sites that fall into the latter category, and because of that, it’s becoming more necessary for Web developers to be able to design a method of allowing users to log into a Web site so they can be uniquely identified.

There are many ways to implement a login system, but almost all of them require a significant amount of code to implement. Not only that, but writing secure code for a login system is difficult because it requires a full understanding of security issues.

Caution

Security should be among your highest priorities when designing a Web application. You should be aware that by adding features such as login functionality, you are exposing yourself to security risks.

If you are going to use ASP.NET 2.0’s login controls in your Web site, I highly recommend that you visit Microsoft’s page on securing the login controls. You can access this page by browsing to http://msdn2.microsoft.com/en-US/library/ms178346 (VS.80).aspx.

Fortunately for you, ASP.NET 2.0 has a full suite of login controls that provide an amazing level of functionality without having to write a single line of code. You’re probably picturing a simple system with a basic username and password implementation. Think again! ASP.NET 2.0 login controls provide you with all the features needed for most applications.

Note

The ASP.NET membership system uses Microsoft SQL Server 2005 Express Edition by default to store users for your Web site. Therefore, to walk through the examples in this chapter, you will need to install Microsoft SQL Server 2005 Express Edition and the Microsoft .NET Framework 2.0.

The easiest way to get everything that you need is to install Microsoft Visual Web Developer Express Edition. As of this writing, it’s free, but it’s also a 344MB download.

You can find Visual Web Developer Express Edition at http://msdn.microsoft.com/vstudio/express/vwd/default.aspx.

Overview of ASP.NET 2.0 Login Controls

Expression Web provides access to all seven ASP.NET 2.0 login controls via the Login section of the ASP.NET controls Toolbox.

Tip

Those of you using Windows XP Home Edition are not excluded from testing the concepts described in this chapter. The ASP.NET Development Server provides a fully supported environment for ASP.NET 2.0, and it will run on any version of Windows XP.

For more information on the ASP.NET Development Server, see “Using the ASP.NET Development Server”, p. 485 (Chapter 27).

The Login Control

The Login control, like most of the other ASP.NET login controls, is simple in appearance but robust in functionality. In its simplest terms, the Login control provides users with textboxes for entering a username and a password, as shown in Figure 31.1. A “Remember Me” checkbox is also provided so that users don’t have to log in on each subsequent visit to your Web site.

The Login control is simple in appearance, but there’s a lot of functionality under the hood.

Figure 31.1. The Login control is simple in appearance, but there’s a lot of functionality under the hood.

The Login control also implements form validation so that users cannot submit a form without supplying both a username and a password.

Figure 31.1 shows the default appearance of the Login control. You can reformat it using CSS styles or by using the AutoFormat option on the Common Login Tasks popup. By choosing one of the six available formatting options, as shown in Figure 31.2, you can quickly change the appearance of the entire control.

You can quickly give the Login control a new look using the AutoFormat dialog.

Figure 31.2. You can quickly give the Login control a new look using the AutoFormat dialog.

Note

The Common Tasks popups for the login controls have an Administer Website link. If you click this link, you’ll be informed that administering the Web site is not supported. If you want to administer the Web site, you’ll need to use the tools provided by ASP.NET itself.

Because the Login control is a single control, you cannot move the elements in the control by default. If you want to rearrange the controls that make up the Login control, you’ll need to convert the control to a template—, which is referred to as a templated control. By converting the control to a template, you will have access to all the constituent controls that make up the Login control. All the functionality remains the same.

To convert the Login control to a template, click the button at the upper right of the control to access the Common Login Tasks popup and click the Convert to Template link. After you do this, the controls within the Login control will immediately become accessible, as shown in Figure 31.3.

Converting the Login control to a template allows access to the controls that comprise it. Notice here that the Button control is selected. Accessing the button is impossible before converting the control to a template.

Figure 31.3. Converting the Login control to a template allows access to the controls that comprise it. Notice here that the Button control is selected. Accessing the button is impossible before converting the control to a template.

To convert the Login control back to a regular control instead of a template, click the button on the control to access the Common Login Tasks popup and click the Reset option. Any changes you made to the control while it was in a templated state will be reset and the control will take on its default appearance.

Converting a control to a template is more powerful than it may seem at first. As you will see shortly, there are many properties for the Login control that enable several other user interface elements. For example, the control can display links for help text or user registration. By converting the control to a template, you have full control over the placement of all parts of the control.

The built-in functionality of the Login control isn’t limited to the appearance of the control. When the Log In button on the control is clicked, ASP.NET will automatically do a lookup on the user and authenticate him/her. If the user presents incorrect credentials, the control will notify the user. If the credentials are correct, the control will log the user in and redirect him/her to the page specified in the DestinationPageUrl property of the control.

There are many other useful properties of the Login control that can be accessed via the Tag Properties task pane.

  • CreateUserIconUrlSpecifies a URL to a graphic file that acts as a link for new users who are not yet registered. When clicked, users will be taken to a registration page for the site.

  • CreateUserTextText that is displayed that acts as a link for new users who are not yet registered. This is most often used in place of the CreateUserIconUrl.

  • DestinationPageUrlThe URL to which users are redirected upon a successful login.

  • DisplayRememberMeIf true, displays the “Remember Me” checkbox. This value is true by default.

  • FailureActionThis property can be one of two values: Refresh or RedirectToLoginPage. It controls what happens if a user fails to log in successfully. The RedirectToLoginPage is used in situations where the Login control is placed on a page other than the login page.

  • FailureTextConfigures the text that is displayed if a user fails the login attempt. It is recommended that this text be chosen carefully so as not to cause a security risk. For example, notifying a user that a password is incorrect may imply that the username is valid, leading to a potential security risk.

  • HelpPageIconUrlSets the URL of a graphic that can be displayed as a help icon. When the user clicks this graphic, he or she will be redirected to a help page for your site.

  • HelpPageTextConfigures the text that is displayed as a link to the help page for the site.

  • HelpPageUrlSpecifies the URL of the help page for the site.

  • InstructionTextSets the text that appears to offer instructions to users.

  • LoginButtonImageUrlSpecifies the URL of an image to use for the login button. The LoginButtonType property should be set to Image when using this property.

  • LoginButtonTextAllows you to change the text that appears on the button. By default, the button displays the text “Log In”.

  • LoginButtonTypeThis property can be one of three values: Button, Image, or Link. Button is the default. When set to Link, the button is converted to a regular link. When set to Image, the image specified by the LoginButtonImageUrl property is displayed.

  • OrientationSets the orientation of the control to either Horizontal or Vertical.

  • PasswordLabelTextSets the text that labels the Password textbox.

  • PasswordRecoveryIconUsed to specify an image to display for a link to a password recovery page. Users can click this when they forget their password.

  • PasswordRecoveryTextSets the text to display for the password recovery link.

  • PasswordRecoveryUrlSets the URL of the password recovery page.

  • PasswordRequiredTextThe text entered here is displayed in the ValidationSummary control on the Login control when no password is entered.

  • RememberMeSetSets this property to true to check the “Remember Me” checkbox by default.

  • RememberMeTextSets the text for the “Remember Me” checkbox.

  • TextLayoutCan be set to TextOnLeft or TextOnTop. This controls the position of the text for the textboxes.

  • TitleTextThe text that appears in the title bar of the control.

  • UserNameSets the initial text of the Username textbox.

  • UserNameLabelTextSets the text that labels the Username textbox.

  • UserNameRequiredErrorSets the text that is displayed in the ValidationSummary control on the Login control when no username is entered.

  • VisibleWhenLoggedInWhen true, the Login control is visible even when the user is logged in. This property is normally used only when the Login control appears on a page other than the login page.

As you can see from that rather long list of properties, the Login control is quite a bit more powerful than it seems at first.

LoginStatus Control

The LoginStatus control has two views: one view for when the user is logged in and one for when the user is logged out. As shown in Figure 31.4, the view of the control can be configured using the dropdown available in the Common LoginStatus Tasks popup.

ASP.NET will automatically choose the correct view for the LoginStatus control based on whether the user is authenticated, but you can choose the view yourself if you wish.

Figure 31.4. ASP.NET will automatically choose the correct view for the LoginStatus control based on whether the user is authenticated, but you can choose the view yourself if you wish.

Some of the useful properties of the LoginStatus control are as follows:

  • LoginImageUrlSpecifies the URL of an image to display for the login image. When a URL is specified in this property, the link in the control changes from text to the image specified.

  • LoginTextSpecifies the text that appears for the login link.

  • LogoutActionThis property can be set to one of three values: Refresh, Redirect, or RedirectToLoginPage. When set to Redirect, users are redirected to the URL in the LogoutPageUrl property when logging out.

  • LogoutImageUrlSpecifies the URL of an image to display for the logout image. When a URL is specified in this property, the link in the control changes from text to the image specified.

  • LogoutPageUrlThe URL to which users are redirected upon logging out when the LogoutAction is set to Redirect.

  • LogoutTextThe text that is displayed for the logout link.

LoginName Control

The LoginName control is perhaps the simplest of the login controls. It displays the name of the logged-in user.

By default, the control displays only the username. By altering the FormatString property, you can alter the text that is displayed. For example, if a user named Jim is logged into the Web site and the FormatString property is set to Logged in as {0}, the LoginName control would display the text “Logged in as Jim”.

ChangePassword Control

The ChangePassword control (Figure 31.5) allows a user to change his or her password. In the default configuration, users are required to be logged in to change their password. However, the ChangePassword control can be configured to also prompt for the username. In those situations, a user can change his or her password without logging in. In fact, when the username field is displayed on the control, it is possible for a user to change the password of a different user as long as he or she knows the old password of the user whose password is being changed.

The Change-Password control makes it easy for a user to change his or her password. In some configurations, a user can even change someone else’s password.

Figure 31.5. The Change-Password control makes it easy for a user to change his or her password. In some configurations, a user can even change someone else’s password.

Similar to the Login control, the Common ChangePassword Tasks popup shown in Figure 31.6 provides you with an AutoFormat link for easy formatting of the control and a link to convert the control to a template for more precision over the layout of the control.

The Common ChangePassword Tasks popup offers similar options to the Login control with the addition of a Views dropdown for switching between the two views provided by the control.

Figure 31.6. The Common ChangePassword Tasks popup offers similar options to the Login control with the addition of a Views dropdown for switching between the two views provided by the control.

The ChangePassword control also includes a Views dropdown that allows you to switch between the Change Password view and the Success view. The Success view is displayed when a user has successfully changed his or her password. Figure 31.6 shows the Change Password view of the control and Figure 31.7 shows the Success view.

When a user has successfully changed his or her password, the Success view is displayed.

Figure 31.7. When a user has successfully changed his or her password, the Success view is displayed.

The ChangePassword control has many properties that allow you to customize the control’s appearance and behavior. Because the list is long, we won’t go over the properties that are similar to corresponding properties of the Login control. Refer back to that section of this chapter to refresh your memory if necessary.

DisplayUserName Property

The DisplayUserName property controls whether or not a textbox for entry of a username exists on the control. If the DisplayUserName property is true and a user is already logged in, the user will have the ability to change the password of another user assuming he or she knows the other user’s password. The ChangePassword control shown in Figure 31.8 has a DisplayUserName property of true.

You can display a textbox for a user’s username by setting the DisplayUserName property to true.

Figure 31.8. You can display a textbox for a user’s username by setting the DisplayUserName property to true.

By placing the ChangePassword control on a page that can be browsed without logging into the site (a page that can be browsed anonymously), a user can change his or her password without logging into the site, provided the DisplayUserName property is set to true.

MailDefinition Property

The MailDefinition property provides the ability to send users an e-mail after a successful password change. The MailDefinition property is actually a reference to a special object in the .NET Framework called MailDefinition.

Note

We’re delving into some basic programmatic concepts as we discuss the MailDefinition property. Because this isn’t a programming book, we won’t go into great detail on this property. I’ll explain how it’s used, but if you want the down-and-dirty details, your best resource is the MSDN Web site at http://msdn2.microsoft.com.

The details on the MailDefinition class can be found by browsing to http://msdn2.microsoft.com/en-US/library/system.web.ui.webcontrols.maildefinition(VS.80).aspx.

As shown in Figure 31.9, the MailDefinition property expands into several different fields:

  • BodyFileNameThe BodyFileName field allows you to specify a file that will be used for the body of the e-mail sent by the ChangePassword control. Any occurrence of <%UserName%> in this file will automatically be replaced by the username of the user, and any occurrence of <%Password%> will automatically be replaced by that user’s new password.

  • CCE-mail address(es) that should be copied on the e-mail. If you’d like to enter more than one address, separate the e-mail addresses with commas.

  • EmbeddedObjectsThe EmbeddedObjects property is a collection of images or graphics to be embedded into the e-mail. When you click the button next to this property, the EmbeddedMailObject Collection Editor appears, as shown in Figure 31.10. The code to insert these objects into the e-mail is included in the file specified by the BodyFileName property.

The Mail-Definition property is actually a collection of many fields that make it easy to define an e-mail to send to users upon a password change.

Figure 31.9. The Mail-Definition property is actually a collection of many fields that make it easy to define an e-mail to send to users upon a password change.

Embedding images in your e-mail is accomplished via the EmbeddedMailObject Collection Editor. In this case, a company logo is being added.

Figure 31.10. Embedding images in your e-mail is accomplished via the EmbeddedMailObject Collection Editor. In this case, a company logo is being added.

The following code inserts the embedded object shown in Figure 31.10:

<img src="cid:CompanyLogo" alt="Jimco Software" />
  • FromThe From property specifies the originating e-mail address for the e-mail.

  • IsBodyHtmlThis property specifies whether or not the file specified by the BodyFileName property contains HTML code or plain text. If you have set the EmbeddedObjects property, you should set the IsBodyHtml property to true.

  • PriorityThe priority at which the e-mail will be sent. Valid values are Normal, Low, and High.

  • SubjectThe subject of the e-mail.

Tip

To send e-mail, the computer on which the Web site resides must have the SMTP service configured on it. You can get information on how to configure SMTP by browsing to http://msdn2.microsoft.com/en-US/library/8b83ac7t(VS.80).aspx.

Caution

When using the MailDefinition property, keep in mind that e-mail can be intercepted fairly easily by someone other than the intended recipient. Use caution.

PasswordHintText Property

The text specified for the PasswordHintText property appears above the Password textbox. It is used to communicate your password requirements to users.

The default requirements of passwords require that they be at least seven characters in length with at least one non-alphanumeric character.

For information on how to modify password requirements, see “Modifying Password Requirements” in the “Lagniappe” section of this chapter.

PasswordRecoveryUrl

The PasswordRecoveryUrl property points to the page containing a PasswordRecovery control so that a user can recover or reset his or her existing password. (We’ll cover the PasswordRecovery control later in this chapter.)

This property will use the PasswordRecoveryText or PasswordRecoveryIconUrl property to create the link.

SuccessPageUrl Property

The SuccessPageUrl property is used in cases where you would like a user to be redirected to a specific page when his or her password has been successfully changed.

If this value is not specified, the ChangePassword control will switch to the Success view upon a successful password change. If the SuccessPageUrl property is specified, the Success view of the ChangePassword control will not be displayed at all.

PasswordRecovery Control

The PasswordRecovery control is designed to allow a user to gain access to your site even in cases of a forgotten password. The name of the control is a bit misleading. By default, a user cannot recover his or her password. Instead, a new one is assigned and sent in an e-mail. That’s because ASP.NET uses an irreversible hashing algorithm before storing a password by default. It is possible to change this behavior and store passwords encrypted. When a password is encrypted, it can be decrypted and recovered for the user.

Note

We won’t go into the specifics of configuring ASP.NET’s behavior when storing passwords. If you’d like more information, Microsoft has excellent documentation on the MSDN Web site at http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.passwordrecovery.membershipprovider(VS.80).aspx.

As with the other controls we’ve reviewed, the PasswordRecovery control can be auto-formatted for a more pleasing appearance using the AutoFormat dialog shown in Figure 31.11. This dialog is accessible via the Common PasswordRecovery Tasks popup. The PasswordRecovery control is also a templated control, so you can rearrange the layout if you wish.

The Password-Recovery control can be formatted for a more pleasing appearance using the AutoFormat dialog.

Figure 31.11. The Password-Recovery control can be formatted for a more pleasing appearance using the AutoFormat dialog.

When a user changes his or her password, the process actually occurs in a series of three steps. In the first step, the user is asked for his or her username. After the Submit button is clicked, the user is asked for the answer to his or her secret question provided when he or she registered for the Web site. Assuming the answer is correct, the user is presented with a message indicating that the password is being e-mailed.

Each of these steps is accessible in Expression Web using the Views dropdown in the Common PasswordRecovery Tasks popup, as shown in Figure 31.12. Because the control is templated, you can convert one or more of these steps to a template and control the layout and other functionality of each step.

The Password-Recovery control consists of three different views to allow a user to retrieve or reset a password. The Question view is shown here.

Figure 31.12. The Password-Recovery control consists of three different views to allow a user to retrieve or reset a password. The Question view is shown here.

Tip

The view that is initially displayed for the PasswordRecovery control is the view that is selected in Expression Web when the page is saved. Therefore, you’ll want to make sure you select the UserName view before saving your page.

The properties of the PasswordRecovery control are similar to the properties for the other login controls we’ve covered, so there’s no need to cover the details here.

CreateUserWizard

The CreateUserWizard control (Figure 31.13) is a wizard-based control that makes it easy for new users of your Web site to create an account so they can log in. The CreateUserWizard control is actually a customized ASP.NET Wizard control, so the configuration options available are the same options used for the Wizard control.

The CreateUser-Wizard control is a customized wizard control designed to allow users to easily create new accounts for your Web site.

Figure 31.13. The CreateUser-Wizard control is a customized wizard control designed to allow users to easily create new accounts for your Web site.

For more information on the Wizard control, see “Using Standard ASP.NET Controls”, p. 495 (Chapter 28).

Several properties are unique to the CreateUserWizard control. The following are a few that affect the behavior of the control:

  • DisableCreatedUserBy default, after a user creates a new account, he or she can immediately log into the Web site. By setting the DisableCreatedUser property to false, the user will be prevented from logging in. This is commonly used in cases where an administrator or moderator is required to approve an account before it is granted access.

  • LoginCreatedUserWhen a user creates a new account using the CreateUserWizard control, he or she is immediately logged into the Web site upon completion of the wizard. If the LoginCreatedUser property is set to false, the user will have to explicitly log in instead of being logged in automatically.

    If the DisableCreatedUser property is set to true, you will want to set the LoginCreatedUser to false so that the CreateUserWizard control doesn’t attempt to automatically log in a disabled user account.

  • PasswordRegularExpressionAllows you to use a regular expression to apply specific restrictions to password requirements for your site. This regular expression is applied in addition to the password requirements specified by ASP.NET.

For more information on ASP.NET password requirements, see “Modifying the Password Requirements” in the “Lagniappe” section of this chapter.

The CreateUserWizard control exposes a MailDefinition object so you can send the new user his or her login information via e-mail if you choose. We discussed the requirements for sending e-mail in the overview of the ChangePassword control earlier in this chapter.

LoginView Control

So far, we’ve covered controls that have a single purpose. The LoginView control is a break from that pattern. The LoginView control is a container control for other controls and provides you with, by default, two views: the AnonymousTemplate view and the LoggedInTemplate view.

Controls that you place in the AnonymousTemplate view, as shown in Figure 31.14, will be visible only to users who have not yet logged into the site. In Figure 31.14, I have inserted a Login control into the AnonymousTemplate view so that users can log in if they haven’t done so.

The Anonymous-Template view is visible only to users who are browsing anonymously. Once a user logs in, he or she will no longer see the Anonymous-Template view.

Figure 31.14. The Anonymous-Template view is visible only to users who are browsing anonymously. Once a user logs in, he or she will no longer see the Anonymous-Template view.

On the other hand, Figure 31.15 shows the LoggedInTemplate view, where I have inserted LoginStatus and LoginName controls. I changed the LoginStatus control’s view to the Logged In view so it will provide a link for the user to log out.

The LoggedIn-Template is usually visible to users who have logged into the Web site. As you’ll soon see, the user may see a different view instead.

Figure 31.15. The LoggedIn-Template is usually visible to users who have logged into the Web site. As you’ll soon see, the user may see a different view instead.

The LoginView control is commonly used on pages where anonymous content is present, but you also want to provide a login interface in one part of the page so that users can log in if desired. A forum page is an excellent example of a page suitable for this kind of control. Users can browse the forums anonymously. If they want to post on the forum, they can log in right on the page they are currently viewing without having to redirect to a login page and lose their place.

As shown in Figures 31.14 and 31.15, the Common LoginView Tasks popup contains a link for editing RoleGroups. This allows you to define a template for different ASP.NET roles to which a user may belong using the RoleGroup Collection Editor shown in Figure 31.16. In Figure 31.16, you can see that I’ve defined a role called Administrators. If the logged-in user is a member of the Administrators role, he or she will see the view associated with that role instead of the LoggedInTemplate view. Figure 31.17 shows the new role selected in the Common LoginView Tasks popup.

The RoleGroup Collection Editor allows for the creation of views for specific ASP.NET roles that have been previously created.

Figure 31.16. The RoleGroup Collection Editor allows for the creation of views for specific ASP.NET roles that have been previously created.

When a new RoleGroup has been added, you’ll have a new view to choose in the Views dropdown. Users who are in the Administrators role will see the new Administrators view.

Figure 31.17. When a new RoleGroup has been added, you’ll have a new view to choose in the Views dropdown. Users who are in the Administrators role will see the new Administrators view.

Tip

When the page containing a LoginView control is browsed, ASP.NET will look for a role that applies, starting at the top of the list of roles. As soon as it locates a role to which the current user belongs, it will display that view to the user. Therefore, if a user is a member of more than one role, he or she will always see the view for the first role in the list of RoleGroups.

Note

A discussion of ASP.NET roles is outside the scope of this book. If you’d like more information on ASP.NET roles, there is an excellent resource on the MSDN Web site at http://msdn2.microsoft.com/en-us/library/5k850zwb(VS.80).aspx.

Creating a Login Solution

Now that you’ve seen an overview of the different login controls that are available, let’s design a simple membership Web site.

The first step in creating our membership Web site is to configure the Web site for ASP.NET Forms authentication. Forms authentication is a security mechanism that is enforced by ASP.NET. If a user tries to browse to a page that is not available anonymously, ASP.NET will automatically send him/her to a login page instead, where the user can enter a username and password to log into the site.

Configuring the Web Site (IIS)

Note

If you are using the ASP.NET Development Server, refer to the section “Configuring the Web Site (ASP.NET Development Server)” that follows this section.

In ASP.NET 1.0 and 1.1, configuring Forms authentication required the manual editing of configuration files. ASP.NET 2.0 makes the job significantly easier by providing a Windows interface into the configuration options.

Note

The following steps require IIS 5 or IIS 6. The ASP.NET Development Server does not allow for configuration of a Web site from within a Windows interface.

Note

Configuration of Web sites is dramatically different in IIS 7. As of this writing, IIS 7 is still in beta. Please refer to the Que Web site at http://www.quepublishing.com for updated information on IIS 7 when it releases.

  1. Create a new Web site at http://<server>/membership, where <server> is a Web server running IIS 5 or greater with the .NET Framework 2.0 installed.

  2. Open the Windows Control Panel and double-click on Administrative Tools.

  3. Double-click on Internet Information Services.

  4. Expand the computer name node in Internet Information Services.

  5. Expand the Web Sites node.

  6. Expand the Web site on which the Web site was created in Step 1.

  7. Right-click on the membership Web application and choose Properties.

  8. Click the ASP.NET tab.

  9. Make sure that 2.0.50727 is selected in the ASP.NET version dropdown.

  10. Click the Edit Configuration button, as shown in Figure 31.18.

    Editing the configuration of an ASP.NET 2.0 Web site is easy thanks to the new user interface built into IIS.

    Figure 31.18. Editing the configuration of an ASP.NET 2.0 Web site is easy thanks to the new user interface built into IIS.

  11. Click the Authentication tab.

  12. Set the Authentication mode dropdown to Forms, as shown in Figure 31.19.

    We need to configure the new application for Forms authentication so we can use the ASP.NET login controls.

    Figure 31.19. We need to configure the new application for Forms authentication so we can use the ASP.NET login controls.

  13. Make sure that the Login URL is set to login.aspx. We will create this page soon.

For more information on creating Web sites in Expression Web, see “Creating a Web Site”, p. 25 (Chapter 2).

Note

We need to configure the new application for Forms authentication so we can use the ASP.NET login controls.

If you don’t see an ASP.NET tab in the Properties dialog for your Web application, see “ASP.NET Tab Is Missing” in the “Troubleshooting” section of this chapter.

Now we need to configure the application so that no one can browse it anonymously. We’ll use ASP.NET’s authorization features to implement this restriction.

  1. Click the Authorization tab in the ASP.NET Configuration Settings dialog.

  2. Click the Add button.

  3. Select the Deny radio button in the Rule type section.

  4. Select the Anonymous users radio button in the Users and roles section, as shown in Figure 31.20.

    The Edit Rule dialog is an easy way to configure authorization settings for your ASP.NET application. You can manually edit configuration files to do the same thing, but the Windows interface is much easier to use.

    Figure 31.20. The Edit Rule dialog is an easy way to configure authorization settings for your ASP.NET application. You can manually edit configuration files to do the same thing, but the Windows interface is much easier to use.

  5. Click OK in the Edit Rule dialog.

  6. Click OK in the ASP.NET Configuration Settings dialog.

  7. Click OK in the Properties dialog for your Web application.

You have just configured an ASP.NET Forms authentication Web site and set the authorization of the site so that anonymous users are not allowed.

Tip

Notice that we didn’t tell ASP.NET to allow anonymous users to access the login page. ASP.NET will always allow anonymous access to the login page, so even though we’ve configured the site so that no anonymous users are allowed, everyone will be able to access the login page.

Configuring the Web Site (ASP.NET Development Server)

The ASP.NET Development Server does not have a Windows interface for modifying the configuration of your site, so you’ll need to create a configuration file for that purpose. To make matters even more confusing, Expression Web does not have IntelliSense for ASP.NET configuration files.

Note

Because ASP.NET configuration files are XML files, Expression Web will provide color-coding for the files.

For information on controlling the color-coding of files within Expression Web, see “Configuring Page Editor Options”, p. 257 (Chapter 15).

Tip

If you want a better method of creating a configuration file (and many other ASP.NET 2.0 tasks), I encourage you to download Microsoft Visual Web Developer Express Edition from http://msdn.microsoft.com/vstudio/express/vwd/.

For more information on using Visual Web Developer Express Edition with Expression Web, see “Using Expression Web with Visual Web Developer Express Edition”, p. 655 (Appendix A).

To control the configuration of a specific Web application, ASP.NET uses a special configuration file in the root of the Web site called web.config. The web.config file contains XML code that controls many aspects of the Web site.

To configure our Web site for ASP.NET membership, we’ll need to do the following:

  • Configure the site for ASP.NET Forms authentication.

  • Disable the ability for unauthenticated users to browse the Web site.

  • Turn on ASP.NET Impersonation.

Note

ASP.NET Impersonation is a feature that allows you to run ASP.NET code under a user identity other than the default identity.

A full discussion of ASP.NET Impersonation is outside the scope of this book. For full details on impersonation in ASP.NET, read Sams Teach Yourself ASP.NET 2.0 in 24 Hours, Complete Starter Kit from Sams Publishing.

Begin by selecting File, New, Page and selecting XML from the list of file types. Place your cursor after the XML code that Expression Web adds by default and enter the following code:

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
    <system.web>
        <authentication mode="Forms" />
        <authorization>
            <deny users="?" />
        </authorization>
        <identity impersonate="true" />
    </system.web>
</configuration>

Now save the file as web.config. Make sure to select All Files (*.*) from the Save as type dropdown. Otherwise, Expression Web will automatically add an .xml file extension to your file.

Note that the outermost element in the web.config file is the <configuration> section. Within that section is a <system.web> section. This is where you make changes to ASP.NET configuration.

In this case, the first element inside the <system.web> section is the <authentication> element. We have enabled ASP.NET Forms authentication by setting the mode of the <authentication> element to Forms.

Caution

ASP.NET configuration files are case-sensitive. If you enter information in the wrong case, you’ll see errors in your application.

The next element defines the <authorization> section. The <authorization> section allows you to control who has access to the Web site. In this case, we want to disallow anyone from browsing the site unless they have been authenticated. The <deny> tag allows us to do that. By specifying a users attribute with a value of ?, we are telling ASP.NET that any user who is not authenticated should be denied access.

The next element is the <identity> element. We use this element to turn on ASP.NET Impersonation. The ASP.NET application would normally execute under the identity of the process in which it runs. By enabling ASP.NET Impersonation, we’re forcing our page to run under the identity of the user who is authenticated to our application.

Creating the Web Pages

Our membership site will only require two pages: the login page and a content page. In a real application, you’d probably want to have a separate login page and new user page, but in this sample, we’ll use one page for both functions.

  1. Create a new ASP.NET Web Form and save it as login.aspx.

  2. Create a second ASP.NET Web Form and save it as default.aspx.

  3. Add a Login control and a CreateUserWizard control to the login.aspx page. The login.aspx page should now look like Figure 31.21.

    The login page will serve two purposes: it will allow users to log in or create a new account if they’ve never visited the site before.

    Figure 31.21. The login page will serve two purposes: it will allow users to log in or create a new account if they’ve never visited the site before.

  4. Add a new LoginStatus control to the default.aspx page and set the view to LoggedIn.

  5. Place the insertion point just to the right of the LoginStatus control and press the Spacebar on your keyboard.

  6. Insert a new LoginName control.

Your default.aspx page should now look like Figure 31.22. When a user logs in and sees this content, the controls will allow him/her to log out easily.

The content page will use ASP.NET login controls to allow a user to easily log out.

Figure 31.22. The content page will use ASP.NET login controls to allow a user to easily log out.

Now you’re ready to try out the Web site. Try browsing to the default.aspx page. You should be redirected automatically to the login.aspx page because you have not yet logged in.

Note

The content page will use ASP.NET login controls to allow a user to easily log out.

If you get an error saying “Failed to access IIS metabase” when browsing the ASP.NET page, see “Metabase Access Fails Browsing ASP.NET Page” in the “Troubleshooting” section of this chapter.

Note

The content page will use ASP.NET login controls to allow a user to easily log out.

If you get an error saying “Failed to start monitoring file changes” or “Failed to start monitoring directory changes” when browsing the ASP.NET page, see “Failed to Start Monitoring Changes Error” in the “Troubleshooting” section of this chapter.

Fill out the form to sign up for a new account, as shown in Figure 31.23, and click the Create User button to create your account. You’ll be presented with a message letting you know that the account has been successfully created, as shown in Figure 31.24.

The CreateUser-Wizard control will not only collect all the information for a new user, but it will also create the user database when the first user is created.

Figure 31.23. The CreateUser-Wizard control will not only collect all the information for a new user, but it will also create the user database when the first user is created.

Your new user account has been created and you can now log in using your new user credentials.

Figure 31.24. Your new user account has been created and you can now log in using your new user credentials.

Note

Your new user account has been created and you can now log in using your new user credentials.

If you get an error that says “Access denied creating App_Data subdirectory”, see “Access Denied Error” in the “Troubleshooting” section of this chapter.

When you create the first user in an ASP.NET membership application, the SQL Server 2005 Express Edition database will be created for you automatically.

As you’ve seen in this chapter, creating a powerful membership system in ASP.NET 2.0 and Expression Web is as simple as just dropping the controls on the page. We created an entire application without writing a single line of code.

Troubleshooting

ASP.NET Tab Is Missing

I’ve opened the properties for my Web site, but there isn’t an ASP.NET tab.

There are many reasons for this, but the most common is missing Registry information. Open a command prompt and run the following command:

Regsvr32.exe %windir%microsoft.netframeworkv2.0.50727mmcaspext.dll

This will add the Registry information for the file that creates the tab and will hopefully correct the problem. If that doesn’t correct your problem, open a command prompt and run the following commands:

cd %windir%microsoft.netframeworkv2.0.50727
aspnet_regiis –i

Metabase Access Fails Browsing ASP.NET Page

I’m browsing my ASP.NET page and I see an error that says “Failed to access IIS metabase.” What does this mean?

This is a permissions issue. The account that is used to run ASP.NET needs access to a special database IIS uses to keep track of its settings.

To correct this problem, open a command prompt and switch to the following directory:

%windir%microsoft.netframeworkv2.0.50727

At the command line, run the following command if using Windows 2000 or Windows XP:

aspnet_regiis –ga ASPNET

If you’re using Windows 2003, run the following command:

aspnet_regiis –ga IISWPG

Failed to Start Monitoring Changes Error

When browsing my ASP.NET page, I get an error that says “Failed to start monitoring file changes” or “Failed to start monitoring directory changes.”

This error means that the ASP.NET process account does not have permission to access the Web site’s content. Here’s how to fix it.

  1. Right-click on the root folder of the Web site (c:inetpubwwwroot by default).

  2. Choose Properties from the menu.

  3. Select the Security tab.

  4. Click Add.

  5. Enter ASPNET in the box if you are using Windows 2000 or Windows XP and IISWPG if you are using Windows 2003.

  6. Click the Advanced button.

  7. Place a check in the box that says Replace permission entries on all child objects with entries shown here that apply to child objects.

  8. Click OK.

  9. Click OK again.

Access Denied Error

When browsing my membership site, I get an error that says “Access denied creating App_Data subdirectory.” How do I fix this?

The steps to resolve this are the same as the steps to resolve the “Failed to Start Monitoring Changes Error” in the previous troubleshooting note.

Lagniappe (lan yap’) n., a gift or bonus: Modifying Password Requirements

The password requirements for an ASP.NET membership application may be a bit stringent for your needs. By default, the password must be at least seven characters in length and must include at least one non-alphanumeric character. If you’d like to change these requirements and make them a bit less stringent (or more, if you’d like), you can edit a configuration file provided by the .NET Framework.

The master configuration for the machine is defined in a file called machine.config. This file is located in the %windir%Microsoft.NETFrameworkv2.0.50727CONFIG directory. When you are dealing with settings specific to ASP.NET membership applications, you want to work with the <membership> section of the file.

The following code shows the default settings:

<membership>
  <providers>
    <add name="AspNetSqlMembershipProvider"
         type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.0.0,
             Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
         connectionStringName="LocalSqlServer"
         enablePasswordRetrieval="false"
         enablePasswordReset="true"
         requiresQuestionAndAnswer="true"
         applicationName="/"
         requiresUniqueEmail="false"
         passwordFormat="Hashed"
         maxInvalidPasswordAttempts="5"
         minRequiredPasswordLength="7"
         minRequiredNonalphanumericCharacters="1"
         passwordAttemptWindow="10"
         passwordStrengthRegularExpression="" />
  </providers>
</membership>

Several attributes control the policy concerning passwords:

  • maxInvalidPasswordAttemptsThe default value is 5. If a user enters an incorrect password more than five times, the login automatically fails.

  • minRequiredPasswordLengthThis value defaults to 7. Therefore, the password must be at least seven characters.

  • minRequiredNonalphanumericCharactersThis value defaults to 1, meaning that a valid password must have at least one character that is neither a letter nor a number. To remove that qualification, set this value to 0.

  • passwordAttemptWindowThis value defaults to 10 minutes. This value works in conjunction with the maxInvalidPasswordAttempts, meaning that if a user makes more than 5 invalid login attempts within a 10-minute window, he/she is locked out.

When you change any of these settings, you’ll need to run iisreset from a command prompt to restart the ASP.NET worker process with the new settings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset