Pro ASP.NET 2.0 In CSharp 2005 (2005) [eng]
.pdf
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"
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.
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. |
|
|
