ASP. NET underlying encapsulation of HttpModule instance --- FormsAuthentication class analysis,

Source: Internet
Author: User

ASP. NET underlying encapsulation of HttpModule instance --- FormsAuthentication class analysis,

HttpModule is used to register an HttpApplication event. The managed code module implementing the IHttpModule interface can access all events in the request pipeline. So how is the most common ASP. NET Forms authentication module encapsulated?

I passed ASP today. NET life cycle, I used to like to do various applications, small programs, etc. Gradually I felt really boring, because as long as you know some basic syntax, it will use the relevant library or framework. If an error occurs, it is a bit of detail error. Strictly speaking, this is not a good exercise. It is a bit like a warm boiled frog. Of course, it cannot be said that this is not good, this can help us to master the use of the framework, increase the level of proficiency and related basic applications, but I personally think of the shortcomings... later, I thought that what I want to do is to let others use the frameworks and libraries I developed. What I want to study is the underlying architecture of the framework rather than the framework. After a lifecycle, the IIS cannot process the request. NET is still more proficient in processing requests. I will not deliberately understand it if I do not understand it. After all, my technical depth and breadth are there, and I will naturally understand it later. Compared with earlier versions, IIS7 expands an integration mode. IS 7.0 integrated pipeline IS a unified request processing pipeline that supports both local code and managed code modules. The managed code module that implements the IHttpModule interface can access all events in the request pipeline. For example, the managed code module can be used for ASP. NET web pages (. aspx files) and HTML pages (.htm or. html files) for ASP. NET Forms authentication. This is true even if IIS and ASP. NET regard HTML pages as static resources.

Functionally, HttpModule is equivalent to ISAPI Filter in IIS in ASP. NET. Before IIS delivers the received request to the corresponding ISAPI Extension, the registered ISAPI Filter intercepts the request first. The ISAPI Filter can obtain or even modify the request content to complete some additional functions. Similarly, when a request is transferred to ASP. after the. NET pipeline, the final HttpHandler object that is responsible for processing the request matches the request resource type. However, before Handler's official work, ASP. NET will first load and initialize all the configured HttpModule objects. During the initialization process, the HttpModule registers some functions to the corresponding event of the HttpApplication. In this case, the corresponding event will be triggered at a certain stage in the entire request processing lifecycle of the HttpApplication, event Handlers registered with HttpModule can also be executed.

All httpmodules implement the IHttpModule interface. The following is the definition of IHttpModule. The Init method is used to initialize the HttpModule itself. This method accepts an HttpApplication object. With this object, event registration is easy.

Many of the basic components (Infrastructure) provided by ASP. NET are implemented through the corresponding HttpModule. The following Classes list some typical httpmodules:

OutputCacheModule: implements the Output cache function;
SessionStateModule: Implements Session-based status on stateless HTTP protocol;
WindowsAuthenticationModule + FormsAuthenticationModule + PassportAuthentication-Module: implements three typical authentication methods: Windows authentication, Forms authentication, and Passport authentication;
UrlAuthorizationModule + FileAuthorizationModule: Implements Uri-based and Access Control List authorization.

With a nitpicking learning attitude, I studied the Forms authentication source code (in fact, it is not the source code, it was found by reflector)

See the source code of FormsAuthenticationModule:

Let's take a look at our most familiar Init method:

We can see that two HttpApplication pipeline events are registered here. Let's take a look at the explanation given by the AuthenticateRequest event:

Then let's look at the OnEnter method:

Then let's Click here to see the OnAuthenticate method:

  private void OnAuthenticate(FormsAuthenticationEventArgs e){    HttpCookie cookie = null;    if (this._eventHandler != null)    {        this._eventHandler(this, e);    }    if (e.Context.User == null)    {        if (e.User != null)        {            e.Context.SetPrincipalNoDemand(e.User);        }        else        {            bool cookielessTicket = false;            FormsAuthenticationTicket tOld = ExtractTicketFromCookie(e.Context, FormsAuthentication.FormsCookieName, out cookielessTicket);            if ((tOld != null) && !tOld.Expired)            {                FormsAuthenticationTicket ticket = tOld;                if (FormsAuthentication.SlidingExpiration)                {                    ticket = FormsAuthentication.RenewTicketIfOld(tOld);                }                e.Context.SetPrincipalNoDemand(new GenericPrincipal(new FormsIdentity(ticket), new string[0]));                if (!cookielessTicket && !ticket.CookiePath.Equals("/"))                {                    cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];                    if (cookie != null)                    {                        cookie.Path = ticket.CookiePath;                    }                }                if (ticket != tOld)                {                    if ((cookielessTicket && (ticket.CookiePath != "/")) && (ticket.CookiePath.Length > 1))                    {                        ticket = FormsAuthenticationTicket.FromUtc(ticket.Version, ticket.Name, ticket.IssueDateUtc, ticket.ExpirationUtc, ticket.IsPersistent, ticket.UserData, "/");                    }                    string cookieValue = FormsAuthentication.Encrypt(ticket, !cookielessTicket);                    if (cookielessTicket)                    {                        e.Context.CookielessHelper.SetCookieValue('F', cookieValue);                        e.Context.Response.Redirect(e.Context.Request.RawUrl);                    }                    else                    {                        if (cookie != null)                        {                            cookie = e.Context.Request.Cookies[FormsAuthentication.FormsCookieName];                        }                        if (cookie == null)                        {                            cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue) {                                Path = ticket.CookiePath                            };                        }                        if (ticket.IsPersistent)                        {                            cookie.Expires = ticket.Expiration;                        }                        cookie.Value = cookieValue;                        cookie.Secure = FormsAuthentication.RequireSSL;                        cookie.HttpOnly = true;                        if (FormsAuthentication.CookieDomain != null)                        {                            cookie.Domain = FormsAuthentication.CookieDomain;                        }                        e.Context.Response.Cookies.Remove(cookie.Name);                        e.Context.Response.Cookies.Add(cookie);                    }                }            }        }    }}

Note that all the classes related to Forms form authentication in this method are involved. Therefore, the FormsAuthenticationModule class is the most important module for Forms form authentication. classes created for decoupling operations are used here. I have to say that if I cannot write it out, I can understand the actual application of the HttpModule pipeline. I have a rough understanding of the module design. Here, I don't know if this class will remind you of ASP. net mvc Framework Authentication Filter, the implementation of the Filter is actually to use the Attribute feature to implement AOP aspect injection, therefore, in fact, this should also be able to add Attribute to implement AOP ., Of course this is my guess, but it should be feasible.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.