Tải bản đầy đủ (.pdf) (10 trang)

Professional ASP.NET 3.5 in C# and Visual Basic Part 81 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (283.62 KB, 10 trang )

Evjen c16.tex V2 - 01/28/2008 2:51pm Page 757
Membership and Role
Management
The authentication and authorization of users are important functions in many Web sites and
browser-based applications. Traditionally, when working with Microsoft’s Windows Forms
applications (thick-client), you depended on Windows Integrated Authentication; when working
with browser-based applications (thin-client), you used forms authentication.
Forms authentication enabled you to take requests that were not yet authenticated and redirect
them to an HTML form using HTTP client-side redirection. The user provided his login information
and submitted the form. After the application authenticated the request, the user received an HTTP
cookie, which was then used on any subsequent requests. This kind of authentication was fine
in many ways, but it required developers to build every element and even manage the back-end
mechanics of the overall system. This was a daunting task for many developers and, in most cases,
it was rather time-consuming.
ASP.NET 3.5 includes an authentication and authorization management service that takes care
of the login, authentication, authorization, and management of users who require access to your
Web pages or applications. This outstanding membership and role management service is an easy-to-
implement framework that works out of the box using Microsoft SQL Server as the back-end data
store. This framework also includes an API that allows for programmatic access to the capabilities
of both the membership and role management services. In addition, a number of membership and
role management–focused server controls make it easy to create Web applications that incorporate
everything these services have to offer.
Before you look at the membership and role management features of ASP.NET 3.5, here’s a quick
review of authentication and authorization. This is vital to understand before proceeding.
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 758
Chapter 16: Membership and Role Management
Authentication
Authentication is a process that determines the identity of a user. After a user has been authenticated,
a developer can determine if the identified user has authorization to proceed. It is impossible to give
an entity authorization if no authentication process has been applied. Authentication is provided in
ASP.NET 3.5 using the membership service.


Authorization
Authorization is the process of determining whether an authenticated user is allowed access to any
part of an application, access to specific points of an application, or access only to specific datasets that
the application provides. When you authenticate and authorize users or groups, you can customize a
site based on user types or preferences. Authorization is provided in ASP.NET 3.5 using a role
management service.
ASP.NET 3.5 Authentication
ASP.NET 3.5 provides the membership management service to deal with authenticating users to access
a page or an entire site. The ASP.NET management service not only provides an API suite for managing
users, but it also gives you some server controls, which in turn work with this API. These server controls
work with the end user through the process of authentication. You look at the functionality of these
controls shortly.
Setting Up Your Web Site for Membership
Before you can use the security controls that are provided with ASP.NET 3.5, you first have to set up
your application to work with the membership service. How you do this depends on how you approach
the security framework provided.
By default, ASP.NET 3.5 uses the built-in
SqlMembershipProvider
instance for storing details about the
registered users of your application. For the initial demonstrations, the examples in this chapter work
with forms-based authentication. You can assume for these examples that the application is on the public
Internet and, therefore, is open to the public for registration and viewing. If it were an intranet-based
application (meaning that all the users are on a private network), you could use Windows Integrated
Authentication for authenticating users.
ASP.NET 3.5, as you know, offers a data provider model that handles the detailed management required
to interact with multiple types of underlying data stores. Figure 16-1 shows a diagram of the ASP.NET
3.5 membership service.
From the diagram, you can see that, like the rest of the ASP.NET provider models, the membership
providers can access a wide variety of underlying data stores. In this diagram, you can see the built-in
Microsoft SQL Server data store. You can also build your own membership providers to get at any other

custom data stores that work with user credentials. Above the membership providers in the diagram, you
can see a collection of security-focused server controls that utilize the access granted by the underlying
membership providers to work with the users in the authentication process.
758
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 759
Chapter 16: Membership and Role Management
Server Controls
Membership Server Controls
<asp : Login>, etc.
Membership API
Custom Provider
Custom
SqlMembershipProvider
SQL Server
7 .0/2000/2005/2008
Membership Providers
Data Stores
API
Figure 16-1
Adding an
<
authentication
>
Element to the web.config File
In order to have the forms authentication element in your Web application work with the membership
service, the first step is to turn on forms authentication within the
web.config
file. To accomplish this,
create a
web.config

file (if you do not already have one in your application). Next, add the section shown
in Listing 16-1 to this file.
Listing 16-1: Adding forms authentication to the web.config file
<
?xml version="1.0" encoding="utf-8"?
>
<
configuration
>
<
system.web
>
<
authentication mode="Forms" /
>
<
/system.web
>
<
/configuration
>
The simple addition of the <
authentication
> element to the
web.config
file turns on everything
that you need to start using the membership service provided by ASP.NET 3.5. To turn on the forms
authentication using this element, you simply give the value
Forms
to the

mode
attribute. This is a
forms authentication example, but other possible values of the
mode
attribute include
Windows
,
Passport
,
or
None
.
IIS authentication schemes include basic, digest, and Integrated Windows Authentication. Passport
authentication points to a centralized service provided by Microsoft that offers a single login and core
profile service for any member sites. It costs money to use Passport, which has also recently been depre-
ciated by Microsoft.
Because the
mode
attribute in our example is set to
Forms
, you can move on to the next step of adding
users to the data store. You can also change the behavior of the forms authentication system at this point
by making some modifications to the
web.config
file. These possibilities are reviewed next.
759
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 760
Chapter 16: Membership and Role Management
Adding a
<

forms
>
Element to the web.config File
Using forms authentication, you can provide users with access to a site or materials based upon
credentials they input into a Web-based form. When an end user attempts to access a Web site, he is
entering the site using anonymous authentication, which is the default authentication mode. If he
is found to be anonymous, he can be redirected (by ASP.NET) to a specified login page. After the end
user inputs the appropriate login information and passes the authentication process, he is provided with
an HTTP cookie, which can be used in any subsequent requests.
You can modify the behavior of the forms-based authentication by defining that behavior within a
<
forms
> section in the
web.config
file. You can see the possibilities of the forms authentication setting
in Listing 16-2, which shows possible changes to the
<
forms
> section in the
web.config
file.
Listing 16-2: Modifying the forms authentication behavior
<
?xml version="1.0" encoding="utf-8"?
>
<
configuration
>
<
system.web

>
<
authentication mode="Forms"
>
<
forms name=".ASPXAUTH"
loginUrl="Login.aspx"
protection="All"
timeout="30"
path="/"
requireSSL="false"
slidingExpiration="true"
cookieless="UseDeviceProfile" /
>
<
/authentication
>
<
/system.web
>
<
/configuration
>
You can set these as you wish, and you have plenty of options for values other than the ones that are
displayed. Also, as stated earlier, these values are not required. You can use the membership service
right away with only the configuration setting that is shown in Listing 16-1.
You can find some interesting settings in Listing 16-2, however. You can really change the behavior of
the forms authentication system by adding this
<
forms

> element to the
web.config
file. If you do this,
however, make sure that you have the
<
forms
> element nested within the <
authentication
> elements.
The following list describes the possible attributes of the
<
forms
> element:

name
: Defines the name used for the cookie sent to end users after they have been authenti-
cated. By default, this cookie is named
.ASPXAUTH
.

loginUrl
: Specifies the page location to which the HTTP request is redirected for logging in the
user if no valid authentication cookie (
.ASPXAUTH
or otherwise) is found. By default, it is set to
Login.aspx
.

protection
: Specifies the amount of protection that you want to apply to the cookie that is

stored on the end user’s machine after he has been authenticated. The possible settings include
All
,
None
,
Encryption
,and
Validation
. You should always attempt to use
All
.

timeout
: Defines the amount of time (in minutes) after which the cookie expires. The default
value is 30 minutes.
760
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 761
Chapter 16: Membership and Role Management

path
: Specifies the path for cookies issued by the application.

requireSSL
: Defines whether you require that credentials be sent over an encrypted wire (SSL)
instead of clear text.

slidingExpiration
: Specifies whether the timeout of the cookie is on a sliding scale. The default
value is
true

. This means that the end user’s cookie does not expire until 30 minutes (or the time
specified in the
timeout
attribute) after the last request to the application has been made. If the
value of the
slidingExpiration
attribute is set to
false
, the cookie expires 30 minutes from
the first request.

cookieless
: Specifies how the cookies are handled by ASP.NET. The possible values include
UseDeviceProfile
,
UseCookies
,
AutoDetect
,and
UseUri
. The default value is
UseDevicePro-
file
. This value detects whether to use cookies based on the user agent of the device.
UseCookies
requires that all requests have the credentials stored in a cookie.
AutoDetect
auto-determines whether the details are stored in a cookie on the client or within the URI (this
is done by sending a test cookie first). Finally,
UseUri

forces ASP.NET to store the details within
the URI on all instances.
Now that forms authentication is turned on, the next step is adding users to the Microsoft SQL Server
Express Edition data store,
ASPNETDB.mdf
.
Adding Users
To add users to the membership service, you can register users into the Microsoft SQL Server Express
Edition data store. The first question you might ask is, ‘‘Where is this data store?’’
Of course, there are a number of editions of Microsoft’s SQL Server that you can use to work through
the examples in this book. With that said, this chapter uses the default database the membership system
uses in creating users.
The Microsoft SQL Server provider for the membership system can use a SQL Server Express Edition file
that is structured specifically for the membership service (and other ASP.NET systems, such as the role
management system). ASP.NET is set to automatically create this particular file for you if the appropriate
file does not exist already. To create the
ASPNETDB.mdf
file, you work with the ASP.NET server controls
that utilize an aspect of the membership service. When the application requires the
ASPNETDB.mdf
file,
ASP.NET creates this file on your behalf in the
App_Data
folder.
After the data store is in place, it is time to start adding users to the data store.
Using the CreateUserWizard Server Control
The CreateUserWizard server control is one that can be used in conjunction with the membership service.
You can find this and the other controls mentioned in this chapter under the Login section in the Visual
Studio 2008 Toolbox. The CreateUserWizard control enables you to plug registered users into your data
store for later retrieval. If a page in your application allows end users to register for your site, you want,

at a minimum, to retrieve a login and password from the user and place these values in the data store.
This enables the end user to access these items later to log in to the application using the membership
system.
To make your life as simple as possible, the CreateUserWizard control takes complete control of
registration on your behalf. Listing 16-3 shows a simple use of the control.
761
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 762
Chapter 16: Membership and Role Management
Listing 16-3: Allowing end users to register with the site
<
%@ Page Language="VB" %
>
<
html xmlns=" />>
<
head runat="server"
>
<
title
>
Creating Users
<
/title
>
<
/head
>
<
body
>

<
form id="form1" runat="server"
>
<
asp:CreateUserWizard ID="CreateUserWizard1" Runat="server"
BorderWidth="1px" BorderColor="#FFDFAD" BorderStyle="Solid"
BackColor="#FFFBD6" Font-Names="Verdana"
>
<
TitleTextStyle Font-Bold="True" BackColor="#990000"
ForeColor="White"
><
/TitleTextStyle
>
<
/asp:CreateUserWizard
>
<
/form
>
<
/body
>
<
/html
>
This page simply uses the CreateUserWizard control and nothing more. This one control enables you to
register end users for your Web application. This particular CreateUserWizard control has a little style
applied to it, but this control can be as simple as:
<

asp:CreateUserWizard ID="CreateUserWizard1" Runat="server"
>
<
/asp:CreateUserWizard
>
When this code is run, an end user is presented with the form shown in Figure 16-2.
Figure 16-2
This screenshot shows the form as it would appear when filled out by the end user and includes informa-
tion such as the username, password, e-mail address, as well as a security question-and-answer section.
Clicking the Create User button places this defined user information into the data store.
762
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 763
Chapter 16: Membership and Role Management
The username and password provided via this control enable the end user to log in to the application
later through the Login server control. A Confirm Password text box is also included in the form of the
CreateUser server control to ensure that the passwordprovidedisspelledcorrectly.Ane-mailaddress
text box is included (in case end users forget their login credentials and want the credentials e-mailed
to them at some later point in time). Then finally, the security question and answer are used to verify
the identity of the end user before any credentials or user information is changed or later provided via
the browser.
After the Create User button on this form is clicked, the end user is presented with a confirmation of the
information being stored (see Figure 16-3).
Figure 16-3
Seeing Where Users Are Stored
Now that the CreateUserWizard control has been used to add a user to the membership service, look at
where this information is stored. If you used Visual Studio to create the Microsoft SQL Server Express
Edition file in which you want to store the user information, the file is created when the previous example
is run and you complete the form process as shown in the preceding figures. When the example is run
and completed, you can click the Refresh button in the Solution Explorer to find the
ASPNETDB.mdf

file,
whichislocatedinthe
App_Data
folder of your project. Many different tables are included in this file, but
you are interested in the
aspnet_Membership
table only.
When you open the
aspnet_Membership
table (by right-clicking the table in the Server Explorer and
selecting Show Table Data), the users you entered are in the system. This is illustrated in Figure 16-4.
The user password in this table is not stored as clear text; instead, it is hashed, which is a one way
form of encryption that cannot be reversed easily. When a user logs in to an application that is using
the ASP.NET 3.5 membership service, his or her password is immediately hashed and then compared
to the hashed password stored in the database. If the two hashed strings do not compare, the passwords
763
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 764
Chapter 16: Membership and Role Management
are not considered a match. Storing clear text passwords is considered a security risk, so you should
never do so without weighing the risk involved.
Figure 16-4
A note regarding the passwords used in ASP.NET 3.5: If you are having difficulty entering users because
of a password error, it might be because ASP.NET requires strong passwords by default. All passwords
input into the system must be at least seven characters, and contain at least one non-alphanumeric char-
acter (such as
[]
,
!
,
@

,
#
,or
$
). Whew! An example password of this combination is:
Bevjen7777$
Although this type of password is a heck of a lot more secure, a password like this is sometimes difficult
to remember. You can actually change the behavior of the membership provider so that it doesn’t require
such difficult passwords by reworking the membership provider in the
web.config
file, as illustrated in
Listing 16-4.
Listing 16-4: Modifying the membership provider in web.config
<
configuration
>
<
system.web
>
764
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 765
Chapter 16: Membership and Role Management
<
membership
>
<
providers
>
<
clear /

>
<
add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed"
minRequiredNonalphanumericCharacters="0"
minRequiredPasswordLength="3" /
>
<
/providers
>
<
/membership
>
<
/system.web
>
<
/configuration
>
In this example, you have reworked the membership provider for SQL Server so that it does not actually
require any non-alphanumeric characters and allows passwords as small as three characters in length.
You do this by using the
minRequiredNonalphanumericCharacters
and
minRequiredPasswordLength

attributes. With these in place, you can now create users with these password rules as set forth in these
configuration settings. Modifying the membership provider is covered in more detail later in this chapter.
Working with the CreateUserWizard Control
When you work with the CreateUserWizard control, be aware of the
ContinueButtonClick()
and
the
CreatedUser()
events. The
ContinueButtonClick()
event is triggered when the Continue button
on the second page is clicked after the user has been successfully created (see Listing 16-5).
Listing 16-5: The ContinueButtonClick event
VB
Protected Sub CreateUserWizard1_ContinueButtonClick(ByVal sender As Object, _
ByVal e As System.EventArgs)
Response.Redirect("Default.aspx")
End Sub
C#
protected void CreateUserWizard1_ContinueButtonClick(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
In this example, after the user has been added to the membership service through the form provided
by the CreateUserWizard control, she can click the Continue button to be redirected to another page in
the application. This is done with a simple
Response.Redirect
statement. Remember when you use this
event, that you must add an
OnContinueButtonClick = "CreateUserWizard1_ContinueButtonClick"

to
the
<
asp:CreateUserWizard
> control.
The
CreatingUser()
event is triggered when a user is successfully created in the data store. The use of
this event is shown in Listing 16-6.
765
Evjen c16.tex V2 - 01/28/2008 2:51pm Page 766
Chapter 16: Membership and Role Management
Listing 16-6: The CreateUser event
VB
Protected Sub CreateUserWizard1_CreatingUser(ByVal sender As Object, _
ByVal e As System.EventArgs)
’ Code here
End Sub
C#
protected void CreateUserWizard1_CreatingUser(object sender, EventArgs e)
{
// Code here
}
Use this event if you want to take any additional actions when a user is registered to the service.
Incorporating Personalization Properties in the Registration Process
As you saw in the previous chapter on personalization, it is fairly simple to use the personalization
management system that comes with ASP.NET 3.5 and store user-specific details. The registration process
provided by the CreateUserWizard control is an ideal spot to retrieve this information from the user to
store directly in the personalization system. The retrieval is not too difficult to incorporate into your code.
The first step, as you learned in the previous chapter on personalization, is to have some personalization

points defined in the application’s
web.config
file. This is shown in Listing 16-7.
Listing 16-7: Creating personalization properties in the web.config file
<
configuration
>
<
system.web
>
<
profile
>
<
properties
>
<
add name="FirstName" /
>
<
add name="LastName" /
>
<
add name="LastVisited" /
>
<
add name="Age" /
>
<
add name="Member" /

>
<
/properties
>
<
/profile
>
<
/system.web
>
<
/configuration
>
Now that these properties are defined in the
web.config
file, you can use them when you create users in
the ASP.NET membership system. Again, using the CreateUserWizard control, you can create a process
that requires the user to enter his preferred username and password in the first step, and then the second
step asks for these custom-defined personalization points. Listing 16-8 shows a CreateUserWizard control
that incorporates this idea.
766

×