Application_AuthenticateRequest

G

Guest

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.
}

}
 
G

Guest

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.
 
W

Walter Wang [MSFT]

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 ([email protected], 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.
 
G

Guest

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;
}
}
}
}
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,016
Latest member
TatianaCha

Latest Threads

Top