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

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

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

C H A P T E R 2 1

■ ■ ■

Membership

On one hand, forms authentication solves the critical fundamentals for implementing secure, custom login forms for your ASP.NET applications. On the other hand, the tasks you have to accomplish for implementing the login forms and communicating with the underlying credential store are almost always the same for every web application, and they’re tedious. You should keep in mind one more point: forms authentication provides the infrastructure for authenticating users only. If you are using a custom credentials store, you have to write administration applications for managing users.

That’s what the ASP.NET team received as feedback from the developer community. Therefore, the team has added the new Membership API to ASP.NET 2.0; the Membership API is a framework based on top of the existing forms authentication infrastructure. When using the Membership API, you even don’t need to implement login pages or credential storage. In this chapter, you will learn about the details of the Membership API.

Introducing the ASP.NET Membership API

The Membership API framework provides you with a complete set of user management functions out of the box:

The ability to create and delete users either programmatically or through the ASP.NET web configuration utility.

The ability to reset passwords with the possibility of automatically sending password reset e-mails to the users if an e-mail address is stored for the affected user.

The ability to automatically generate passwords for users if these users are created programmatically in the background. Of course, these passwords can be sent to these users automatically if e-mail addresses are available for them.

The ability to find users in the underlying data store as well as retrieve lists of users and details for every user.

A set of prebuilt controls for creating login pages and registration pages and for displaying login states and different views for authenticated and unauthenticated users.

A layer of abstraction for your application so that the application has no dependency on the underlying data store through the so-called Membership provider classes. Any functionality listed until now therefore works completely independently from the underlying data store, and the data store can be replaced with other types of data stores without needing to modify the application at all.

Figure 21-1 shows the fundamental architecture of the Membership API, which consists of

providers, an API, and controls for creating appropriate user interfaces.

709

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

Figure 21-1. Architecture of the Membership API

The Membership API is designed to work completely independently from its underlying data store. You, as the application developer, primarily work with the controls provided by ASP.NET as well as the Membership class. The Membership class provides you with a set of methods for programmatically accessing users and roles of the store. These methods work with a Membership provider. This provider implements the access to the underlying data store. Table 21-1 describes the Membership components.

Table 21-1. The Membership API Components

Component

Description

Membership

The Membership class is the primary point of

 

interaction with the Membership API. It provides a

 

couple of methods for managing users, validating

 

users, and resetting user passwords.

MembershipCreateUserException

An exception is thrown if an error occurs when you try

 

to create a user through the Membership class.

MembershipUser

Represents a single user stored in a Membership API

 

credential store. This object contains all information

 

about this user and is returned through several

 

methods of the Membership class such as GetUser.

MembershipUserCollection

A collection of Membership users. For example, the

 

GetUsers method of the Membership class returns an

 

instance of this collection.

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

711

Component

Description

MembershipProvider

This is the base class that you derive from if you

 

want to create a custom Membership provider that

 

authenticates users against your custom credential

 

store.

MembershipProviderCollection

A collection of available Membership providers on the

 

machine and for this web application.

SqlMembershipProvider

An implementation of the MembershipProvider class

 

that works with SQL Server databases.

ActiveDirectoryMembershipProvider

An implementation of the MembershipProvider class

 

that works with Active Directory.

ActiveDirectoryMembershipUser

This class inherits all the functionality from

 

MembershipUser and adds some Active

 

Directory–specific properties.

 

 

ASP.NET ships with a provider for SQL Server and Active Directory (which enables you to create custom login pages for users stored in Active Directory). But the idea of providers is that they give you the ability to completely extend the infrastructure. Therefore, you can write your own Membership provider, which is basically a class that inherits from System.Web.Security.MembershipProvider. Membership providers are primarily configured through your web.config configuration file, which includes a new <membership /> section. You will learn more about custom Membership providers in Chapter 26.

Note Although the Membership API supports Active Directory as a provider, there is still a big difference between using Windows authentication and using the Membership API for authenticating users in your web application. When you configure your application to use Membership APIs, which are actually based on forms authentication, credentials are sent as clear text across the line (except you should use SSL), and a forms authentication ticket is used for authentication, as you learned in the previous chapter. On the other hand, when configuring Windows authentication, the user is authenticated either through NTLM or through Kerberos (in the case of Windows 2000 or Windows Server 2003 domains). Both methods are much more secure, because credentials are never sent across the line.

The Membership API is just used for managing and authenticating users. It does not implement any authorization functionality and doesn’t provide you with functionality for managing user roles. For this purpose, you have to use the Roles API. You will learn more about authorization and the role management functionality in Chapter 23.

Using the Membership API

Before you can use the ASP.NET Membership API and the security controls of ASP.NET, you have to complete a couple of steps:

1.Configure forms authentication in your web.config file as usual, and deny access to anonymous users.

2.Set up the Membership data store. For example, if you are using SQL Server, you have to create a couple of tables and stored procedures in a SQL Server database of your choice.

3.Configure the database connection string and the Membership provider you want to use in the application’s web.config file.

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

4.Create users in your Membership store using the ASP.NET web configuration utility or using a custom administration page.

5.Create a login page that uses the prebuilt Login control, or create a login page that uses the Membership class for validating the entered credentials and authenticating the user.

You can perform every configuration step except the provider configuration through the ASP.NET WAT, which includes a security wizard. Just select the Web Site ASP.NET Configuration menu from within Visual Studio. Figure 21-2 shows the WAT.

Figure 21-2. Setting up security in the WAT

If you are using ASP.NET on a machine with SQL Server 2005, you don’t even need to set up a data store and configure a Membership provider. Just launch the security wizard in the WAT, as shown in Figure 21-2, and start by adding users to your Membership storage. The required underlying data store will be created automatically for you when you create the first user. It will be created automatically even if you programmatically access the Membership store, because this functionality is provided through the SqlMembershipProvider.

But if you want to use your own database for data storage, you have to configure the Membership provider and connection information for the provider before you launch the security wizard. You will learn more about the configuration steps and how the Membership API works behind the scenes in the next sections of this chapter.

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

713

Configuring Forms Authentication

The Membership API is based on top of forms authentication and provides you with an out-of-the- box infrastructure for managing and authenticating users. Therefore, as the first step, you have to configure your application for forms authentication as usual. But you will structure the solution

a little bit differently this time. Often, the root directory of the web application grants access to anonymous users, while restricted resources are stored in subdirectories with restricted access. These subdirectories have their own web.config file that denies access to anonymous users. As soon as someone tries to access resources stored in this secured directory, the ASP.NET runtime automatically redirects the user to the login page. Typically, the root directory, which is accessible to anonymous users, includes features such as a login page and a registration page. You can see the structure of the web application in Figure 21-3, which displays the Solution Explorer of an already structured Visual Studio project.

Figure 21-3. The folder and file structure of a web application with a secured area

Therefore, in the root directory of the web application, you just configure forms authentication by including the following:

<system.web>

<authentication mode="Forms" /> </system.web>

As you can see, this configuration specifies forms authentication and allows anonymous access to the pages. In the secured subdirectory, you add an extra web.config file with the following contents:

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <system.web>

<authorization>

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

</system.web>

</configuration>

This configuration denies any anonymous user access to the website’s secured subfolder. If someone who is not authenticated tries to access resources placed in this directory, the ASP.NET runtime automatically redirects the user to the (publicly available) login page. Of course, you

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

have to create the login page on your own, but it’s much easier and much less work with the Membership API, as you will see when you learn about the Login control in the section “Using the Security Controls.”

Creating the Data Store

When using the Membership API, you have to set up a data store that will be used by your Membership provider. In the case of SQL Server, this means just creating a couple of database tables in either an existing or a new SQL Server database. Fortunately, the .NET Framework ships with a tool called aspnet_regsql.exe that can create the tables for you automatically. In the case of a custom provider, you have to prepare and configure the data store used by the custom provider according to the custom provider’s documentation.

You can use the aspnet_regsql.exe tool in two ways: either through a wizard interface or through the command line. If you just launch the tool without any parameters, it fires up the wizard interface that guides you through the process of creating a database, as shown in Figure 21-4.

Figure 21-4. The apsnet_regsql.exe wizard user interface

The wizard provides you with the option of either creating the necessary database or removing the tables from an existing database. If you select the <default> option for the database, it looks for a database called aspnetdb on the server you have specified. If it doesn’t exist already, it creates this database and creates the tables in this database. If the tables already exist in the target database, the wizard leaves them as they are.

As already mentioned, you can use the aspnet_regsql.exe tool from the command line as well. Actually, that’s a good way to automate your application’s setup—just call this tool from the command line and automatically set up the ASP.NET database tables required by your application. For example, to set up the Membership API database tables, you can execute the following command:

aspnet_regsql -S (local) -E -A all -d MyDatabase

Figure 21-5 shows the result of executing this command.

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

715

Figure 21-5. Executing aspnet_regsql.exe for installing the database

Table 21-2 describes the command-line switches of the aspnet_regsql.exe tool needed for the Membership API and related ASP.NET application services.

Table 21-2. Command-Line Switches of aspnet_regsql.exe

Switch

Description

-S servername

Specifies the SQL Server and instance for which you want to install the

 

ASP.NET database tables.

-U username

The SQL Server database user with which you want to connect to SQL Server.

-P password

If the -U switch is specified, you need to specify the password switch as well.

-E

If you don’t specify -U and -P, you automatically connect through Windows

 

authentication to the SQL Server instance specified in -S. With -E, you can

 

explicitly specify to connect through Windows authentication to the SQL

 

Server.

-C

Allows you to specify a full-fledged ODBC or OLEDB connection string for

 

connecting to the database.

-sqlexportonly

Creates the SQL scripts for the specified option without installing them on a

 

dedicated SQL Server instance.

-A

Installs application services. The valid options for this switch are all, m, r,

 

p, c, and w. The command in the previous example used the option all for

 

installing all application services; m is dedicated to Membership. r means role

 

services, p means ASP.NET profiles for supporting user profiles, and c stands

 

for personalization of web part pages.

-R

Uninstalls application services. This switch supports the same option as -A

 

and uninstalls the corresponding database tables for the application services.

-d

Lets you optionally specify the name of the database into which you want to

 

install the application services. If you don’t specify this parameter, a database

 

named aspnetdb is created automatically (as is the case with the <default>

 

option for the database in the wizard interface).

 

 

The aspnet_regsql.exe tool contains a couple of additional switches for installing SQL Server– based session state as well as for configuring the SQL cache dependency. For session state, please refer to Chapter 6. You will learn more about caching and cache dependencies in Chapter 11.

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

Database Scripts for ASP.NET Services

The aspnet_regsql.exe tool executes a couple of scripts for creating (or dropping) the Membershiprelated database and database tables. These scripts ship with the .NET Framework; you can find them in the .NET Framework directory, as shown in Figure 21-6.

Figure 21-6. The SQL scripts for installing and uninstalling SQL databases

Basically, two types of scripts exist: InstallXXX and the corresponding UninstallXXX scripts. When an InstallXXX script installs a set of database tables such as the set needed for the Membership API, the corresponding UninstallXXX script drops the same tables and databases. Table 21-3 describes the install scripts included with the .NET Framework.

Table 21-3. Membership API Installation Scripts

Script

Description

InstallCommon.sql

Installs some common tables and stored procedures necessary for

 

both the Membership and Roles APIs. This includes tables for

 

identifying ASP.NET applications that use other ASP.NET features

 

such as the Membership API, role service, or personalization.

InstallMembership.sql

Installs the database tables, stored procedures, and triggers used by

 

the Membership API. This includes tables for users, additional user

 

properties, and stored procedures for accessing this information.

InstallRoles.sql

Installs all database tables and stored procedures required for

 

associating users with application roles. These roles will be used for

 

authorization, as you will learn in Chapter 23.

InstallPersonalization.sql

Contains DDL for creating any table and stored procedure required

 

for creating personalized portal applications with web parts.

InstallProfile.sql

Creates all the necessary tables and stored procedures for

 

supporting ASP.NET 2.0 user profiles.

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

717

Script

Description

InstallSqlState.sql

Installs tables for persistent session state in the TEMP database of

 

SQL Server. That means every time the SQL Server service is shut

 

down, the session state gets lost.

InstallPersistSqlState.sql

Installs tables for persistent session state in a separate ASPState

 

database. That means the state stays alive even if the SQL Server

 

service gets restarted.

 

 

You can execute these scripts by either using osql.exe or using sqlcmd.exe. osql.exe is included with SQL Server 2000 editions, and sqlcmd.exe is included with SQL Server 2005 editions for executing scripts from the command line. For example, to install the common database tables on a SQL Server Express Edition, you can execute the following command:

sqlcmd -S (local)\SQLExpress -E -i InstallCommon.sql

The -S switch specifies the server and instance name for the target SQL Server. Usually you will not use an instance name (which is specified after the \), but SQL Server Express Edition will be installed as a named instance so that you can install more versions and instances of SQL Server on the same machine. Therefore, for SQL Server Express Edition, you have to specify the instance name, which is SQLExpress by default. With the -E switch you specify to access SQL Server through Windows authentication, and finally through the -i switch you can specify the input SQL script that should be executed. Figure 21-7 shows the result of executing the previous command.

Figure 21-7. Installing ASP.NET database tables on SQL Server Express

File-Based SQL Server Store

SQL Server 2005 supports a file-only database mode that allows you to access SQL Server databases directly through their MDF files without creating or attaching them in a SQL Server instance. With this feature it is possible to just copy the application’s database file with the application files onto the target server and run the application. The SQL Server provider then uses a connection string