ASP.NET Membership Provider and Role Manager


In the previous section, you saw how one approach for maintaining lists of valid users for an application when using Forms authentication is to store the details in the web.config file. However, doing this has the following disadvantages:

  • It is not very secure, though you can encrypt the passwords to improve security. Visitors to the site cannot view web.config files, but anyone with access to the server directly or through the local network might be able to access and view these files.

  • It is not very flexible, because you can only define users, and not roles or groups of users to which you want to grant permissions, in one operation. Instead, you must list and configure access for each user individually, and the options available for this are limited.

  • It is not very easy to maintain. You have to edit the file directly whenever you want to change the list of users or just update their passwords.

A better approach is to use a database to store details of each user. You can implement this yourself (the FormsAuthentication class has methods and properties that make this easier) and validate users in your own custom code routines. You could even implement your own system of account groups or roles this way.

However, ASP.NET provides all the features you need to use a database to store all kinds of security, user, and role membership details. It also provides a series of server controls that help you build the pages that users need and that administrators require to create accounts, change passwords, and maintain the login information and role membership for each user. The two features of ASP.NET that support this are:

  • The membership provider and the associated database tables and procedures

  • The role manager and its associated database tables and procedures

The ASP.NET Web Site Administration Tool supports most of the actions you need to take when managing users and roles. However, some configuration tasks are required first. In this section of the chapter, you will see how ASP.NET integrates the membership provider and role manager, and the options available for specifying the provider settings that are necessary before you start using the Web Site Administration Tool.

The ASP.NET Application Database

As you will have realized from the previous section, ASP.NET uses a database to store membership and roles information for your applications. Figure 11.3 shows the complete schema for this database. You can see from the table names that it stores much more than just user and role detailsit also holds personalization details, application details, and information about events that occur as ASP.NET executes.

Figure 11.3. The ASP.NET Application Database schema


Part of the configuration task that you must perform involves creating this database, and you will see how to do that later in this chapter in The ASP.NET Web Site Administration Tool section. First, however, you will see how ASP.NET knows where to find the database and the options you have for using different database servers and database locations.

ASP.NET Membership Provider Configuration

The ASP.NET membership provider manages the tables in the ASP.NET application database that store details of the users you define for that application or Web site. The <membership> section of web.config defines the configuration of the membership provider, including the connection to the database shown in Figure 11.3. Listing 11.7 shows the <membership> element (located within the <system.web> section) and the content.

The <membership> element consists of a series of one or more <add> elements within the <providers> section, each of which defines the parameters for a provider that will be available for the membership system to use. By default, it includes just the first one shown in Listing 11.7, named AspNet-SqlMembershipProvider. We have added two more to the list to demonstrate how you can choose a different configuration for your providers, if required.

The type attribute refers to the .NET class that implements the providerwe have removed the long version information string from the listing so that you can see the structure of the file more easily. In all three cases, the type in use is the default SqlMembershipProvider class that is provided as part of the ASP.NET framework.

The connectionStringName attribute refers to a value in the <connectionStrings> section of this web.config file, or a value defined in a web.config file nearer the root folder of this application. You will see more details of the <connectionStrings> section in the next section of this chapter.

The remaining attributes set specific properties of the provider that control how ASP.NET pages and controls can interact with it. Most are self-explanatory, and you will see how they relate to the ASP.NET server controls that manipulate the membership information toward the end of this chapter.

Listing 11.7. The <membership> Section of web.config

<system.web>   ...   <membership>     <providers>       <add name="AspNetSqlMembershipProvider"            type="System.Web.Security.SqlMembershipProvider, ..."            connectionStringName="LocalSqlServer"            applicationName="/"            enablePasswordRetrieval="false"            enablePasswordReset="true"            requiresQuestionAndAnswer="true"            requiresUniqueEmail="false"            passwordFormat="Hashed"            maxInvalidPasswordAttempts="5"            minRequiredPasswordLength="7"            minRequiredNonalphanumericCharacters="1"            passwordAttemptWindow="10"            passwordStrengthRegularExpression="" />       <!-- following added to use SQL Server 2005 database ->       <add name="Sql2005MembershipProvider"            type="System.Web.Security.SqlMembershipProvider, ..."            connectionStringName="SqlServer2005"            ... />       <!-- following uses remote SQL Server attached database ->       <add name="Sql2005RemoteMembershipProvider"            type="System.Web.Security.SqlMembershipProvider, ..."            connectionStringName="Sql2005Remote"            ... />     </providers>   </membership>   ... </system.web>

Notice that the three <add> elements in Listing 11.7 have unique names, even though they use the same built-in provider class. They also use different connectionStringName values. The listing intentionally omits the remaining attributes for the last two <add> elements to aid clarity; however, they exist in the file and are the same as the first <add> element.

Using a remote server allows you to centralize the membership and other information across multiple servers and use a failover database system for high-availability scenarios, if you wish.


Specifying the Database Connection Strings

The <add> elements in the <membership> section of web.config correspond to values defined in the <connectionStrings> section. Listing 11.8 shows an example <connectionStrings> section that contains three connection string definitions. These are, in order:

  • A connection to the local SQL Server Express Edition database that is an optional component you can install with Visual Studio 2005. SQL Server 2005 and SQL Server Express Edition can auto-attach an .mdf database file as they connect. The AttachDBFilename and User Instance properties of the connection string specify that this will occur, and they provide the required location and instance information.

  • A connection to a local instance of SQL Server 2005 using the database auto-attach feature.

  • A connection to a remote SQL Server that has the database already attached, specifying the login details required to connect to this database.

Notice that all specify the database named aspnetdb in the file named aspnetdb.mdf. This is the default database name, though you can specify a different name if you wish when you create the database. The physical location, when using the auto-attach feature, is the App_Data subfolder within the root of the Web site or Web application virtual directory.

Note that the <connectionStrings> element does not reside within the <system.web> section, because it stores connection strings for all other types of applications (such as Windows Forms applications) as well as Web Forms pages.


Creating and Using Custom Providers

It should be clear from the preceding discussion that the provider model for membership (and for role management, as you will see shortly) is completely pluggable and extensibleyou can replace the default ASP.NET providers with your own custom providers, or with third-party providers, to take information from any data source and in any format. There is not sufficient room in this book to cover building custom providers, but Microsoft provides plenty of information and resources to help if you decide to take that approach. The article "Building Custom Providers for ASP.NET 2.0 Membership" describes the process in detail and contains a sample Active Directory provider. You can find this article at http://msdn.microsoft.com/library/en-us/dnaspp/html/bucupro.asp.

Listing 11.8. The <connectionStrings> Section of web.config

<connectionStrings>   <add name="LocalSqlServer"        connectionString="data source=.\SQLEXPRESS;                          Integrated Security=SSPI;                          AttachDBFilename=|DataDirectory|aspnetdb.mdf;                          User Instance=true"        providerName="System.Data.SqlClient" />   <!-- following added to use SQL Server 2005 database ->   <add name="SqlServer2005"        connectionString="data source=localhost;                          Integrated Security=SSPI;                          AttachDBFilename=|DataDirectory|aspnetdb.mdf;                          User Instance=true"        providerName="System.Data.SqlClient" />   <!-- following added to use remote SQL Server attached database ->   <add name="Sql2005Remote"        connectionString="data source=myremoteserver;                          Initial Catalog=aspnetdb;                          User ID=myusername;                          Password=secret"        providerName="System.Data.SqlClient" /> </connectionStrings>

The ASP.NET Provider Toolkit, developed by the ASP.NET team, is also available. This explains the provider design pattern and contains custom site map providers and Access database providers. You can find the toolkit at http://msdn.microsoft.com/ASP.NET/downloads/providers/.

ASP.NET Role Manager Configuration

Having looked at the configuration of the built-in membership provider in ASP.NET, you will not be surprised to discover that the built-in role provider follows much the same pattern. The <roleManager> section of web.config defines a list of providers that are available. It contains, by default, two providers:

  • The SqlRoleProvider uses the same database as the membership provider to hold details of the roles and role membership, and you can configure the roles and members using the ASP.NET Web Site Administration Tool.

  • The WindowsTokenRoleProvider is a read-only provider, and exposes information about roles for a specific Windows user account. It takes this information from the account groups held in Active Directory or on your server or local machine, depending on the configuration. You cannot create, add, or delete roles with this provider.

Listing 11.9 shows the <roleManager> section of an example web.config file that contains the two default role manager providers. It also contains two more entries that use the SqlRoleProvider, but this time connecting to a local and a remote instance of SQL Server 2005, and using auto-attach and a pre-attached database. In fact, the connection details are, as you would expect, stored in the <connectionStrings> section and referenced just as the membership providers you saw in the previous sections of this chapter were referenced.

You will find a useful Microsoft patterns & practices guide to using role manager in ASP.NET 2.0 at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/paght000013.asp.




ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net