Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Pro ASP.NET 2.0 In CSharp 2005 (2005) [eng]

.pdf
Скачиваний:
107
Добавлен:
16.08.2013
Размер:
29.8 Mб
Скачать

718C H A P T E R 2 1 M E M B E R S H I P

that accesses the database file directly. SQL Server automatically attaches the database (temporarily) and allows you to access it directly through the file without any additional configuration steps. The only prerequisite of course is that SQL Server 2005 is installed on the target machine.

These database files are located in the special App_Data subdirectory of the application. When running ASP.NET with the default configuration, this file will be created automatically for you. But what causes the file to be created for you? Well, the answer is quite simple: when a feature that requires a specific type of functionality is used for the first time, the provider automatically creates the database file with the necessary contents. Therefore, when you first run the security wizard you saw previously, the database will be created automatically when you create the first user. This functionality is provided by the SqlMembershipProvider class. (The actual implementation is also included in a utility class used by all SQL provider classes, such as like the SqlRoleProvider.)

Configuring Connection String and Membership Provider

With the default configuration and SQL Server 2005 (Express Edition or the full version) installed, you don’t have to prepare the data store and configure a Membership provider, because the ASP.NET runtime uses the file-based SQL Server 2005 provider and automatically creates the database file for you.

But if you want to use your own SQL Server database, or even your custom Membership provider and store, you have to configure the provider as well as the connection string to the Membership store database appropriately. For this purpose, you have to touch the web.config file directly or edit the configuration through the IIS MMC snap-in if you are running your application on IIS.

In the case of using SQL Server storage (or other database-based storage), you have to configure the connection string as your first step. You can do this through the <connectionStrings /> section of the web.config file. For example, if you want to use a local database called MyDatabase where you have installed the database tables through the aspnet_regsql.exe tool as shown previously, you have to configure the connection string as follows (remember, the <connectionStrings /> section is located directly below the <configuration /> element):

<connectionStrings>

<add name="MyMembershipConnString"

connectionString="data source=(local);Integrated Security=SSPI; initial catalog=MyDatabase" />

</connectionStrings>

After you have configured the connection string for your custom Membership storage, you must configure the Membership provider for the application. For this purpose, you have to add the <membership /> section to your web.config file (if it’s not already there) below the <system.web /> section, as follows:

<system.web>

<authentication mode="Forms" /> <authorization>

<deny users="?"/> </authorization>

<membership defaultProvider="MyMembershipProvider">

<providers>

<add name="MyMembershipProvider" connectionStringName="MyMembershipConnString"

C H A P T E R 2 1 M E M B E R S H I P

719

applicationName="MyMembership"

enablePasswordRetrieval="false"

enablePasswordReset="true"

requiresQuestionAndAnswer="true"

requiresUniqueEmail="true"

passwordFormat="Hashed" type="System.Web.Security.SqlMembershipProvider" />

</providers>

</membership>

</system.web>

Within the <membership /> section, you can add multiple providers as child elements of the <providers /> section. In the previous code, you can see a valid configuration for the included

SqlMembershipProvider. It’s important to not forget about the defaultProvider attribute. This attribute indicates the Membership provider that will be used if you don’t override the used provider in your code. Configured providers are shown in the ASP.NET web configuration when selecting the option Select a Different Provider for Each Feature, as shown in Figure 21-8.

Figure 21-8. The configured provider selected in the WAT

Table 21-4 describes the properties you can configure for the SqlMembershipProvider.

720 C H A P T E R 2 1 M E M B E R S H I P

Table 21-4. The SqlMembershipProvider’s Properties

Property

Description

Name

Specifies a name for the Membership provider.

 

You can choose any name you want. This name

 

can be used later for referencing the provider

 

when programmatically accessing the list of

 

configured Membership providers. Furthermore,

 

this name will be used by the WAT to display the

 

provider.

ApplicationName

Specifies the name of the application for which

 

the Membership provider manages users and

 

their settings.

Description

An optional description for the Membership

 

provider.

PasswordFormat

Gets or sets the format in which passwords will be

 

stored in the underlying credential store. Valid

 

options are Clear for clear-text password storage,

 

Encrypted for encrypting passwords in the data

 

store (uses the locally configured machine key for

 

encryption), and Hash for hashing passwords

 

stored in the underlying Membership store.

MinRequiredNonAlphanumericCharacters

Specifies the number of nonalphanumeric

 

characters the password needs to have. This is an

 

important part for the validation of the password

 

and enables you to specify strength requirements

 

for the passwords used by your users.

MinRequiredPasswordLength

Allows you to specify the minimum length of

 

passwords for users of your application. This

 

is also an important property for specifying

 

password strength properties.

PasswordStrengthRegularExpression

If the previously mentioned properties are not

 

sufficient for specifying password strength

 

conditions, then you can use a regular expression

 

for specifying the format of valid passwords. With

 

this option you are completely flexible in terms of

 

specifying password format criteria.

EnablePasswordReset

The Membership API contains functionality for

 

resetting a user’s password and optionally

 

sending an e-mail if an SMTP server is configured

 

for the application.

EnablePasswordRetrieval

When set to true, you can retrieve the password

 

of a MembershipUser object by calling its

 

GetPassword method. Of course, this works

 

only if the password is not hashed.

MaxInvalidPasswordAttempts

Specifies the number of invalid validation

 

attempts before the user gets locked.

PasswordAttemptWindow

Here you can set the number of minutes in which

 

a maximum number of invalid password or

 

password question-answer attempts are allowed

 

before the user is completely locked out from the

 

application. In that case, the user gets locked out,

 

so the administrator must activate the account

 

again.

C H A P T E R 2 1 M E M B E R S H I P

721

Property

Description

RequiresQuestionAndAnswer

Specifies whether the password question with

 

an answer is required for this application. This

 

question can be used if the user has forgotten his

 

password. With the answer he gets the possibility

 

of retrieving an automatically generated, new

 

password via e-mail.

RequiresUniqueEmail

Specifies whether e-mail addresses must be

 

unique for every user in the underlying

 

Membership store.

 

 

Now, after you have set up the data store and configured the Membership provider, you can test your configuration by creating users through the WAT. The utility includes a link for testing the configuration by connecting to the database with the configured Membership provider, as shown in Figure 21-9.

Figure 21-9. Testing the Membership provider configuration

Creating and Authenticating Users

To create new users in your previously created Membership provider store, launch the WAT by selecting the Website ASP.NET Web Configuration menu from within Visual Studio. Now switch to the Security tab, and select Create User, as shown in Figure 21-10.

722 C H A P T E R 2 1 M E M B E R S H I P

Figure 21-10. Creating users with the WAT

After you have created a couple of users, you can connect to the database through Visual Studio’s Server Explorer and look at the aspnet_Users and aspnet_Membership tables in the database, as shown in Figure 21-11.

Figure 21-11. The aspnet_Users table in the Membership database

C H A P T E R 2 1 M E M B E R S H I P

723

Both the password and the answer for the password question are stored as a salted hash in the database because you have selected the passwordFormat="Hashed" option for the provider in the <membership> configuration section. After you have added users to the Membership store, you can authenticate those users with the Membership API. For that purpose, you have to create a login page that queries the user name and password from the user and then validates those credentials against the credential store, as follows:

protected void LoginAction_Click(object sender, EventArgs e)

{

if (Membership.ValidateUser(UsernameText.Text, PasswordText.Text))

{

FormsAuthentication.RedirectFromLoginPage(UsernameText.Text, false);

}

else

{

LegendStatus.Text = "Invalid user name or password!";

}

}

You don’t need to know about which provider is actually used by the application. If you want to use a different Membership provider, you just need to change the configuration so that the Membership API uses this different provider. You application doesn’t know about any details of the underlying provider. Furthermore, in the next section you will learn about the new security controls. You will see that you don’t need to create the controls for the login page manually anymore.

Using the Security Controls

Of course, you still have to create the login page again and again. But ASP.NET 2.0 ships with several new controls that simplify the process of creating the login page as well as other related functionality. In this section, you will learn more about the new security controls included with ASP.NET.

These security controls rely on the underlying forms authentication and the Membership API infrastructure. Table 21-5 describes the security controls that ship with ASP.NET.

Table 21-5. The New ASP.NET Security Controls

Control

Primary Purpose

Login

The Login control is a composite control that solves the most common

 

task for forms authentication–based applications—displaying a user name

 

and password textbox with a login button. Furthermore, if events are

 

caught through custom event procedures, it automatically validates the

 

user against the default Membership provider.

LoginStatus

The login status is a simple control that validates the authentication state

 

of the current session. If the user is not authenticated, it offers a login

 

button that redirects to the configured login page. Otherwise, it displays

 

a sign-out button for the possibility of logging off.

LoginView

This is really a powerful control that allows you to display different sets of

 

controls for authenticated and unauthenticated users. Furthermore, it

 

allows you to display different controls for users who are in different roles,

 

as you will see in Chapter 23.

Continued

724 C H A P T E R 2 1 M E M B E R S H I P

Table 21-5. Continued

Control

Primary Purpose

PasswordRecovery

This allows the user to retrieve the password if the user has provided an

 

e-mail address during registration. It requests the user name from the

 

user and then automatically displays a user interface that displays the

 

password question and requests the appropriate answer from the user.

 

If the answer is correct, it uses the Membership API to send the password

 

to the user.

ChangePassword

This control is a composite control that requests the old password from

 

the user and lets the user enter a new password including the password

 

confirmation.

CreateUserWizard

Includes a complete wizard that guides the user (or an administrator)

 

through the creation process of a user.

 

 

You can use these controls with any other control. For example, you can use the Login control either on your main page or on a separate login page. Every control works in the same way: if you don’t catch any custom events, all these controls work with the Membership API by default. As soon as you catch events provided by the controls, you are responsible for completing the task. For example, the Login control supports an Authenticate event. If you don’t catch this event, it uses the Membership API automatically. But if you catch this event, you are responsible for validating user credentials on your own.

The Login Control

The Login control provides you with a ready-to-use user interface that queries the user name and password from the user and offers a login button for actually logging the user in. Figure 21-12 shows an example of the Login control in action.

Figure 21-12. The Login control in action

Behind the scenes the Login control is nothing more than an ASP.NET composite control. It’s completely extensible in that it allows you to override any layout styles and properties as well as catch events thrown by the control for overriding its default behavior. If you leave the Login control

C H A P T E R 2 1 M E M B E R S H I P

725

as it is and you don’t catch any of its events, it automatically uses the Membership provider configured for your application. The simplest form of a Login control on your page is as follows:

<form id="form1" runat="server"> <div style="text-align: center">

<asp:Login ID="Login1" runat="server"> </asp:Login>

</div>

</form>

You can use several properties for changing the appearance of the control. You can use the different style settings supported by the Login control as follows:

<form id="form1" runat="server"> <div style="text-align: center">

<asp:Login ID="Login1" runat="server"

BackColor="aliceblue" BorderColor="Black" BorderStyle="double"> <LoginButtonStyle BackColor="darkblue" ForeColor="White" /> <TextBoxStyle BackColor="LightCyan" ForeColor="Black" Font-Bold="true" />

<TitleTextStyle Font-Italic="true" Font-Bold="true" Font-Names="Verdana" /> </asp:Login>

</div>

</form>

You can also use CSS classes for customizing the Login control’s appearance. Every style property supported by the Login control includes a CssClass property. As is the case for every other ASP.NET control, this property allows you to set a CSS class name for your Login control that was added to the website previously. Imagine you added the following CSS style sheet with the filename MyStyles.css to your project:

.MyLoginTextBoxStyle

{

cursor: crosshair; background-color: yellow; text-align: center; border-left-color: black; border-bottom-color: black; border-top-style: dotted; border-top-color: black; border-right-style: dotted; border-left-style: dotted; border-right-color: black; border-bottom-style: dotted; font-family: Verdana; vertical-align: middle;

}

The content of the CSS file defines the style .MyLoginTextBoxStyle that you will use for the text boxes displayed on your Login control. You can include this style file in your login page so that you can use the style for the Login control as follows:

<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

<title>Untitled Page</title>

<link href="MyStyles.css" rel="stylesheet" type="text/css" />

</head>

<body>

<form id="form1" runat="server"> <div style="text-align: center">

<asp:Login ID="Login1" runat="server"

726 C H A P T E R 2 1 M E M B E R S H I P

BackColor="aliceblue" BorderColor="Black" BorderStyle="double">

<LoginButtonStyle BackColor="darkblue" ForeColor="White" /> <TextBoxStyle CssClass="MyLoginTextBoxStyle" /> <TitleTextStyle Font-Italic="true" Font-Bold="true"

Font-Names="Verdana" />

</asp:Login>

</div>

</form>

</body>

</html>

Note If you try running the page and if the CSS file is placed in a directory where anonymous access is denied, the styles will not be applied to the Login control because the CSS file is protected by the ASP.NET runtime (because its file extension is mapped to ASP.NET). This is also the case if you deny access to anonymous users in the root directory and put your CSS file there. Therefore, if you want to use CSS files with the Login control (where the user is definitely the anonymous user), either you have to put the CSS file into a directory that allows anonymous users access or you have to add the following configuration for the CSS file to your web.config file:

<location path="MyStyles.css"> <system.web>

<authorization>

<allow users="*" /> </authorization>

</system.web>

</location>

We prefer having publicly available resources in a separate folder and restricting access to any other location of the web application, or the other way round. You will learn more about authorization and the configuration steps for it in Chapter 23.

Table 21-6 lists the styles supported by the Login control. Every style works in the same way. You can set color and font properties directly, or you use the CssClass property for assigning a CSS class.

Table 21-6. The Styles Supported by the Login Control

Style

Description

CheckBoxStyle

Defines the style properties for the Remember Me check box.

FailureStyle

Defines the style for the text displayed if the login was not successful.

HyperLinkStyle

The Login control allows you to define several types of hyperlinks, for

 

example, to a registration page. This style defines the appearance of

 

these hyperlinks.

InstructionTextStyle

The Login control allows you to specify help text that is displayed directly

 

in the Login control. This style defines the appearance of this text.

LabelStyle

Defines the style for the User Name and Password labels.

LoginButtonStyle

Defines the style for the login button.

TextBoxStyle

Defines the style for the User Name and Password text boxes.

TitleTextStyle

Defines a style for the title text of the Login control.

ValidatorTextStyle

Defines styles for validation controls that are used for validating the user

 

name and password.

 

 

C H A P T E R 2 1 M E M B E R S H I P

727

The styles are customizable not only for the Login control. Any content displayed in the control is customizable through several properties. For example, you can select the text displayed for the login button, and you have the choice of displaying a login link instead of a login button (which is the default). Furthermore, you can add several hyperlinks to your Login control, such as a hyperlink to a help text page or a hyperlink to a registration page. Of course, both pages must be available for anonymous users, because the help should be provided to anonymous users (remember, if someone sees the Login control, she potentially is an anonymous user). If you want to include some additional links in your Login control, modify the previously displayed control as follows:

<asp:Login ID="Login1" runat="server" BackColor="aliceblue" BorderColor="Black" BorderStyle="double"

CreateUserText="Register"

CreateUserUrl="Register.aspx" HelpPageText="Additional Help" HelpPageUrl="HelpMe.htm"

InstructionText="Please enter your user name and password for <br> logging into the system.">

<LoginButtonStyle BackColor="DarkBlue" ForeColor="White" /> <TextBoxStyle CssClass="MyLoginTextBoxStyle" />

<TitleTextStyle Font-Italic="True" Font-Bold="True" Font-Names="Verdana" /> </asp:Login>

This code displays two additional links—one for a help page and one for a registration page— and adds some short, instructional text below the heading of the Login control. The styles discussed previously are applied to these properties. Table 21-7 describes the relevant properties for customizing the Login control.

Table 21-7. The Relevant Customization Properties for the Login Control

Property

Description

TitleText

The text displayed as the heading of the control.

InstructionText

You have already used this property in the previous code

 

snippet, which contains text that is displayed below the

 

heading of the control.

FailureText

This is the text displayed by the Login control if the login

 

attempt was not successful.

UserNameLabelText

The text displayed as a label in front of the user name

 

text box.

PasswordLabelText

The text displayed as a label in front of the password

 

text box.

UserName

Initial value filled into the user name text box.

UsernameRequiredErrorMessage

Error message displayed if the user has not entered a

 

user name.

PasswordRequiredErrorMessage

Error message displayed if the user has not entered a

 

password.

LoginButtonText

The text displayed for the login button.

LoginButtonType

The login button can be displayed as a link, button, or

 

image. For this purpose, you have to set this property

 

appropriately. Supported values are Link, Button, and

 

Image.

Continued