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

ASP.NET 4 Unleased - p 129 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 (744.1 KB, 10 trang )

ptg
1254
CHAPTER 27 Using ASP.NET Membership
<ContentTemplate>
<h1>Welcome Administrator!</h1>
</ContentTemplate>
</asp:RoleGroup>
</RoleGroups>
<LoggedInTemplate>
<h1>Welcome Average User!</h1>
</LoggedInTemplate>
</asp:LoginView>
</div>
</form>
</body>
</html>
If you request the page in Listing 27.31 after enabling the WindowsTokenRoleProvider, you
see the content displayed by the LoginView control only when you are a member of the
Windows Administrators group.
Configuring the AuthorizationStoreRoleProvider
Authorization Manager (AzMan) is a component of Windows Server 2003 and Windows
Server 2008. You can use Authorization Manager to define roles, tasks, and operations.
Authorization Manager supports more features than the authorization framework included
in ASP.NET Framework. For example, Authorization Manager supports role inheritance,
which enables you to easily define new roles based on existing roles.
Authorization Manager can store role information in three different ways. You can create
an authorization store by using an XML file, by using Active Directory, or by using Active
Directory Lightweight Directory Services (AD LDS).
Before you use Authorization Manager with the ASP.NET Framework, you need to create
an authorization store. Role information is stored in an XML file local to the application.
Follow these steps:


1. Launch Authorization Manager by executing the command AzMan.msc from a
command prompt (see Figure 27.15).
2. Switch Authorization Manager into Developer mode by selecting Action, Options
and selecting Developer mode.
3. Open the New Authorization Store dialog box by selecting Action, New
Authorization Store.
4. Select the XML file option and enter the path to your application’s App_Data folder
for the Store Name field. For example:
c:\Websites\MyWebsite\App_Data\WebRoles.xml
From the Library of Wow! eBook
ptg
1255
Using the Role Manager
27
FIGURE 27.15 Using Authorization Manager.
5. Create a new Authorization Manager application by right-clicking the name of your
authorization store and selecting New Application. Enter the name WebRoles for
your application (you can leave the other fields blank).
After you complete these steps, a new XML file is added to your application. This XML file
contains the authorization store.
Next, you need to configure the ASP.NET Role Manager to use the authorization store. The
web configuration file in Listing 27.32 uses the WebRoles.xml authorization store.
LISTING 27.32 Web.Config
<?xml version=”1.0” encoding=”utf-8”?>
<configuration>
<connectionStrings>
<add
name=”AZConnection”
connectionString=”msxml://~/App_Data/WebRoles.xml”/>
</connectionStrings>

<system.web>
<authentication mode=”Windows” />
<roleManager enabled=”true” defaultProvider=”MyRoleProvider”>
<providers>
<add
name=”MyRoleProvider”
type=”System.Web.Security.AuthorizationStoreRoleProvider”
connectionStringName=”AZConnection”
applicationName=”WebRoles”
/>
From the Library of Wow! eBook
ptg
1256
CHAPTER 27 Using ASP.NET Membership
FIGURE 27.16 Creating a new role definition with Authorization Manager.
</providers>
</roleManager>
</system.web>
</configuration>
You should notice a couple of things about the configuration file in Listing 27.32. First,
notice that the connection string uses the prefix msxml: to indicate that the connection
string represents a connection to an XML file.
Second, notice that the AuthorizationStoreRoleProvider includes an applicationName
attribute. This attribute must contain the name of the Authorization Manager application
that you created in the preceding steps.
After you complete these configuration steps, you can use the Authorization Manager just
as you do the default SqlMembershipProvider. You can define new roles by using either the
Web Site Administration Tool or the Authorization Manager interface (see Figure 27.16).
Caching Roles in a Browser Cookie
To improve your application’s performance, you can cache user roles in a browser cookie.

That way, the Role Manager does not have to perform a query against the Role provider
each and every time a user visits a page.
Caching roles in cookies is disabled by default. You can enable this feature with the web
configuration file in Listing 27.33.
From the Library of Wow! eBook
ptg
1257
Using the Role Manager
27
LISTING 27.33 Web.Config
<?xml version=”1.0” encoding=”utf-8”?>
<configuration>
<system.web>
<roleManager
enabled=”true”
cacheRolesInCookie=”true”
createPersistentCookie=”true” />
</system.web>
</configuration>
The web configuration in Listing 27.33 enables role caching. Furthermore, it causes the
roles to be cached in a persistent cookie rather than a session cookie.
WARNING
When you cache roles in a cookie, there is the potential that a user’s cached roles can
become out of sync with a user’s actual roles. If you update users’ roles on the server,
they don’t get updated on the browser. You can call the Roles.DeleteCookie()
method to delete the cached cookies.
You can set a number of attributes related to the roles cookie:
. cacheRolesInCookie—Enables you to cache user roles in a browser cookie (the
default value is false).
. cookieName—Enables you to specify the name for the roles cookie (the default value

is .ASPXROLES).
. cookiePath—Enables you to specify the path associated with the cookie. (The default
value is /.).
. cookieProtection—Enables you to encrypt and validate the roles cookie. Possible
values are All, Encryption, None, and Validation (the default value is All).
. cookieRequireSSL—Enables you to require that the roles cookie be transmitted over
a Secure Sockets Layer connection. (The default value is False.).
. cookieSlidingExpiration—Enables you to prevent a cookie from expiring just as
long as a user continues to request pages. (The default value is True.)
. cookieTimeout—Enables you to specify the amount of time in minutes before a
cookie times out. (The default value is 30.)
. createPersistentCookie—Enables you to create a persistent rather than a session
cookie. (The default value is False.)
From the Library of Wow! eBook
ptg
1258
CHAPTER 27 Using ASP.NET Membership
. domain—Enables you to specify the domain associated with the cookie. (The default
value is an empty string.)
. maxCachedResults—Enables you to specify the maximum number of roles that are
cached in a cookie. (The default is 25.)
Using the Roles Application Programming Interface
The Roles class exposes the main application programming interface for manipulating
roles. If you need to create roles programmatically, delete roles, or assign users to roles;
then you use the methods of the Roles class.
The Roles class includes the following methods:
. AddUsersToRole—Enables you to add an array of users to a role.
. AddUsersToRoles—Enables you to add an array of users to an array of roles.
. AddUserToRole—Enables you to add a user to a role.
. AddUserToRoles—Enables you to add a user to an array of roles.

. CreateRole—Enables you to create a new role.
. DeleteCookie—Enables you to delete the roles cookie.
. DeleteRole—Enables you to delete a particular role.
. FindUsersInRole—Enables you to return a list of users in a role that has a particu-
lar username.
. GetAllRoles—Enables you to retrieve a list of all roles.
. GetRolesForUser—Enables you to get a list of all roles to which a user belongs.
. GetUsersInRole—Enables you to get a list of users in a particular role.
. IsUserInRole—Enables you to determine whether a particular user is a member of a
particular role.
. RemoveUserFromRole—Enables you to remove a particular user from a particular role.
. RemoveUserFromRoles—Enables you to remove a particular user from an array of
roles.
. RemoveUsersFromRole—Enables you to remove an array of users from a particular
role.
. RemoveUsersFromRoles—Enables you to remove an array of users from an array of
roles.
. RoleExists—Enables you to determine whether a particular role exists.
The page in Listing 27.34 illustrates how you can use the methods of the Roles class. The
Page_Load() method creates two roles named Sales and Managers (if they don’t already
exist). Next, it assigns the current user to both roles. The body of the page contains a
GridView that displays all the roles to which the current user belongs (see Figure 27.17).
From the Library of Wow! eBook
ptg
1259
Using the Role Manager
27
FIGURE 27.17 Displaying a user’s roles.
LISTING 27.34 ShowRoles.aspx
<%@ Page Language=”C#” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

<script runat=”server”>
void Page_Load()
{
// If user is not authenticated, redirect to Login page
if (!Request.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
Response.End();
}
// Create two roles
if (!Roles.RoleExists(“Managers”))
Roles.CreateRole(“Managers”);
if (!Roles.RoleExists(“Sales”))
Roles.CreateRole(“Sales”);
// Add current user to both roles
if (!Roles.IsUserInRole(“Managers”))
Roles.AddUserToRole(User.Identity.Name, “Managers”);
From the Library of Wow! eBook
ptg
1260
CHAPTER 27 Using ASP.NET Membership
if (!Roles.IsUserInRole(“Sales”))
Roles.AddUserToRole(User.Identity.Name, “Sales”);
}
</script>
<html xmlns=” >
<head id=”Head1” runat=”server”>
<title>Show Roles</title>

</head>
<body>
<form id=”form1” runat=”server”>
<div>
<h1>Your Roles</h1>
<asp:GridView
id=”grdRoles”
DataSourceID=”srcRoles”
EmptyDataText=”You are not a member of any roles”
GridLines=”none”
Runat=”server” />
<asp:ObjectDataSource
id=”srcRoles”
TypeName=”System.Web.Security.Roles”
SelectMethod=”GetRolesForUser”
Runat=”server” />
</div>
</form>
</body>
</html>
Summary
In this chapter, you learned about the four security frameworks included in ASP.NET
Framework. In the first part, you learned how to authenticate users by enabling both
Forms and Windows authentication. You learned how to take advantage of several
advanced features of authentication such as cookieless authentication and cross-
application authentication.
You also learned how to authorize users to access particular resources. You not only
learned how to control access to ASP.NET pages, but also how you can control access to
image files and other files or pages.
From the Library of Wow! eBook

ptg
1261
Summary
27
Next, you learned how to use ASP.NET Membership to represent user information. You
learned how to use the Membership class to create users, delete users, and modify user
properties programmatically. You also explored the two Membership providers included
with ASP.NET Framework: SqlMembershipProvider and ActiveDirectoryMembership
Provider. Finally, we created a custom MembershipProvider: the XmlMembershipProvider.
The final section was devoted to the Role Manager. You learned how to configure the
three Role providers included in ASP.NET Framework: SqlRoleProvider,
WindowsTokenRoleProvider, and AuthorizationStoreRoleProvider. You also learned how
to take advantage of the Roles class to create roles, delete roles, and assign users to roles
programmatically.
From the Library of Wow! eBook
ptg
This page intentionally left blank
From the Library of Wow! eBook
ptg
CHAPTER 28
Maintaining
Application State
IN THIS CHAPTER
. Using Browser Cookies
. Using Session State
. Using Profiles
. Summary
Developers who are new to programming for the web
always have difficulty understanding the problem of main-
taining state. The HTTP protocol, the fundamental protocol

of the World Wide Web, is a stateless protocol. What this
means is that from a web server’s perspective, every request
is from a new user. The HTTP protocol does not provide
you with any method of determining whether any two
requests are made by the same person.
However, maintaining state is important in just about any
web application. The paradigmatic example is a shopping
cart. If you want to associate a shopping cart with a user
over multiple page requests, you need some method of
maintaining state.
This chapter looks at three methods included in ASP.NET 4
Framework for associating data with a particular user over
multiple page requests. In the first section, you learn how
to create and manipulate browser cookies. A browser cookie
enables you to associate a little bit of text with each website
user.
Next, you learn how to take advantage of
Session state,
which enables you to associate an arbitrary object with any
user. For example, you can store a shopping cart object in
Session state.
You learn how take advantage of cookieless Session state so
that you can use Session state even when a browser has
cookies disabled. You also learn how to make Session state
more robust by enabling out-of-process Session state.
From the Library of Wow! eBook

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×