TheSessionobject remains as before, but the option to plug in your own session state provider is now available... What Are Your Choices?Given a relatively weak client, a stateless protoc
Trang 1are configured Highlight.aspxin the list of mappings and click the Edit button Figure 21-16 shows
the result
In the Executable text box, you can see that all.aspxpages map to theaspnet_isapi.dllfrom ASP.NET,
and that you can also specify which types of requests are allowed in the application You can allow either
all verbs (for example,GETorPOST) or you can specify which verbs are allowed access to the application
One important point regarding these mappings is that you do not see.html,.htm,.jpg, or other file
extensions such as.txtin the list Your application will not be passing requests for these files to ASP
.NET That might not be a big deal, but in working through the various security examples in this chapter,
you might want to have the same type of security measures applied to these files as to.aspxpages If,
for instance, you want all.htmlpages to be included in the forms authentication model that you require
for your ASP.NET application, you must add.html(or whatever file extension you want) to the list To
do so, click the Add button in the Application Configuration dialog
In the next dialog, you can add the ASP.NET DLL to the Executable text box, and the appropriate file
extension and verbs to the list before adding the mapping to your application’s mapping table This
example is illustrated in Figure 21-17
Figure 21-17
When dealing with the security of your site, you have to remember all the files that might not be included
in the default mapping list and add the ones you think should fall under the same security structure
If you are working with Windows Vista, you can get to the same functionality through the IIS Manager
In this tool, select Handler Mappings in the IIS section You will find a large list of mappings that have
already been provided This is illustrated in Figure 21-18
By highlighting the*.aspxoption and pressing the Edit button, you see that this extension is mapped to
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll, as shown in Figure 21-19
Pressing the Request Restrictions button provides a dialog that enables you to select the verbs allowed
(as shown in Figure 21-20)
Trang 2Figure 21-18
Figure 21-19
Trang 3Figure 21-20
Figure 21-21
Trang 4Using the ASP.NET MMC Snap-In
The ASP.NET MMC console (covered in more detail in Chapter 34) enables you to edit theweb.config
andmachine.configfiles using an easy-to-use GUI instead of having to dig through the text of those
files yourself to make the necessary changes This option is only available in either Windows Server 2003
or Windows XP Most of the items examined in this book can also be modified and changed using this
dialog The plug-in is available on the ASP.NET tab (see Figure 21-21) of your Web application running under IIS
When you make the changes directly in the dialog, you are also making the hardcoded changes to the
actual configuration files
Click the Edit Configuration button on the ASP.NET tab, and the ASP.NET Configuration Settings dialog opens There you can modify how your forms authentication model works in the GUI without going
to the application’sweb.configfile directly Figure 21-22 shows an example of working with forms
authentication in the GUI
Figure 21-22
Trang 5Using the IIS 7.0 Manager
You will not find the ASP.NET MMC Snap In within Windows Vista Instead, you will be able to make
all the same site modifications through the Internet Information Services (IIS) Manager (as shown in
Figure 21-23)
Figure 21-23
After making any changes through this dialog, you can select the Apply Changes link in the Actions
pane and it will notify you if the changes made have been saved When successful, the changes made are
applied to the site’sweb.configfile
Summar y
This chapter covered some of the foundation items of ASP.NET security and showed you how to apply
both authentication and authorization to your Web applications It reviewed some of the various
authen-tication and authorization models at your disposal, such as Basic, Digest, and Windows Integrated
Authentication Other topics included forms-based authentication and how to construct your own
forms-based authentication models outside of the ones provided via ASP.NET 3.5 by using the
member-ship and role management capabilities it provides The chapter also discussed how to use authentication
properties within your applications and how to authorize users and groups based on those properties
Trang 6State Management
Why is state management such a difficult problem that it requires an entire chapter in a book on
programming? In the old days (about 15 years ago), using standard client-server architecture meant
using a fat client and a fat server Perhaps your Visual Basic 6 application could talk to a database
The state was held either on the client-side or in the server-side database Typically, you could
count on a client having a little bit of memory and a hard drive of its own to manage state The
most important aspect of traditional client/server design, however, was that the client was always
connected to the server It’s easy to forget, but HTTP is a stateless protocol For the most part,
a connection is built up and torn down each time a call is made to a remote server Yes, HTTP
1.1 includes a keep-alive technique that provides optimizations at the TCP level Even with these
optimizations, the server has no way to determine that subsequent connections came from the
same client
Although the Web has the richness of DHTML and Ajax, JavaScript, and HTML 4.0 on the client
side, the average high-powered Intel Core Duo with a few gigabytes of RAM is still being used
only to render HTML It’s quite ironic that such powerful computers on the client side are still so
vastly underutilized when it comes to storing state Additionally, although many individuals have
broadband, it is not universally used Developers must still respect and pay attention to the dial-up
users of the world When was the last time that your project manager told you that bandwidth was
not an issue for your Web application?
The ASP.NET concept of a Session that is maintained over the statelessness of HTTP is not a new
one, and it existed before ASP.NET and even before classic ASP It is, however, a very effective and
elegant way to maintain state There are, however, a number of different choices available to you,
of which the ASP.NET session is just one There have been a few subtle changes between ASP.NET
1.x and 2.0/3.5 that will be covered in this chapter TheSessionobject remains as before, but the
option to plug in your own session state provider is now available
Trang 7What Are Your Choices?
Given a relatively weak client, a stateless protocol such as HTTP, and ASP.NET on the server side, how
do you manage state on the Web? Figure 22-1 is a generalized diagram that identifies the primary means
available for managing state The problem is huge, and the solution range is even larger This chapter
assumes that you are not using Java applets or ActiveX controls to manage state Although these options
are certainly valid (although complex) solutions to the state problem, they are beyond the scope of
this book
Session Application ASP.Net worker process Web server
Hidden HTML form
field and/or JavaScript
array
Cookies (HTTP headers)
http:// /page.aspx?state=some State in the URL Client Browser
Cache
OOP session state
Figure 22-1
If you remember one thing about state management, remember this: There is no right answer Some
answers are more right than others, certainly; but there are many, many ways to manage state Think
about your last project How many days were spent trying to decide where you should manage state?
The trick is to truly understand the pros and cons of each method
To make an educated decision about a method, you should understand the lifecycle of a request and the
opportunities for state management at each point in the process:
1. A Web browser makes anHTTP GETrequest for a page on your server,http://myserver/
myapp/mypage.aspx This client Web browser has never visited your site before.
2. IIS and your ASP.NET application respond by returning HTML rendered bymypage.aspx
Additionallymypage.aspxreturns a cookie with a unique ID to track this Web browser
Remember that a cookie is actually a slightly abstract concept The cookie is set by
return-ing a Set-Cookie HTTP Header to the client The client then promises to return the values of
the cookie in every subsequent HTTP call in the HTTP header The state in this example is
actually an agreement between the client and server to bounce the cookie back-and-forth on
every request in response
3. The HTML that is returned may contain hidden text boxes such as<input type="hidden"
value="somestate"/> These text boxes are similar to cookies because they are passed back
to the server if the form on this page is submitted Cookies are set per domain; hidden form
fields are set per page
Trang 84. Upon the next request, the previously set cookies are returned to the server If this request
was the submission of the form as an HTTP POST, all fields in the Form are returned —
hidden or otherwise
5. The unique identifier that was set earlier as a cookie can now be used as a key into any kind
of server-side state mechanism That state might be as simple as an in-memory hashtable, or
as complicated as a SQL database
One of the repeating themes you might notice is the agreement between the client and the server to
pass information back and forth That information can be in the URL, in HTTP headers, or even in the
submitted Form as an input field
On the server side, you have a few options You’ll want to weigh the options based on the amount of
memory you have available, the amount of data you want to store, and how often you’ll require access
to the data
The following tables express each of the server-side and client-side options and list a few pros and cons for each
Server-Side Option Pros Cons
Application State Fast Shared among all users State is stored once per server in
multiple server configurations
Cache Object
(Application Scope)
Like the Application State but includes expiration via Dependencies (see Chapter 23 on caching)
State is stored once per server in multiple server configurations
Session State Three choices: in process, out of
process, DB-backed Can be configured as cookieless
Can be abused You pay a serialization cost when objects leave the process In process requires Web Server affinity
Cookieless configuration makes it easier to hijack
Database State can be accessed by any server
in a Web farm
Pay a serialization and persistence cost when objects leave the process
Requires a SQL Server license
On the client side, every available option costs you in bandwidth Each option involves passing data back and forth from client to server Every byte of data you store will be paid for twice: once when it is passed
to the server and once when it is passed back
Client-Side Option Pros Cons
for large amounts of data Inappropriate for
sensitive data Size cost is paid on every
HTTP Request and Response
Hidden Field Simple for page-scoped data Not appropriate for large amounts of data
Inappropriate for sensitive data
Trang 9Client-Side Option Pros Cons
ViewState Simple for page-scoped data Encoding of serialized object as binary
Base64-encoded data adds approximately 30 percent overhead Small serialization cost
Has a negative reputation, particularly with DataGrids
ControlState Simple for page-scoped
control-specific data
Like ViewState, but used for controls that require ViewState even if the developer has turned it off
QueryString (URL) Incredibly simple and often
convenient if you want your URLs to be modified directly
by the end user
Comparatively complex Can’t hold a lot of information Inappropriate for sensitive data Easily modified by the end user
These tables provided you with some of the server-side and client-side options The improvements to
caching in ASP.NET 2.0/3.5 are covered in Chapter 23
Understanding the Session Object in ASP.NET
In classic ASP, theSessionobject was held in-process (as was everything) to the IIS process The user
received a cookie with a unique key in the form of a GUID The Session key was an index into a dictionary
where object references could be stored
In all versions of ASP.NET theSessionobject offers an in-process option, but also includes an
out-of-process and database-backed option Additionally, the developer has the option to enable cookieless
session state where the Session key appears in the URL rather than being sent as a cookie
Sessions and the Event Model
TheHttpApplicationobject raises a series of events during the life of the HTTP protocol request:
❑ BeginRequest: This event fires at the beginning of every request
❑ AuthenticateRequest: This event is used by the security module and indicates that a request is
about to be authenticated This is where the security module, or you, determines who the user is
❑ AuthorizeRequest: This event is used by the security module and indicates that a request is
about to be authorized This is where the security module, or you, determines what the user is
allowed to do
❑ ResolveRequestCache: This event is used by the caching module to determine whether this
now-authorized request can bypass any additional processing
❑ AcquireRequestState: This event indicates that all session state associated with this HTTP
request is about to be acquired
Trang 10Session state is available to you, the developer, after theAcquireRequestState event
fires The session state key that is unique to each user is retrieved either from a
cookie or from the URL.
❑ PreRequestHandlerExecute: This is the last event you get before theHttpHandlerclass for this request is called
Your application code, usually in the form of a Page, executes at this point in
the process.
❑ PostRequestHandlerExecute: This is the event that fires just after theHttpHandleris called
❑ ReleaseRequestState: Indicates that the session state should be stored Session state is
persisted at this point, using whatever Session-state module is configured inweb.config
❑ UpdateRequestCache: All work is complete, and the resulting output is ready to be added to
the cache
❑ EndRequest: This is the last event called during a request
You can see from the preceding list thatAcquireRequestStateandReleaseRequestStateare two
significant events in the life of theSessionobject
By the time your application code executes, theSessionobject has been populated using the Session key that was present in the cookie, or as you see later, from the URL If you want to handle some processing
at the time the Session begins, rather than handling it inAcquireRequestState, you can define an event handler for theStartevent of a SessionState HttpModule
Sub Session_OnStart()
’this fires after session state has been acquired by the SessionStateModule
End Sub
The Session object includes both Start and End events that you can hook event
handlers to for your own needs However, the Session_OnEnd event is supported
only in the In-Process Session State mode This event will not be raised if you use
out-of-process State Server or SQL Server modes The Session ends, but your
handlers will never hear about it.
Pre- and post-events occur at almost every point within the life of an HTTP request Session state can be manipulated at any point afterAcquireRequestState, including in theGlobal.asaxwithin the
Session_OnStartevent
TheHttpSessionStateobject can be used within any event in a subclass of thePageobject Because
the pages you create in ASP.NET derive fromSystem.Web.UI.Page, you can access Session State as a
collection becauseSystem.Web.SessionState.HttpSessionStateimplementsICollection