473,324 Members | 1,678 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Application_AuthenticateRequest

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.Ge t("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)Co nfigurationManager.GetSection("FormsAuthentication Configuration");

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_Confi gInfo.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.Contai ns(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.Re quest.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.Reque st.Url.Host,
strFullyQualifiedHostName)
+ requestURL;

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

}
Oct 18 '07 #1
3 9669
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.
Oct 18 '07 #2
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 (wa****@online.microsoft.com, 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.

Oct 19 '07 #3
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.Ge t("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)Co nfigurationManager.GetSection("FormsAuthentication Configuration");

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;
}
}
}
}
Oct 19 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Daniel Brown | last post by:
I am using forms based authentication and this is working fine at user level. I have put code in the global.asax file to get the roles from the database however it seems that this code is not being...
0
by: Mike Kingscott | last post by:
Hi there, Getting into ASP.Net finally, looks good but I'm having a bit of trouble here. I'm protecting my web site via form-based security (I won't go into the ins and outs, suffice to say it's...
0
by: Nugs | last post by:
Hey there again, Well I am still having this problem with my forms authentication. My previous post describes my problem. But I have another question and thought I would post a new topic for it....
1
by: AVance | last post by:
Hi, I've come across this scenario in ASP.NET 1.1 with forms authentication where the forms auth doesn't seem to timeout correctly, nor redirect to the login page. I have done some testing, and...
4
by: danman226 | last post by:
I will be using a companyname, user name, and password to authenicate users in my system. I am trying to save the company name in the session for later use. I cannot access the Session object in...
0
by: Alessio Brizi | last post by:
Hi to all, I have a problem with the method Application_AuthenticateRequest in the global.asax file. I developed a web application with an url rewriting module, with a private area. In the...
1
by: the friendly display name | last post by:
I am using .net 1.1 In the global.asax.cs file, there is this entry: protected void Application_AuthenticateRequest(Object sender, EventArgs e) as far as I know, it is wired with the ...
1
by: Andrew | last post by:
Hello, friends, I am implementing a role based authentication (Forms authentication) for our web app using .net 1.1. I read the paper:...
0
by: sloan | last post by:
I've been reading this article: http://msdn2.microsoft.com/EN-US/library/aa302401.aspx Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication (the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.