Application_AuthenticateRequest

Discussion in 'ASP .Net' started by =?Utf-8?B?Q2h1Y2sgUA==?=, Oct 18, 2007.

  1. I have an HttpModule with the code show below in it.
    It seems to work fine in development and in test. However on our production
    server (which does get used a lot more) it seems that the
    Application_AuthenticateRequest event doesn't fire after a while.

    Other websites on the same server that use the same module/dll don't have
    problems. Could something be happening to kill the event listeners and the
    init not being restarted because of the locking code? Or an Ajax problem?

    The websites use Forms Authentication.

    #region Intialize
    static object _initLock = new object();
    static bool _initialized = false;

    public virtual void Init(HttpApplication application)
    {


    if (!_initialized)
    {
    lock (_initLock)
    {
    if (!_initialized)
    {
    if (application == null) throw new
    ArgumentNullException("application");


    //this module is dependent on Exception handling
    module because we log authorization exceptions
    //exception handling module requires application
    settings in web.config and checks for them

    //Verify exception handling module is loaded
    if (null ==
    HttpContext.Current.ApplicationInstance.Modules.Get("ASPExceptionHandler"))
    throw new Exception("The Forms Authentication
    Module is dependent on the Exception Handling Module. Please add the module
    to your web.config.");

    //this will force read of the web.config; otherwise
    no checking of whether section is even present until first use
    Util.WebLogin.FormsAuthenticationConfiguration
    ConfigInfo =
    (Util.WebLogin.FormsAuthenticationConfiguration)ConfigurationManager.GetSection("FormsAuthenticationConfiguration");

    if (null == ConfigInfo)
    throw new Exception("The Forms Authentication
    Configuration section was not found in the web.config. Please add the section
    to your web.config.");


    m_ConfigInfo = ConfigInfo;

    application.AuthenticateRequest += new
    EventHandler(Application_AuthenticateRequest);
    application.EndRequest += new
    EventHandler(Application_EndRequest);

    _initialized = true;
    }
    }
    }
    }
    #endregion


    void Application_AuthenticateRequest(object sender, EventArgs e)
    {

    if (HttpContext.Current.Request.IsAuthenticated)
    {

    FormsCookie.UserData UserData = new FormsCookie.UserData();

    IpSpoofingCheck(UserData.RemoteAddress);

    //token still good check
    if (UserData.AuthenticationMode ==
    WebLogin.HowAuthenticated.TOKEN && m_ConfigInfo.TokenCardVerifyEachRequest)
    {
    TokenCard.AuthResults results =
    Util.WebLogin.TokenCard.LanlCookieValidate(m_ConfigInfo.TokenCardServerDnsName);
    if (!results.Result)
    {
    FormsCookie.Kill();

    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString(), true);
    }

    }

    //authentication mode use is allowed on this site
    if
    (!m_ConfigInfo.AuthenticationMethodsAllowed.Contains(UserData.AuthenticationMode.ToString().Split('_')[0]))
    {
    FormsCookie.Kill();

    HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString(), true); //Application_EndRequest will append allowed methods
    }
    }
    else //not authenticated
    {
    CheckForFullyQualifiedDomainName();
    }

    }

    /// <summary>
    /// If not a Fully Qualified Domain Name in Request, convert it
    /// </summary>
    /// <remarks>
    /// if the user specifies hostname without the domain (i.e., company
    not company.com, netbios resolution or network configuration appends domain)
    /// cookie sharing across the domain will fail because the cookie
    doman will be company not company.com
    /// </remarks>
    private void CheckForFullyQualifiedDomainName()
    {
    string requestURL = HttpContext.Current.Request.Url.AbsoluteUri;
    if (!(HttpContext.Current.Request.Url.Host == "localhost") &&
    !HttpContext.Current.Request.Url.Host.Contains("."))
    {
    string strFullyQualifiedHostName =
    System.Net.Dns.GetHostEntry(HttpContext.Current.Request.Url.Host).HostName;
    System.Text.RegularExpressions.Match match;
    Regex r = new Regex(@"^http(s)?://[-a-z0-9_.]*" +
    HttpContext.Current.Request.Url.Host, RegexOptions.IgnoreCase);
    match = r.Match(HttpContext.Current.Request.Url.ToString());
    int iMatchLength = match.Length;

    requestURL = requestURL.Remove(0, iMatchLength);
    requestURL =
    match.ToString().Replace(HttpContext.Current.Request.Url.Host,
    strFullyQualifiedHostName)
    + requestURL;

    HttpContext.Current.Response.Redirect(requestURL,
    true);//comeback and see me with fully qualified hostname.
    }

    }
    =?Utf-8?B?Q2h1Y2sgUA==?=, Oct 18, 2007
    #1
    1. Advertising

  2. When the application.EndRequest stops firing. The other websites continue to
    work.
    All the applications share the same application pool. If I recycle the
    pool, it works again for a little while.
    =?Utf-8?B?Q2h1Y2sgUA==?=, Oct 18, 2007
    #2
    1. Advertising

  3. Hi Chuck,

    First, I'm not sure if you've already known this or not: there might be
    multiple instances of an Http Module in a web application. One
    HttpApplication instance will only have one instance of each configured
    Http Module, but there might be mulitple HttpApplication instances since
    each request will need an instance. These instances will be reused by
    different requests.

    #INFO: Application Instances, Application Events, and Application State in
    ASP.NET
    http://support.microsoft.com/kb/312607


    In your code, note the static variable is shared among the entire AppDomain
    (the web application). Therefore second and other instances of
    HttpApplication will initialize a new instance of your Http Module without
    hooking up the AuthenticateRequest event.

    It appears to me that you're using the static variables to make sure the
    Init is only called once, actually you don't need this. In an
    HttpApplication instance, it's guranteed the Http Module will only be
    initialized once.

    Hope this helps.



    Regards,
    Walter Wang (, remove 'online.')
    Microsoft Online Community Support

    ==================================================
    When responding to posts, please "Reply to Group" via your newsreader so
    that others may learn and benefit from your issue.
    ==================================================

    This posting is provided "AS IS" with no warranties, and confers no rights.
    Walter Wang [MSFT], Oct 19, 2007
    #3
  4. Walter,

    Thanks,
    I didn't realize that multiple Modules instances could be present.

    I changed my code as shown below.
    I believe the !_initialized section will simulate the application_start
    event, so those things only will get run once.

    In a different module I put the following within the !_initialized section:
    AppDomain.CurrentDomain.UnhandledException += new
    UnhandledExceptionEventHandler(OnUhe);

    I guess this even hooks into AppDomain so it needs to be in !_initialized
    section.




    public virtual void Init(HttpApplication application)
    {

    application.AuthenticateRequest += new
    EventHandler(Application_AuthenticateRequest);
    application.EndRequest += new
    EventHandler(Application_EndRequest);

    // HttpModules can get reused and their can be multiple modules
    active.
    // The above events need to get called every init, the below
    just once per Application Start
    if (!_initialized)
    {
    lock (_initLock)
    {
    if (!_initialized)
    {
    if (application == null) throw new
    ArgumentNullException("application");

    //Verify exception handling module is loaded
    if (null ==
    HttpContext.Current.ApplicationInstance.Modules.Get("ASPExceptionHandler"))
    throw new Exception("The Forms Authentication
    Module is dependent on the Exception Handling Module. Please add the module
    to your web.config.");

    //this will force read of the web.config; otherwise
    no checking of whether section is even present until first use
    Util.WebLogin.FormsAuthenticationConfiguration
    ConfigInfo =
    (Util.WebLogin.FormsAuthenticationConfiguration)ConfigurationManager.GetSection("FormsAuthenticationConfiguration");

    if (null == ConfigInfo)
    throw new Exception("The Forms Authentication
    Configuration section was not found in the web.config. Please add the section
    to your web.config.");

    m_ConfigInfo = ConfigInfo;

    _initialized = true;
    }
    }
    }
    }
    =?Utf-8?B?Q2h1Y2sgUA==?=, Oct 19, 2007
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mike Kingscott
    Replies:
    0
    Views:
    472
    Mike Kingscott
    Jun 30, 2003
  2. Nugs

    Application_AuthenticateRequest

    Nugs, Apr 17, 2004, in forum: ASP .Net
    Replies:
    0
    Views:
    1,203
  3. =?Utf-8?B?ZGFubWFuMjI2?=

    Application_AuthenticateRequest cannot read Session variable

    =?Utf-8?B?ZGFubWFuMjI2?=, Apr 18, 2005, in forum: ASP .Net
    Replies:
    4
    Views:
    12,399
    Brock Allen
    Apr 18, 2005
  4. Alessio Brizi

    Application_AuthenticateRequest Problem

    Alessio Brizi, Jul 8, 2005, in forum: ASP .Net
    Replies:
    0
    Views:
    588
    Alessio Brizi
    Jul 8, 2005
  5. =?Utf-8?B?dGhlIGZyaWVuZGx5IGRpc3BsYXkgbmFtZQ==?=

    When does Application_AuthenticateRequest fires?

    =?Utf-8?B?dGhlIGZyaWVuZGx5IGRpc3BsYXkgbmFtZQ==?=, Dec 22, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    10,653
    Brock Allen
    Dec 22, 2005
Loading...

Share This Page