ASP.NET Forms Authentication Overview

http://msdn.microsoft.com/en-us/library/7t6b43z4.aspx
Forms authentication lets you authenticate users by using your own code and then maintain an authentication token in a cookie or in the page URL. Forms authentication participates in the ASP.NET page life cycle through the FormsAuthenticationModule class. You can access forms authentication information and capabilities through the FormsAuthentication class.
To use forms authentication, you create a login page that collects credentials from the user and that includes code to authenticate the credentials. Typically you configure the application to redirect requests to the login page when users try to access a protected resource, such as a page that requires authentication. If the user's credentials are valid, you can call methods of the FormsAuthentication class to redirect the request back to the originally requested resource with an appropriate authentication ticket (cookie). If you do not want the redirection, you can just get the forms authentication cookie or set it. On subsequent requests, the user's browser passes the authentication cookie with the request, which then bypasses the login page.
You configure forms authentication by using the authentication configuration element. In the simplest case, you have a login page. In the configuration file, you specify a URL to redirect unauthenticated requests to the login page. You then define valid credentials, either in the Web.config file or in a separate file. The following example shows a section from a configuration file that specifies a login page and authentication credentials for the Authenticate method. The passwords have been encrypted by using the HashPasswordForStoringInConfigFile method.

<authentication mode="Forms">
   <forms name="SavingsPlan" loginUrl="/Login.aspx">
      <credentials passwordFormat="SHA1">
         <user name="Kim"
               password="07B7F3EE06F278DB966BE960E7CBBD103DF30CA6"/>
         <user name="John"
               password="BA56E5E0366D003E98EA1C7F04ABF8FCB3753889"/>
      </credentials>
   </forms>
</authentication>

After successful authentication, the FormsAuthenticationModule module sets the value of the User property to a reference to the authenticated user. The following code example shows how to programmatically read the identity of the forms-authenticated user.
C#
Visual Basic
Dim authUser2 As String = User.Identity.Name

String authUser2 = User.Identity.Name;


A convenient way to work with forms authentication is to use ASP.NET membership and ASP.NET login controls. ASP.NET membership lets you store and manage user information and includes methods to authenticate users. ASP.NET login controls work with ASP.NET membership. They encapsulate the logic to prompt users for credentials, validate users, recover or replace passwords, and so on. In effect, ASP.NET membership and ASP.NET login controls provide a layer of abstraction over forms authentication. These features replace most or all the work that you would ordinarily have to do to use forms authentication. For more information, see Managing Users by Using Membership and the ASP.NET Login Controls Overview.


You can also access forms authentication as a Windows Communication Framework (WCF) service by using the ASP.NET authentication service. The authentication service enables you to use forms authentication from any application that can send and consume messages in SOAP format. The authentication service accepts user credentials and returns a forms authentication cookie.

ASP.NET Authentication

http://msdn.microsoft.com/en-us/library/eeyk640h.aspx
Authentication is the process of obtaining identification credentials such as name and password from a user and validating those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.
ASP.NET implements authentication through authentication providers, the code modules that contain the code necessary to authenticate the requestor's credentials. The topics in this section describe the authentication providers built into ASP.NET.



TermDefinition
Windows Authentication Provider Provides information on how to use Windows authentication in conjunction with Microsoft Internet Information Services (IIS) authentication to secure ASP.NET applications.
Forms Authentication Provider Provides information on how to create an application-specific login form and perform authentication using your own code. A convenient way to work with forms authentication is to use ASP.NET membership and ASP.NET login controls, which together provide a way to collect user credentials, authenticate them, and manage them, using little or no code. For more information, see Managing Users by Using Membership and ASP.NET Login Controls Overview.
You might also consider using Windows Live ID for user authentication. For information about how to use Windows Live ID to authenticate users for you website

Exception Handling Application Block

This topic includes a series of brief sections that provide information to help you decide whether the Exception Handling Application Block is suitable for your requirements. This topic includes the following sections:

In addition to this introductory material, the documentation contains the following topics:
For details of the system requirements for the Exception Handling Application Block, see System Requirements. For details of the dependencies for the Exception Handling Application Block, see Application Block Dependencies.
The Exception Handling Application Block is designed to address the most common tasks developers face when they write applications that use exception handling. These tasks are arranged according to scenarios. Each scenario gives an example of a real-world situation, discusses the exception handling functions the situation requires, and shows the code that accomplishes the task.
The goal of arranging these tasks according to scenarios is to give the code some context. Instead of displaying an isolated group of methods, with no sense of where they can best be used, scenarios provide a setting for the code and describe situations that are familiar to many developers whose applications must handle exceptions.
The scenarios are the following:

The Exception Handling Application Block is designed to support the typical code contained in catch statements in application components. Instead of repeating this code (such as logging exception information) throughout identical catch blocks in an application component, the application block allows developers to encapsulate this logic as reusable exception handlers. Exception handlers are .NET classes that encapsulate exception handling logic and implement the Exception Handling Application Block interface named IExceptionHandler. The Exception Handling Application Block includes four exception handlers:
  • Wrap handler. This exception handler wraps one exception around another.
  • Replace handler. This exception handler replaces one exception with another.
  • Logging handler. This exception handler formats exception information, such as the message and the stack trace. Then the logging handler passes this information to the Enterprise Library Logging Application Block so that it can be published.
  • Fault Contract Exception Handler. This exception handler is designed for use at Windows Communication Foundation (WCF) service boundaries, and generates a new Fault Contract from the exception.
Users can extend the Exception Handling Application Block by implementing their own handlers. The Enterprise Library configuration tools provide the ability to configure the Exception Handling Application Block to use custom handlers. Developers do not have to modify the application block source code or rebuild the application block.
The Exception Handling Application Block lets you associate exception types with named policies. You do this by using the configuration tools. Policies specify the exception handlers that execute when the application block processes a particular exception type. You can chain these handlers together so that a series of them execute when the associated exception type is handled. The following are some examples of named policies and descriptions of what they might provide:
  • Base policy. This policy logs the exception and rethrows the original exception.
  • Secure policy. This policy logs the exception, replaces the original exception with a custom exception, and throws the new exception.
  • Expressive policy. This policy wraps the original exception inside another exception and throws the new exception.
Example Application Code
The following code shows how to execute the policy named "Data Access Policy" when an exception occurs.


C#
try
{
  // Run code.
}
catch(Exception ex)
{
  bool rethrow = ExceptionPolicy.HandleException(ex, " Data Access Policy");
  if (rethrow)
    throw;
}
 
                  



Visual Basic
Try
  ' Run code.
Catch ex As Exception
  Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, " Data Access Policy")
  If (rethrow) Then
    Throw
  End If
End Try
 
                  



Cc511859.note(en-us,MSDN.10).gifNote:
If you use the Unity Integration approach to create instances of objects from the Exception Handling Application Block, you must use the non-static façade named ExceptionManager. This class exposes the same API as the ExceptionPolicy class static façade. For more information about using the Unity Application Block to create and inject instances of Enterprise Library objects, see Creating Objects Using the Unity Application Block.
When to Use the Exception Handling Application Block

For information about how to develop exception management strategies, see the Design Guidelines for Exceptions. Although it does not specifically discuss the Exception Handling Application Block, it can help you to define a clear, consistent approach to handling exceptions. Use the Exception Management Application Block to help implement your strategy.
The Exception Handling Application Block is best used in situations that require uniform and flexible procedures for handling exceptions. For example, you might want consistent exception handling procedures for all components in a particular tier of an application's architecture. In addition, because of changing security or other operational issues, you might want the ability to change policies as needed, without requiring changes to the application source code. The Exception Handling Application Block, in conjunction with the Enterprise Library configuration tools, lets you accomplish both tasks.
For example, you could use the configuration tools to define a policy that uses handlers to replace exceptions that contain sensitive information with versions that do not include that information. The application block then implements this policy across the components that contain code that specifies this policy should be used.
The Exception Handling Application Block is not limited to cross-tier applications. It can also be used within a particular application. For example, you can define policies that log exception information or display exception information to the user.
In either case, policies are configured without changing the application's code. This makes them easy to maintain or change when new situations occur. Note that, in all cases, you should use the application block to perform only those tasks that are specific to exception handling and that do not intersect with the application's business logic. For example, you can remove the handlers that log an exception or wrap one exception in another without affecting such basic capabilities as updating a customer database.
Figure 1 illustrates examples of cross-layer and single-application component exception handling.
Cc511859.9454bca3-fe44-4e18-808b-1373855c65c0(en-us,MSDN.10).png
Figure 1
Examples of exception handling policies
In this example, exceptions that occur in the data access layer are logged and then wrapped inside another exception that provides more meaningful information to the calling layer. Within the business component layer, the exceptions are logged before they are propagated. Any exceptions that occur in the business component layer and that contain sensitive information are replaced with exceptions that no longer contain this information. These are sent to the user interface (UI) layer and displayed to the user.
Without the Exception Handling Application Block, typical exception handling code for a data access component might look like the following example.



Cc511859.note(en-us,MSDN.10).gifNote:
The code does not include implementations of the custom DataAccessException exception type, or the RunQuery, FormatException, and the Logging.Log methods. These methods represent typical ways to retrieve a DataSet and to log information.
C#
DataSet customersDataSet;
try
{
  customersDataSet = RunQuery("GetAllCustomers");
}
catch(Exception ex)
{
  string formattedInfo = FormatException(ex);
  Logging.Log(formattedInfo);
  throw new DataAccessException("Database access failure for query GetAllCustomers", e);
}
 
                  
Visual Basic
Dim customersDataSet As DataSet
 
Try
  customerDataSet = RunQuery("GetAllCustomers")
Catch ex As Exception
  Dim formattedInfo As String = FormatException(ex)
  Logger.Log(formattedInfo)
  Throw New DataAccessException("Database access failure for query GetAllCustomers", e)
End Try
 
                  

Code similar to this would be repeated in all the routines that perform different data access queries. To change the behavior of the exception handling code, you must update each routine that contained this code.
On the other hand, with the Exception Handling Application Block, the same application would have the following code.

Cc511859.note(en-us,MSDN.10).gifNote:
The code does not include an implementation of the RunQuery method. This method represents a typical way to retrieve a DataSet.
C#
Copy Code

DataSet customersDataSet;
 
try
{
  customersDataSet = RunQuery("GetAllCustomers");
}
catch(Exception ex)
{
  bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Policy");
  if (rethrow)
    throw;
}
 
                  
Visual Basic
Copy Code

Dim customersDataSet As DataSet
 
Try
  customerDataSet = RunQuery("GetAllCustomers")
Catch ex As Exception
  Dim rethrow As Boolean = ExceptionPolicy.HandleException(ex, "Data Access  Policy")
  If (rethrow) Then
    Throw
  End If
End Try
 
                  

The behavior of the exception handling code is determined by an exception handling policy named Data Access Policy. The application would have configuration settings for the Data Access Policy to indicate that exceptions of type System.Exception are passed to the Logging Exception Handler for the Exception Handling Application Block. To change the behavior of the exception handling code, you change configuration information only; you do not have to update application source code.
The Exception Handling Application Block is a complement to exception handling recovery code; it is not a replacement for it. If exceptions occur because of truly unusual circumstances, it can be impossible for an application to recover gracefully and finish the unit of work it has started. However, it is sometimes possible to recover. An example is an exception that occurs because a file is locked. The recovery code might direct the application to retry the file after waiting for some period of time. In such cases, exception handling recovery code should be implemented within the application code; it should not be implemented as a handler used by the Exception Handling Application Block. This is because it requires access to local variables, parameters, and other contextual data. This data is out of scope and inaccessible to handlers run by the Exception Handling Application Block.

The Difference Between the HAVING and WHERE Clauses in a SQL Query

Though the HAVING clause specifies a condition that is similar to the purpose of a WHERE clause, the two clauses are not interchangeable. Listed below are some differences to help distinguish between the two:


1.The WHERE clause specifies the criteria which individual records must meet to be selcted by a query. It can be used without the GROUP BY clause. The HAVING clause cannot be used without the GROUP BY clause.

2.The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.

3.The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions.

ASP.NET Page Life Cycle Overview

In general terms, the page goes through the stages outlined in the following table. In addition to the page life-cycle stages, there are application stages that occur before and after a request but are not specific to a page. For more information, see ASP.NET Application Life Cycle Overview for IIS 7.0.

Stage
Description

Page request
The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

Page initialization
During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Validation
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Postback event handling
If the request is a postback, any event handlers are called.

Rendering
Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

Unload
Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

ASP.NET Application Life Cycle Overview

http://msdn.microsoft.com/en-us/library/ms178473(VS.80).aspx

Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication

How Does It Work?
http://msdn.microsoft.com/en-us/library/aa302376.aspx#secnetap04_topic2

J.D. Meier, Alex Mackman, Michael Dunner, and Srinath Vasireddy
Microsoft Corporation
Published: November 2002
Last Revised: January 2006

Applies to:
Microsoft® ASP.NET
Microsoft® Windows® 2000
See the "patterns & practices Security Guidance for Applications Index" for links to additional security resources.



See the Landing Page for the starting point and a complete overview of Building Secure ASP.NET Applications.



Summary: This appendix provides additional material to explain in more detail how certain key concepts and processes discussed within the main body of the guide actually work. (9 printed pages)



Contents
IIS and ASP.NET Processing
ASP.NET Pipeline Processing
IIS and ASP.NET Processing
Note The information in this section applies to Internet Information Services (IIS) 5, running on Windows® 2000.

ASP.NET Web applications and Web services are processed by code that executes in a single instance of the ASP.NET worker process (aspnet_wp.exe), although on multi-processor computers, you can configure multiple instances, one per processor.

IIS authenticates callers and creates a Windows access token for the caller. If anonymous access is enabled within IIS, then a Windows access token for the anonymous Internet user account (typically, IUSR_MACHINE) is created by IIS.

Requests for ASP.NET file types are handled by an ASP.NET ISAPI extension (aspnet_isapi.dll), which runs in the IIS (inetinfo.exe) process address space. This uses a named pipe to communicate with the ASP.NET worker process as shown in Figure 1. IIS passes the Windows access token that represents the caller to the ASP.NET worker process. The ASP.NET Windows authentication module uses this to construct a WindowsPrincipal object and the ASP.NET File authorization module uses it to perform Windows access checks to ensure the caller is authorized to access the requested file.

Figure 1. IIS and ASP.NET communication
Note Access tokens are process relative. As a result, the ASP.NET ISAPI DLL running in inetinfo.exe calls DuplicateHandle to duplicate the token handle into the aspnet_wp.exe process address space and then passes the handle value through the named pipe.

Application Isolation

Separate application domains within the worker process (one per IIS virtual directory, or in other words, one per ASP.NET Web application or Web service) are used to provide isolation.



This is in contrast to classic ASP, where the application protection level, configured within the IIS metabase determined whether the ASP application should execute in process with IIS (inetinfo.exe), out of process in a dedicated instance of Dllhost.exe, or in a shared (pooled) instance of Dllhost.exe.



Important The process isolation level setting within IIS has no affect on the way ASP.NET Web applications are processed.

The ASP.NET ISAPI Extension

The ASP.NET ISAPI extension (aspnet_isapi.dll) runs in the IIS process address space (inetinfo.exe) and forwards requests for ASP.NET file types to the ASP.NET worker process through a named pipe.



Specific ASP.NET file types are mapped to the ASP.NET ISAPI extension by mappings defined within the IIS metabase. Mappings for standard ASP.NET file types (including .aspx, .asmx, .rem, .soap) are established when the .NET Framework is installed.



To view application mappings



1.From the Administrative Tools programs group, start Internet Information Services.

2.Right-click the default Web site on your Web server computer, and then click Properties.

3.Click the Home Directory tab, and then click Configuration.

A list of mappings is displayed. You can see which file types are mapped to Aspnet_isapi.dll.



IIS 6.0 and Windows Server

IIS 6.0 on Windows Server will introduce some significant changes to the current process arrangement.



You will be able to configure multiple application pools, each served by one or more process instances (w3wp.exe). This will provide additional fault tolerance and manageability benefits and will allow you to isolate separate applications in separate processes.

ASP.NET is integrated with the IIS 6.0 Kernel mode HTTP listener, which will allow requests to be passed directly from the operating system to the ASP.NET worker process.

ASP.NET Pipeline Processing

ASP.NET authentication and authorization mechanisms are implemented using HTTP module objects, which are invoked as part of the standard ASP.NET pipeline processing. Individual Web requests and responses pass through a pipeline of objects as shown in Figure 2.







Figure 2. ASP.NET pipeline processing



The ASP.NET pipeline model consists of an HttpApplication object, various HTTP module objects, and an HTTP handler object, together with their associated factory objects, which have been omitted from Figure 2 for clarity. An HttpRuntime object is used at the start of the processing sequence and an HttpContext object is used throughout the lifecycle of a request to convey details about the request and response.



The following list explains the responsibilities and operations performed by the objects associated with the HTTP processing pipeline:



The HttpRuntime object examines the request received from IIS and dispatches it to an appropriate instance of the HttpApplication object to process the request. There is a pool of HttpApplication objects in each application domain in Aspnet_wp.exe. There is a one-to-one mapping between application domains, HttpApplication objects and IIS virtual directories. In other words, ASP.NET treats separate IIS virtual directories as separate applications.

Note There is one instance of HttpRuntime in every Web application domain.

The HttpApplication objects control the pipeline processing. An individual HttpApplication object is created to handle each simultaneous HTTP request. HttpApplication objects are pooled for performance reasons.

HTTP module objects are filters that process HTTP request and response messages as they flow through the pipeline. They can view or alter the content of the request and response messages. HTTP modules are classes that implement IHttpModule.

HTTP handler objects are the endpoints for HTTP requests and provide the request processing for specific file types. For example, one handler processes requests for *.aspx files while another processes requests for *.asmx files. The HTTP response message is generated and returned from the HTTP handler. HTTP handlers are classes that implement IHttpHandler.

An HttpContext object is used throughout the pipeline to represent the current Web request and response. It is available to all modules in the pipeline and the handler object at the end of the pipeline. The HttpContext object exposes various properties including the User property which contains an IPrincipal object that represents the caller.

The Anatomy of a Web Request

The ASP.NET ISAPI library (Aspnet_isapi.dll) runs inside the IIS process address space (Inetinfo.exe). It dispatches requests to the HttpRuntime object within the ASP.NET worker process (Aspnet_wp.exe). The following set of actions occurs in response to each Web request received by ASP.NET:



The HttpRuntime object examines the request and forwards it to an instance of an HttpApplication object.

There is at least one HttpApplication object instance per application domain (the objects are pooled) and one application domain per IIS virtual directory. The initial request for a file in a particular virtual directory results in a new application domain and a new HttpApplication object being created.



A list of HTTP modules is read from Machine.config (they are contained within the <httpModules> element). Additional custom HTTP modules can be added to Web.config for a specific application. The default <httpModules> element within Machine.config is shown in the following code snippet. Copy Code <httpModules>

<add name="OutputCache"

type="System.Web.Caching.OutputCacheModule"/>

<add name="Session"

type="System.Web.SessionState.SessionStateModule"/>

<add name="WindowsAuthentication"

type="System.Web.Security.WindowsAuthenticationModule"/>

<add name="FormsAuthentication"

type="System.Web.Security.FormsAuthenticationModule"/>

<add name="PassportAuthentication"

type="System.Web.Security.PassportAuthenticationModule"/>

<add name="UrlAuthorization"

type="System.Web.Security.UrlAuthorizationModule"/>

<add name="FileAuthorization"

type="System.Web.Security.FileAuthorizationModule"/>

</httpModules>

The authentication modules hook the AuthenticateRequest event, while the authorization modules hook the AuthorizeRequest event.



The request passes through every module in the pipeline, although only a single authentication module is loaded. This depends on the configuration of the <authentication> element in Web.config. For example, the <authentication> element that follows results in the WindowsAuthenticationModule being loaded.



Copy Code <authentication mode="Windows" />

The activated authentication module is responsible for creating an IPrincipal object and storing it in the HttpContext.User property. This is vital, because the downstream authorization modules use this IPrincipal object in order to make authorization decisions.

In the absence of authentication (for example, where anonymous access is enabled within IIS and ASP.NET is configured with <authentication mode="None" />), there's a special non configured module that puts a default anonymous principal into the HttpContext. User property. As a result, HttpContext.User is always non-null after authentication.



If you implement a custom authentication module, code within the custom module must create an IPrincipal object and store it in HttpContext.User,



Note ASP.NET also wires up Thread.CurrentPrincipal based on HttpContext.User after the AuthenticateRequest event.

The HttpApplication fires the AuthenticateRequest event, which can be hooked in global.asax. This allows you to inject custom processing code; for example, to load the set of roles associated with the current user. However, note that the WindowsAuthenticationModule does this automatically. The role list is obtained from the set of Windows groups in which the authenticated Windows user is a member.

After the appropriate authentication module has finished its processing, the authorization modules are called if the request hasn't been aborted.

When the UrlAuthorizationModule is called, it checks for an <authorization> tag in Machine.config and Web.config. If present, it retrieves the IPrincipal object from HttpContext.User and checks to see whether the user is authorized to access the requested resource using the specified verb (GET, POST, and so on).

If the user is not authorized, the UrlAuthorizationModule calls HttpApplication.CompleteRequest, which aborts normal message processing. The UrlAuthorizationModule returns an HTTP 401 status code.



Next, the FileAuthorizationModule is called. It checks whether the IIdentity object in HttpContext.User.Identity is an instance of the WindowsIdentity class.

If the IIdentity object is not a WindowsIdentity, the FileAuthorizationModule performs no further processing.



If a WindowsIdentity is present, the FileAuthorizationModule calls the AccessCheck API (through P/Invoke) to see if the authenticated caller (whose access token has been passed to ASP.NET by IIS and is exposed by the WindowsIdentity object) is authorized to access the requested file. If the file's security descriptor contains at least a Read ACE in its DACL, the request is allowed to proceed. Otherwise the FileAuthorizationModule calls HttpApplication.CompleteRequest and returns a 401 status code.



Forms authentication processing

The FormsAuthenticationModule is activated when the following element is in Web.config.



Copy Code <authentication mode="Forms" />

Remember that for Forms authentication, you implement the Application_Authenticate event in Global.asax. For Forms authentication, the following sequence occurs:



Within this code, you can construct an IPrincipal object and store it in HttpContext.User. This typically contains the role list retrieved from a custom data store (normally a SQL Server database or Active Directory). The IPrincipal object is typically an instance of the GenericPrincipal class but could also be a custom IPrincipal class.

The FormsAuthenticationModule checks to see if you have created an IPrincipal object. If you have, it is used by the downstream authorization modules. If you haven't, the FormsAuthenticationModule constructs a GenericPrincipal (with no roles) and stores it in the context.



If there is no role information, any authorization checks (such as PrincipalPermssion demands) that demand role membership, will fail.



The UrlAuthorizationModule handles the AuthorizeRequest event. Its authorization decisions are based on the IPrincipal object contained within HttpContext.User.

Windows authentication processing

The WindowsAuthenticationModule is activated when the following element is in Web.config.



Copy Code <authentication mode="Windows" />

For Windows authentication, the following sequence occurs:



1.The WindowsAuthenticationModule creates a WindowsPrincipal object using the Windows access token passed to ASP.NET by IIS.

2.It uses P/Invoke to call Win32 functions to obtain the list of Windows group that the user belongs to. These are used to populate the WindowsPrincipal role list.

3.It stores the WindowsPrincipal object in HttpContext.User, ready to be used by the downstream authorization modules.

Event Handling

The HttpApplication object fires the set of events shown in Table 1. Individual HTTP modules can hook these events (by providing their own event handlers).



Table 1. Events fired by HttpApplication objects



Event Notes

BeginRequest Fired before request processing starts

AuthenticateRequest To authenticate the caller

AuthorizeRequest To perform access checks

ResolveRequestCache To get a response from the cache

AcquireRequestState To load session state

PreRequestHandlerExecute Fired immediately before the request is sent to the handler object

PostRequestHandlerExecute Fired immediately after the request is sent to the handler object

ReleaseRequestState To store session state

UpdateRequestCache To update the response cache

EndRequest Fired after processing ends

PreSendRequestHeaders Fired before buffered response headers are sent

PreSendRequestContent Fired before buffered response body sent





Note The HTTP handler executes in between the PreRequestHandlerExecute and PostRequestHandlerExecute events.

The last two events are non-deterministic and could occur at any time (for example, as a result of a Response.Flush). All other events are sequential.

You do not need to implement an HTTP module simply in order to hook one of these events. You can also add event handlers to Global.asax. In addition to the events listed in Table 1 (which can all be hooked by individual HTTP module objects), the HttpApplication object fires Application_OnStart and Application_OnEnd handlers, which will be familiar to ASP developers. These can be handled only within Global.asax. Finally, you can also implement custom event handlers within Global.asax for events fired by individual HTTP module objects. For example, the session state module fires Session_OnStart and Session_OnEnd events.



Implementing a Custom HTTP Module

To create your own HTTP module and insert it into the ASP.NET processing pipeline



1.Create a class that implements IHttpModule.

2.Place the assembly that contains the module in your application's \bin subdirectory or you can install it into the Global Assembly Cache.

3.Add an <HttpModules> element to your application's web.config, as shown below. Copy Code <system.web>

<httpModules>

<add name="modulename"

type="namespace. classname, assemblyname" />

</httpModules>

</system.web>

Implementing a Custom HTTP Handler

You may need to implement a custom HTTP handler, for example to handle the processing of files with the .data file extension.



To implement a custom HTTP handler



1.Add a mapping to the IIS metabase to map the .data file extension to the ASP.NET ISAPI extension (Aspnet_isapi.dll).

Right-click your application's virtual directory in the IIS MMC snap-in, click the Configuration button, and then click Add to create a new mapping for .data files to C:\Winnt\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll.



Note If you select the Check that file exists check box when adding the mapping, then the file must be physically present. This is usually what is wanted unless you have virtualized paths that don't map to a physical file. Virtualized paths ending with .rem or .soap are used by .NET Remoting.

2.Create a class that implements IHttpHandler (and optionally IHttpAsyncHandler if you want to handle requests asynchronously).

3.Place the assembly that contains the handler in your application's \bin subdirectory or you can install it into the Global Assembly Cache.

4.Add the handler to the processing pipeline by adding an <httpHandlers> section to your application's Web.config file. Copy Code <system.web>

<httpHandlers>

<add verb="*" path="*.data" type="namespace.classname, assemblyname" />

</httpHandlers>

</system.web>