If you create a custom Membership provider, you can use your existing database tables with ASP.NET Membership.. Second, imagine that you need to store membership information in a data st
Trang 1CHAPTER 27 Using ASP.NET Membership
enableSearchMethods—Enables the ActiveDirectoryMembershipProvider class to
use additional methods You must enable this attribute when using the Web Site
Administration Tool
attributeMapPasswordQuestion—Enables you to map the Membership security
ques-tion to an Active Directory attribute
attributeMapPasswordAnswer—Enables you to map the Membership security answer
to an Active Directory attribute
attributeMapFailedPasswordAnswerCount—Enables you to map the Membership
MaxInvalidPasswordAttempts property to an Active Directory attribute
attributeMapFailedPasswordAnswerTime—Enables you to map the Membership
PasswordAttemptWindow property to an Active Directory attribute
attributeMapFailedPasswordAnswerLockoutTime—Enables you to map the
Membership PasswordAnswerAttemptLockoutDuration property to an Active
Directory attribute
After you finish these configuration steps, you can use the ActiveDirectoryMembership
Provider in precisely the same way that you can use the SqlMembershipProvider When
you use the Login control, users are validated against Active Directory When you use the
CreateUserWizard control, new users are created in Active Directory
Creating a Custom Membership Provider
Because ASP.NET Membership uses the provider model, you can easily extend ASP.NET
membership by creating a custom Membership provider There are two main situations in
which you might need to create a custom Membership provider
First, imagine that you have an existing ASP.NET 1.x or ASP classic application You are
currently storing membership information in your own custom set of database tables
Furthermore, your table schemas don’t easily map to the table schemas used by the
SqlMembershipProvider
In this situation, it makes sense to create a custom Membership provider that reflects your
existing database schema If you create a custom Membership provider, you can use your
existing database tables with ASP.NET Membership
Second, imagine that you need to store membership information in a data store other
than Microsoft SQL Server or Active Directory For example, your organization might be
committed to Oracle or DB2 In that case, you need to create a custom Membership
provider to work with the custom data store
In this section, we create a simple custom Membership provider: an
XmlMembershipProvider that stores membership information in an XML file
Trang 2Unfortunately, the code for the XmlMembershipProvider is too long to place here The
code is included on the book’s website in a file named XmlMembershipProvider.cs, located
in the App_Code folder
The XmlMembershipProvider class inherits from the abstract MembershipProvider class
This class has more than 25 properties and methods that you are required to implement
For example, you are required to implement the ValidateUser() method The Login
control calls this method when it validates a username and password
You also are required to implement the CreateUser() method This method is called by
the CreateUserWizard control when a new user is created
The web configuration file used to set up the XmlMembershipProvider is contained in
Listing 27.25
LISTING 27.25 Web.Config
<?xml version=”1.0”?>
<configuration>
<system.web>
<authentication mode=”Forms” />
<membership defaultProvider=”MyMembershipProvider”>
<providers>
<add
name=”MyMembershipProvider”
type=”AspNetUnleashed.XmlMembershipProvider”
dataFile=”~/App_Data/Membership.xml”
requiresQuestionAndAnswer=”false”
enablePasswordRetrieval=”true”
enablePasswordReset=”true”
passwordFormat=”Clear” />
</providers>
</membership>
</system.web>
</configuration>
Notice that the XmlMembershipProvider supports a number of attributes For example, it
supports a passwordFormat attribute that enables you to specify whether passwords are
stored as hash values or as plain text (It does not support encrypted passwords.)
The XmlMembershipProvider stores membership information in an XML file named
Membership.xml, located in the App_Data folder If you want, you can add users to the file
Trang 3CHAPTER 27 Using ASP.NET Membership
by hand Alternatively, you can use the CreateUserWizard control or the Web Site
Administration Tool to create new users
A sample of the Membership.xml file is contained in Listing 27.26
LISTING 27.26 App_Data\Membership.xml
<credentials>
<user name=”Steve” password=”secret” email=”steve@somewhere.com” />
<user name=”Andrew” password=”secret” email=”andrew@somewhere.com” />
</credentials>
The sample code folder on the book’s website includes a Register.aspx, Login.aspx, and
ChangePassword.aspx page You can use these pages to try out different features of the
XmlMembershipProvider
WARNING
Dynamic XPath queries are open to XPath Injection Attacks in the same way that
dynamic SQL queries are open to SQL Injection Attacks When writing the
XmlMembershipProvider class, I avoided using methods such as the
SelectSingleNode() method to avoid XPath Injection Attack issues, even though
using this method would result in leaner and faster code Sometimes, it is better to be
safe than fast
Using the Role Manager
Instead of configuring authorization for particular users, you can group users into roles
and assign authorization rules to the roles For example, you might want to
password-protect a section of your website so that only members of the Administrators role can
access the pages in that section
Like ASP.NET Membership, the Role Manager is built on the existing ASP.NET
authentica-tion framework You configure role authorizaauthentica-tion rules by adding an authorizaauthentica-tion
element to one or more web configuration files
Furthermore, like ASP.NET Membership, the Role Manager uses the provider model You
can customize where role information is stored by configuring a particular Role provider
The ASP.NET Framework includes three role providers:
SqlRoleProvider—Enables you to store role information in a Microsoft SQL Server
database
WindowsTokenRoleProvider—Enables you to use Microsoft Windows groups to
repre-sent role information
Trang 4AuthorizationStoreRoleProvider—Enables you to use Authorization Manager to
store role information in an XML file, Active Directory, or Activity Directory
Lightweight Directory Services (ADLDS)
In the following sections, you learn how to configure each of these Role providers You
also learn how to manage role information programmatically by working with the Roles
application programming interface
Configuring the SqlRoleProvider
The SqlRoleProvider is the default role provider You can use the SqlRoleProvider to
store role information in a Microsoft SQL Server database The SqlRoleProvider enables
you to create custom roles You can make up any roles that you need
You can use the SqlRoleProvider with either Forms authentication or Windows
authenti-cation When Forms authentication is enabled, you can use ASP.NET Membership to
repre-sent users and assign the users to particular roles When Windows authentication is
enabled, you assign particular Windows user accounts to custom roles I assume, in this
section, that you use Forms authentication
WARNING
The Web Site Administration Tool does not support assigning users to roles when
Windows authentication is enabled When Windows authentication is enabled, you must
assign users to roles programmatically
The web configuration file in Listing 27.27 enables the SqlRoleProvider
LISTING 27.27 Web.Config
<?xml version=”1.0” encoding=”utf-8”?>
<configuration>
<system.web>
<roleManager enabled=”true” />
<authentication mode=”Forms” />
</system.web>
</configuration>
The Role Manager is disabled by default The configuration file in Listing 27.27 simply
enables the Role Manager Notice that the configuration file also enables Forms
authentication
If you don’t want to type the file in Listing 27.27, you can let the Web Site Administration
Tool create the file for you Open the Web Site Administration Tool in Visual Web
Trang 5ptg CHAPTER 27 Using ASP.NET Membership
FIGURE 27.10 Enabling Roles with the Web Site Administration Tool
Developer by selecting Website, ASP.NET Configuration Next, click the Security tab and
the Enable roles link (see Figure 27.10)
After you enable the Role Manager, you need to create some roles You can create roles in
two ways You can use the Web Site Administration Tool or you can create the roles
programmatically
Open the Web Site Administration Tool and click the Create or Manage Roles link located
under the Security tab At this point, you can start creating roles I’ll assume that you have
created a role named Managers
After you create a set of roles, you need to assign users to the roles Again, you can do this
by using the Web Site Administration Tool or you can assign users to roles programmatically
If you have not created any users for your application, create a user now by clicking the
Create User link under the Security tab Notice that you can assign a user to one or more
roles when you create the user (see Figure 27.11) You can click the Create or Manage
Roles link to assign roles to users at a later date
After you finish creating your roles and assigning users to the roles, you can use the roles
in the authentication section of a web configuration file For example, imagine that your
website includes a folder named SecretFiles and you want only members of the Managers
role to be able to access the pages in that folder The web configuration file in Listing 27.28
blocks access to anyone except members of the Managers role to the SecretFiles folder
Trang 6FIGURE 27.11 Assigning a new user to a role
LISTING 27.28 Web.Config
<?xml version=”1.0”?>
<configuration>
<system.web>
<authorization>
<allow roles=”Managers”/>
<deny users=”*”/>
</authorization>
</system.web>
</configuration>
The configuration file in Listing 27.28 authorizes Managers and denies access to everyone
else
If you prefer, you can manage authorization with the Web Site Administration Tool
Behind the scenes, this tool creates web configuration files that contain authorization
elements (in other words, it does the same thing as we just did)
Under the Security tab, click the Create Access Rules link Select the SecretFiles folder from
the tree view, the Managers role, Allow (see Figure 27.12) Click the OK button to create
Trang 7ptg CHAPTER 27 Using ASP.NET Membership
FIGURE 27.12 Creating authorization rules
the rule Next, create a second access rule to deny access to users not in the Managers role
Select the SecretFiles folder, All Users, Deny Click the OK button to add the new rule
Using a Different Database with the SqlRoleProvider
By default, the SqlRoleProvider uses the same Microsoft SQL Server Express database as
ASP.NET Membership: the AspNetDB.mdf database This database is created for you
auto-matically in your application’s root App_Data folder
If you want to store role information in another Microsoft SQL Server database, then you
must perform the following two configuration steps
Configure the database so that it contains the necessary database objects
Configure your application to use the new database
Before you can store role information in a database, you need to add the necessary tables
and stored procedures to the database The easiest way to add these objects is to use the
aspnet_regsql command-line tool This tool is located in the following folder:
\WINDOWS\Microsoft.NET\Framework\[version]
NOTE
You don’t need to navigate to the Microsoft.NET folder when you open the SDK
Command Prompt
Trang 8FIGURE 27.13 Using the SQL Server Setup Wizard
If you execute aspnet_regsql without any parameters, the ASP.NET SQL Server Setup
Wizard opens (see Figure 27.13) You can use this wizard to connect to a database and add
the necessary database objects automatically
Alternatively, you can set up a database by executing the following two SQL batch files
InstallCommon.sql
InstallRoles.sql
These batch files are located in the same folder as the aspnet_regsql tool
After you set up your database, you need to configure a new SqlRoleProvider that
includes the proper connection string for your database The web configuration file in
Listing 27.29 configures a new provider named MyRoleProvider that connects to a
data-base named MyDatadata-base located on a server named MyServer
LISTING 27.29 Web.Config
<?xml version=”1.0” encoding=”utf-8”?>
<configuration>
<connectionStrings>
<add
name=”MyConnection”
connectionString=”Data Source=MyServer;
➥Integrated Security=True;Initial Catalog=MyDatabase”/>
Trang 9CHAPTER 27 Using ASP.NET Membership
</connectionStrings>
<system.web>
<authentication mode=”Forms” />
<roleManager enabled=”true” defaultProvider=”MyRoleProvider”>
<providers>
<add
name=”MyRoleProvider”
type=”System.Web.Security.SqlRoleProvider”
connectionStringName=”MyConnection”/>
</providers>
</roleManager>
</system.web>
</configuration>
The configuration file in Listing 27.29 creates a new default RoleManager named
MyRoleProvider Notice that the MyRoleProvider provider includes a
connectionStringName attribute that points to the MyConnection connection
Configuring the WindowsTokenRoleProvider
When you use the WindowsTokenRoleProvider, roles correspond to Microsoft Windows
groups You must enable Windows authentication when using the
WindowsTokenRoleProvider You cannot use Forms authentication or ASP.NET
Membership with the WindowsTokenRoleProvider
The configuration file in Listing 27.30 configures the WindowsTokenRoleProvider as the
default provider
LISTING 27.30 Web.Config
<?xml version=”1.0” encoding=”utf-8”?>
<configuration>
<system.web>
<authentication mode=”Windows” />
<roleManager enabled=”true” defaultProvider=”MyRoleProvider”>
<providers>
<add
name=”MyRoleProvider”
type=”System.Web.Security.WindowsTokenRoleProvider” />
</providers>
</roleManager>
Trang 10FIGURE 27.14 Displaying different content to members of the Windows Administrators group
</system.web>
</configuration>
The page in Listing 27.31 contains a LoginView control The LoginView control displays
different content to the members of the Windows Administrators group than it displays to
everyone else (see Figure 27.14)
LISTING 27.31 ShowWindowsRoles.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Show Windows Roles</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:LoginView
id=”LoginView1”
Runat=”server”>
<RoleGroups>
<asp:RoleGroup Roles=”BUILTIN\Administrators”>