http handlers and http modules

Upload: nitinsingh24

Post on 07-Apr-2018

240 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/4/2019 HTTP Handlers and HTTP Modules

    1/22

    HTTP Handlers and HTTP Modules in ASP.NET

    Setting up the Sample Applications

    ASP.NET Request ProcessingHttp Handlers

    Registering HTTP Handlers and HTTP Handler Factories in ConfigurationFiles

    Use of HTTP Handlers by the ASP.NET RuntimeImplementing HTTP Handlers

    Session State in HTTP HandlersHTTP ModulesRegistering HTTP Modules in Configuration Files

    Use of HTTP Modules by the ASP.NET Runtime

    Implementing an HTTP Module for Providing Security Services

    In the Internet world, Web servers serve resources that have been put on the

    Internet and provide other services like security, logging, etc.

    At the beginning of the Internet era, clients' needs were very limited; .htm files wereoften satisfactory. As time passed, however, clients' requirements extended beyond

    the functionality contained in .htm files or static files.

    Developers needed a way to extend or complement the functionality of Web servers.

    Web server vendors devised different solutions, but they all followed a commontheme: "Plug some component into the Web server". All Web server complement

    technologies allowed developers to create and plug in components for enhancingWeb server functionality. Microsoft came up with ISAPI (Internet Server API);

    Netscape came up with NSAPI (Netscape Server API), etc.

    ISAPI is an important technology that allows us to enhance the capabilities of an

    ISAPI-compliant Web server (IIS is an ISAPI-compliant Web server). The followingcomponents serve this purpose:

    ISAPI Extensions

    ISAPI Filters

    ISAPI extensions are implemented by using Win32 DLLs. You can think of an ISAPI

    extension as a normal application. ISAPI extensions are the target of http requests.

    That means you must call them to activate them. For example, the following URLcalls the store.dll ISAPI extension and passes two values to it:

    http://www.myownwebsite.com/Store.dll?sitename=15seconds&location=USA

    Think of an ISAPI filter as just that: a filter. It sits between your Web server and the

    client. Every time a client makes a request to the server, it passes through the filter.

    Clients do not specifically target the filter in their requests, rather, clients simply

    send requests to the Web server, and then the Web server passes that request tothe interested filters.

    Filters can then modify the request, perform some logging operations, etc.

    It was very difficult to implement these components because of the complexities

    involved. One had to use C/C++ to develop these components, and for many,development in C/C++ is a pain.

    So what does ASP.NET offer to harness this functionality? ASP.NET offersHttpHandlers and HttpModules.

    http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#1#1http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#2#2http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#3#3http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#4#4http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#4#4http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#5#5http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#6#6http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#7#7http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#8#8http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#9#9http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#10#10http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#11#11http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#1#1http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#2#2http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#3#3http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#4#4http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#4#4http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#5#5http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#6#6http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#7#7http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#8#8http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#9#9http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#10#10http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/HTTP%20handlers.htm#11#11
  • 8/4/2019 HTTP Handlers and HTTP Modules

    2/22

    Before going into the details of these components, it is worth looking at the flow ofhttp requests as it passes through the HTTP modules and HTTP handlers.

    Setting up the Sample Applications

    I have created the following C# projects, which demonstrate different components ofthe application.

    NewHandler (HTTP handler)

    Webapp (Demonstrates HTTP handler) SecurityModules (HTTP module)

    Webapp2 (Demonstrated HTTP module)

    To install the applications:

    Extract all the code from the attached zip file .

    Create two virtual directories named webapp and webapp2; point these

    directories to the actual physical folders for the Webapp and Webapp2 webapplications.

    Copy the Newhandler.dll file from the NewHandler project into the bindirectory of webapp web application.

    Copy the SecurityModules.dll file from the SecurityModules project into thebin directory of webapp2 web application.

    ASP.NET Request Processing

    ASP.NET request processing is based on a pipeline model in which ASP.NET passes

    http requests to all the modules in the pipeline. Each module receives the httprequest and has full control over it. The module can play with the request in any way

    it sees fit. Once the request passes through all of the HTTP modules, it is eventuallyserved by an HTTP handler. The HTTP handler performs some processing on it, and

    the result again passes through the HTTP modules in the pipeline.

    Notice that during the processing of an http request, only one HTTP handler will be

    called, whereas more than one HTTP modules can be called.

    Http Handlers

    HTTP handlers are the .NET components that implement theSystem.Web.IHttpHandler interface. Any class that implements the IHttpHandler

    interface can act as a target for the incoming HTTP requests. HTTP handlers aresomewhat similar to ISAPI extensions. One difference between HTTP handlers and

    ISAPI extensions is that HTTP handlers can be called directly by using their file name

    in the URL, similar to ISAPI extensions.

    HTTP handlers implement the following methods.

    Method

    NameDescription

    ProcessRequestThis method is actually the heart of all http handlers. This method iscalled to process http requests.

    IsReusable

    This property is called to determine whether this instance of httphandler can be reused for fulfilling another requests of the same

    type. HTTP handlers can return either true or false in order to specifywhether they can be reused.

    http://g/Kumud/Csharp%20and%20ASP.NET%20Course%20Material/Tutorials/handouts/020417.ziphttp://g/Kumud/Csharp%20and%20ASP.NET%20Course%20Material/Tutorials/handouts/020417.zip
  • 8/4/2019 HTTP Handlers and HTTP Modules

    3/22

    These classes can be mapped to http requests by using the web.config ormachine.config file. Once that is done, ASP.NET will instantiate http handler

    whenever the corresponding request comes in. We will see how to specify all of thesedetails in web.config and/or machine.config files.

    ASP.NET also supports the creation of http handlers by means of theIHttpHandlerFactory interface. ASP.NET provides the capability of routing http

    requests to an object of the class that implements the IHttpHandlerFactory interface.Here, ASP.NET utilizes the Factory design pattern. This pattern provides an interface

    for creating families of related objects without specifying their concrete classes. In

    simple terms, you can consider such a class as a factory that creates http handlerobjects depending on the parameters passed to it. We don't have to specify aparticular http handler class to instantiate; http handler factory takes care of it. The

    benefit of this is if in the future the implementation of the object that implements theIHttpHandler interface changes, the consuming client is not affected as long as the

    interface remains the same.

    These are following methods in IHttpHandlerFactory interface:

    Method

    NameDescription

    GetHandlerThis method is responsible for creating the appropriate handler andreturns the reference out to the calling code (the ASP.NET runtime).Handler object returned by this method should implement the

    IHttpHandler interface.

    ReleaseHandler

    This method is responsible for releasing the http handler once

    request processing is complete. The implementation of the factorydecides what it should do. Factory implementation can either actually

    destroy the instance or return it to a pool for future requests.

    Registering HTTP Handlers and HTTP Handler Factories in

    Configuration Files

    ASP.NET maintains its configuration information in the following configuration files:

    machine.config

    web.config

    machine.config file contains the configuration settings that apply to all the Web

    applications installed on that box.

    web.config file is specific to each Web application. Each Web application can have its

    own web.config file. Any sub directory of a Web application may have its ownweb.config file; this allows them to override the settings imposed by the parent

    directories.

    We can use and nodes for adding HTTP handlers to our Web

    applications. In fact the handlers are listed with nodes in between and nodes. Here is a generic example of adding an

    HTTP handler:

  • 8/4/2019 HTTP Handlers and HTTP Modules

    4/22

    In the above XML,

    The verb attribute specifies the HTTP verbs supported by the handler. If thehandler supports all of the HTTP verbs, simply use "*", otherwise list the

    supported verbs in a comma separated list. So if your handler supports onlyHTTP GET and POST, then verb attribute will be "GET, POST".

    The path attribute specifies the path or wildcard specification of the files for

    which this handler will be invoked. For example, if you want your handler tobe called only when test.xyz file is requested, then the path attribute will

    contain "test.xyz"; similarly if you want your handler called for any file having.xyz extension, the path attribute will contain "*.xyz".

    The type attribute specifies the actual type of the handler or handler factory

    in the form of a combination of namespace, class name and assembly name.ASP.NET runtime first searches the assembly DLL in the application's bin

    directory and then searches in the Global Assembly Cache (GAC).

    Use of HTTP Handlers by the ASP.NET Runtime

    Believe it or not, ASP.NET uses HTTP handlers for implementing a lot of its own

    functionality. ASP.NET uses handlers for processing .aspx, .asmx, .soap and otherASP.NET files.

    The following is the snippet from the machine.config file:

    . . . . . .

    . . . . . .

    You can see in the above configuration that all the requests for .aspx files are

    processed by the System.Web.UI.PageHandlerFactory class. Similarly all the requestsfor .config and other files, which should not be directly accessible to the clients, are

    handled by the System.Web.HttpForbiddenHandler class. As you might have alreadyguessed, this class simply returns an error to the client stating that these kinds of

    files are not served.

    Implementing HTTP Handlers

  • 8/4/2019 HTTP Handlers and HTTP Modules

    5/22

    Now we will see how to implement an HTTP handler. So what should our new handlerdo? Well, as I stated above, handlers are mostly used for adding new functionalities

    to Web servers; therefore, we will create a handler that handles new types of files,files that have a .15seconds extension. Once we implement this handler and register

    it in the web.config file of our Web application, all requests for .15seconds files willbe handled by this new handler.

    You might be thinking about the use of such a handler. Well, what if you want tointroduce a new kind of server scripting language or dynamic server file such as asp,

    aspx? You can write your own handler for this. Similarly, what will you do if you want

    to run Java servlets, JSPs and other server side Java components on IIS? One way ofdoing this is to install some ISAPI extension like Allaire or Macromedia Jrun. Or youcan write your own HTTP handler. Although it is a difficult task for third-party

    vendors like Allaire and Macromedia, it is a very attractive option because their HTTPhandlers will have access to all the new functionalities exposed by the ASP.NET

    runtime.

    Steps involved in implementing our HTTP handler are as follows:

    1. Write a class which implements IHttpHandler interface2. Register this handler in web.config or machine.config file.

    3. Map the file extension (.15seconds) to ASP.NET ISAPI extension DLL

    (aspnet_isapi.dll) in Internet Services Manager.

    Step1

    Create a new C# Class Library project in Visual Studio.NET and name it "MyHandler".Visual Studio.NET will automatically add a class named "Class1.cs" into the project.

    Rename it "NewHandler"; open this class in the code window and change the classname and constructor name to "NewHandler".

    The following is the code for the NewHandler class.

    using System;using System.Web;

    namespace MyHandler

    {///

    /// Summary description for NewHandler.///

    public class NewHandler : IHttpHandler{

    public NewHandler(){

    //// TODO: Add constructor logic here

    //}

    #region Implementation of IHttpHandler

    public void ProcessRequest(System.Web.HttpContext context){

    HttpResponse objResponse = context.Response ;

    objResponse.Write("Hello 15Seconds Reader ") ;objResponse.Write("") ;

    }

  • 8/4/2019 HTTP Handlers and HTTP Modules

    6/22

    public bool IsReusable{

    get{

    return true;}

    }#endregion

    }}

    As you can see in the ProcessRequest method, the HTTP handler has access to all

    ASP.NET intrinsic objects passed to it in its parameter through theSystem.Web.HttpContext object. Implementing the ProcessRequest method is simply

    extracting the HttpResponse object from the context object and then sending someHTML out to the client. Similarly, IsReusable returns true to designate that this

    handler can be reused for processing the other HTTP requests.

    Let's compile it and place it in the bin directory of the webapp virtual directory.

    Step 2

    Register this handler by adding the following text in the web.config file:

    Step 3

    Since we are creating a handler for handling files of a new extension, we also need

    to tell IIS about this extension and map it to ASP.NET. If we don't perform this stepand try to access the Hello.15seconds file, IIS will simply return the file rather than

    pass it to ASP.NET runtime. As a consequence, the HTTP handler will not be called.

    Launch the Internet Services Manager tool, right click on Default Web Site,

    select Properties, go to Home Directory tab and press Configuration button. Thiswill popup Application Configuration dialog. Click Add button and fill the

    Executable field with the path to the aspnet_isapi.dll file and fill .15seconds in theExtension field. Leave the other fields as is; the dialog box should look as follows:

    Close the Application Configuration and Default Web Site Properties dialogboxes by pressing the OK button.

    Now we are good to go. Launch Internet Explorer and go to the following url:

    http://localhost/webapp/hello.15seconds

    You should see the following page:

    Session State in HTTP Handlers

    Maintaining session state is one of the most common tasks that Web applications

    perform. HTTP handlers also need to have access to the session state. But session

  • 8/4/2019 HTTP Handlers and HTTP Modules

    7/22

    state is not enabled by default for HTTP handlers. In order to read and/or writesession data, HTTP handlers are required to implement one of the following

    interfaces:

    IRequiresSessionState

    IReadOnlySessionState.

    An HTTP handler should implement the IRequiresSessionState interface when it

    requires read-write access to the session data. If a handler only needs read access tosession data, then it should only implement the IReadOnlySessionState interface.

    Both of these interfaces are just marker interfaces and do not contain any methods.So if we want to enable session state for our NewHandler handler, then declare the

    NewHandler class as followed:

    public class NewHandler : IHttpHandler, IRequiresSessionState

    HTTP Modules

    HTTP modules are .NET components that implement the System.Web.IHttpModuleinterface. These components plug themselves into the ASP.NET request processingpipeline by registering themselves for certain events. Whenever those events occur,

    ASP.NET invokes the interested HTTP modules so that the modules can play with the

    request.

    An HTTP module is supposed to implement the following methods of the IHttpModule

    interface:

    MethodName

    Description

    Init

    This method allows an HTTP module to register its event handlers to the

    events in the HttpApplication object.

    DisposeThis method gives HTTP module an opportunity to perform any clean upbefore the object gets garbage collected.

    An HTTP module can register for the following events exposed by the

    System.Web.HttpApplication object.

    Event Name Description

    AcquireRequestStateThis event is raised when ASP.NET runtime is ready to

    acquire the Session state of the current HTTP request.

    AuthenticateRequestThis event is raised when ASP.NET runtime is ready to

    authenticate the identity of the user.

    AuthorizeRequestThis event is raised when ASP.NET runtime is ready toauthorize the user for the resources user is trying to

    access.

    BeginRequestThis event is raised when ASP.NET runtime receives anew HTTP request.

    DisposedThis event is raised when ASP.NET completes theprocessing of HTTP request.

    EndRequestThis event is raised just before sending the responsecontent to the client.

  • 8/4/2019 HTTP Handlers and HTTP Modules

    8/22

  • 8/4/2019 HTTP Handlers and HTTP Modules

    9/22

    We can use and nodes for adding HTTP modules to our Webapplications. In fact the modules are listed by using nodes in between

    and nodes.

    Since configuration settings are inheritable, the child directories inherit configuration

    settings of the parent directory. As a consequence, child directories might inheritsome unwanted HTTP modules as part of the parent configuration; therefore, we

    need a way to remove those unwanted modules. We can use the node forthis.

    If we want to remove all of the inherited HTTP modules from our application, we canuse the node.

    The following is a generic example of adding an HTTP module:

    The following is a generic example of removing an HTTP module from yourapplication.

    In the above XML,

    The type attribute specifies the actual type of the HTTP module in the form of

    class and assembly name.

    The name attribute specifies the friendly name for the module. This is thename that will be used by other applications for identifying the HTTP module.

    Use of HTTP Modules by the ASP.NET Runtime

    ASP.NET runtime uses HTTP modules for implementing some special features. The

    following snippet from the machine.config file shows the HTTP modules installed bythe ASP.NET runtime.

  • 8/4/2019 HTTP Handlers and HTTP Modules

    10/22

    All of the above HTTP modules are used by ASP.NET to provide services likeauthentication and authorization, session management and output caching. Since

    these modules have been registered in machine.config file, these modules areautomatically available to all of the Web applications.

    Implementing an HTTP Module for Providing Security Services

    Now we will implement an HTTP module that provides security services for our Web

    application. Our HTTP module will basically provide a custom authentication service.It will receive authentication credentials in HTTP request and will determine whether

    those credentials are valid. If yes, what roles are the user associated with? Throughthe User.Identity object, it will associate those roles that are accessible to our Web

    application pages to the user's identity.

    Following is the code of our HTTP module.

    using System;

    using System.Web;using System.Security.Principal;

    namespace SecurityModules

    {///

    /// Summary description for Class1.///

    public class CustomAuthenticationModule : IHttpModule

    {public CustomAuthenticationModule()

    {}

    public void Init(HttpApplication r_objApplication)

    {// Register our event handler with Application object.

    r_objApplication.AuthenticateRequest +=

    new EventHandler(this.AuthenticateRequest) ;}

    public void Dispose()

    {// Left blank because we dont have to do anything.

    }

    private void AuthenticateRequest(object r_objSender,EventArgs r_objEventArgs)

    {// Authenticate user credentials, and find out user roles.

    1. HttpApplication objApp = (HttpApplication) r_objSender ;2. HttpContext objContext = (HttpContext) objApp.Context ;

    3. if ( (objApp.Request["userid"] == null) ||4. (objApp.Request["password"] == null) )

    5. {6. objContext.Response.Write("Credentials not provided") ;

    7. objContext.Response.End() ;8. }

    9. string userid = "" ;

  • 8/4/2019 HTTP Handlers and HTTP Modules

    11/22

    10. userid = objApp.Request["userid"].ToString() ;11. string password = "" ;

    12. password = objApp.Request["password"].ToString() ;

    13. string[] strRoles ;14. strRoles = AuthenticateAndGetRoles(userid, password) ;

    15. if ((strRoles == null) || (strRoles.GetLength(0) == 0))16. {

    17. objContext.Response.Write("We are sorry but we could notfind this user id and password in our database") ;

    18. objApp.CompleteRequest() ;19. }

    20. GenericIdentity objIdentity = new GenericIdentity(userid,

    "CustomAuthentication") ;21. objContext.User = new GenericPrincipal(objIdentity, strRoles) ;

    }

    private string[] AuthenticateAndGetRoles(string r_strUserID,string r_strPassword)

    {string[] strRoles = null ;

    if ((r_strUserID.Equals("Steve")) &&(r_strPassword.Equals("15seconds"))){

    strRoles = new String[1] ;

    strRoles[0] = "Administrator" ;}

    else if ((r_strUserID.Equals("Mansoor")) &&(r_strPassword.Equals("mas")))

    {strRoles = new string[1] ;

    strRoles[0] = "User" ;}

    return strRoles ;

    }}

    }

    Let's explore the code.

    We start with the Init function. This function plugs in our handler for the

    AuthenticateRequest event into the Application object's event handlers list. This willcause the Application object to call this method whenever the AuthenticationRequest

    event is raised.

    Once our HTTP module is initialized, its AuthenticateRequest method will be called for

    authenticating client requests. AuthenticateRequest method is the heart of the

    security/authentication mechanism. In that function:

    Line 1 and Line 2 extract the HttpApplication and HttpContext objects. Line 3 throughLine 7 checks whether any of the userid or password is not provided to us. If this is

    the case, error is displayed and the request processing is terminated.

    Line 9 through Line 12 extract the user id and password from the HttpRequest

    object.

    Line 14 calls a helper function, named AuthenticateAndGetRoles. This function

    basically performs the authentication and determines the user role. This has been

  • 8/4/2019 HTTP Handlers and HTTP Modules

    12/22

    hard-coded and only two users are allowed, but we can generalize this method andadd code for interacting with some user database to retrieve user roles.

    Line 16 through Line 19 checks whether the user has any role assigned to it. If this isnot the case that means the credentials passed to us could not be verified; therefore,

    these credentials are not valid. So, an error message is sent to the client and therequest is completed.

    Line 20 and Line 21 are very important because these lines actually inform theASP.NET HTTP runtime about the identity of the logged-in user. Once these lines are

    successfully executed, our aspx pages will be able to access this information by usingthe User object.

    Now let's see this authentication mechanism in action. Currently we are only allowing

    the following users to log in to our system:

    User id = Steve, Password = 15seconds, Role = Administrator

    User id = Mansoor, Password = mas, Role = User

    Note that user id and password are case-sensitive.

    First try logging-in without providing credentials. Go tohttp://localhost/webapp2/index.aspx and you should see the following message.

    Now try logging-in with the user id "Steve" and password "15seconds". Go to

    http://localhost/webapp2/index.aspx?userid=Steve&password=15seconds and youshould see the following welcome message.

    Now try to log-in with the user id "Mansoor" and password "15seconds". Go tohttp://localhost/webapp2/index.aspx?userid=Mansoor&password=mas and you

    should see the following welcome page.

    Now try to log-in with the wrong combination of user id and password. Go to

    http://localhost/webapp2/index.aspx?userid=Mansoor&password=xyz and youshould see the following error message.

    This shows our security module in action. You can generalize this security module byusing database-access code in the AuthenticateAndGetRoles method.

    For all of this to work, we have to perform some changes in our web.config file. Firstof all, since we are using our own custom authentication, we don't need any other

    authentication mechanism. To specify this, change the node inweb.config file of webapp2 to look like this:

    Similarly, don't allow anonymous users to our Web site. Add the following to

    web.config file:

    Users should at least have anonymous access to the file that they will use forproviding credentials. Use the following configuration setting in the web.config file for

    specifying index.aspx as the only anonymously accessible file:

  • 8/4/2019 HTTP Handlers and HTTP Modules

    13/22

    Conclusion

    As you might have realized with HTTP handlers and modules, ASP.NET has put a lot

    of power in the hands of developers. Plug your own components into the ASP.NETrequest processing pipeline and enjoy the benefits.

    ASP.NET Security

    Windows Security

    CLR SecurityAuthentication and Authorization in ASP.NETForcing authentication

    Forms-based Authentication in ASP.NET

    The Basics The CLR provides a security model which is layered on top of that provided by theunderlying operating system. It acts as another "hurdle" one must cross in order to accessvarious resources and services.

    Windows Security

    Every OS thread runs on behalf of a security principal Tokens created at login time

    Tokens assigned to processes at launch time A thread is born without any token

    Tokens can be assigned to threads Thread token "overrides" process token

    http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#1#1http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#2#2http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#3#3http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#4#4http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#5#5http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#1#1http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#2#2http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#3#3http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#4#4http://psicf002/EplReference/Tools&Technology/Books/SynergiticsCDs/Course%20Material%20on%20DOTNET%20Csharptrack/data/contents/ASP%20dotnet%20Security.htm#5#5
  • 8/4/2019 HTTP Handlers and HTTP Modules

    14/22

    CLR Security

    Every CLR thread also has a principal

    Managed code can perform access checks A CLR principal has identity and roles

    Roles may represent real OS security groups Roles may represent something more generic

    Choosing CLR Principals

    Many ways of choosing the principal for the CLR thread Assign one directly to Thread.CurrentPrincipal Choose a principal policy for the AppDomain

    Don't do anything (default policy provides an unauthenticated principal) Note that assemblies may be granted or denied the right to set principal policy or change

    principals

    web.config

    ASP.NET configuration determines the principal for both the OSthread and the CLR thread These are completely orthogonal settings!

    IIS provides token for OS thread IIS authentication settings configured via metabase

    ASP.NET provides principal for CLR thread ASP.NET authentication configured via web.config

  • 8/4/2019 HTTP Handlers and HTTP Modules

    15/22

    Don't Forget IIS

    IIS authentication settings are important to consider

    Every request must first get past IIS IIS may deny requests due to authentication failures Enabling impersonation in ASP.NET simply enables handoff of the thread token from the IIS

    thread to the ASPNET_EWP.EXE worker thread Managed code only cares about the CLR principal The OS only cares about the token!

  • 8/4/2019 HTTP Handlers and HTTP Modules

    16/22

    Authentication and Authorization in ASP.NET

    Authentication answers the question "who are you?", while authorization answers thequestion "what can you do?". ASP.NET provides infrastructure for both.

    Authentication Modes

    ASP.NET supports several modes of authentication

    None Windows (default) Forms Passport To choose an authentication mode, configure the application's root web.config

  • 8/4/2019 HTTP Handlers and HTTP Modules

    17/22

    Forcing authentication

    IIS and ASP.NET won't authenticate unless absolutely necessary If anonymous access is good enough, why make more round-trips?

    Generally authentication is forced because the user is not authorized to get to a particularresource

    File-based authorization

    Authorization based on comparing an OS-level token with the target file's DACL FileAuthorizationModule implements this

    Only applies when using Windows auth mode Module returns 401 code on failed AccessCheck

    IIS turns 401 result into a lazy authn request

    web.config authorization

    Further authorization can be specified via web.config

    UrlAuthorizationModule implements this Applies to all authorization modes Permissions can be granted/denied to users/roles Construct user names carefully in web.config (authority\principal) when using Windows

    mode Module returns 401 code on denial

    IIS turns 401 result into a lazy authn request

  • 8/4/2019 HTTP Handlers and HTTP Modules

    18/22

    web.config hierarchy

    web.config authorization settings are applied hierarchically

    Ordered list of grants/denials formed Ordered from the closest to the furthest ancestor

    First match wins out (regardless of whether it's a grant or deny) Note that machine.config grants access to all users by default

    Forms-based Authentication in ASP.NET

  • 8/4/2019 HTTP Handlers and HTTP Modules

    19/22

    For public web sites, native Windows authentication using native Windows accounts isn't agood idea. Most developers write their own forms-based authentication schemes; ASP.NET

    simplifies this task considerably.

    Motivation

    Native Windows authentication is bad for public web servers It's an administrative headache

    Integrated Windows Authentication typically breaks when crossing firewalls and proxies Knowing a native Windows username and password can only make it easier for an attacker

    to break in Developers typically build their own forms-based login

    ASP.NET provides this infrastructure

    Overview

    Overview of forms-based authentication

    Cookie-based authentication scheme Automates redirection to and from login page

    Basic support for password management

    Configuration

    Select forms authentication mode and configure it Choose a login page If authentication is required, deny access to anonymous users

    Figure 2.9 shows the basic configuration

    The login page

    Writing a login page

    Collect user name and password via a form

  • 8/4/2019 HTTP Handlers and HTTP Modules

    20/22

    Optionally allow persistent login (this weakens security, so carefully consider offering thisoption)

    On submit, authenticate the user and use FormsAuthentication to redirect them back to thepage they wanted to visit originally

    Managing passwords in web.config

  • 8/4/2019 HTTP Handlers and HTTP Modules

    21/22

    ASP.NET provides simple password management via web.config Each user name listed with hashed password

    Must write a one-line program to generate password hashes Even though passwords are hashed, must protect web.config from download!

    Caveats

    Security issues you should be aware of Cookies can be stolen via http or the client's file system

    Secure sites should make sure the cookie is only sent via https This is easy to accidentally screw up unless your whole site requires SSL ( tags come

    to mind)

  • 8/4/2019 HTTP Handlers and HTTP Modules

    22/22

    Summary

    The CLR provides a security infrastructure which layers on that of the native operating

    system ASP.NET provides several authentication options

    ASP.NET provides DACL-based or config-based authorization options Forms authentication is convenient for public web sites, but should be used carefully toavoid introducing security holes