I'm using Application_OnAuthenticateRequest in Global.asax to assign a custom principal to HttpContext.Current.User and System.Threading.Thread.CurrentPrincipal.
In testing, I noticed that this code executes multiple times for a single page request. By looking at the HttpContext.Current.Request.Url I determined that this code is executing for each call to a JavaScript file, Image, and CSS file. All of these resources are stored in a single subfolder called "Content". So, I'm able to prevent multiple executions of my custom principal by checking to see if "Content" is part of HttpContext.Current.Request.Url like so:
protected void Application_OnAuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.Url.AbsoluteUri.Contains("/Content"))
return;
if (Context.User != null)
{
if (Context.User.Identity.IsAuthenticated)
{
var userRepository = ObjectFactory.GetInstance<IUserRepository>();
var prospectorUser = userRepository.GetByUserName(Context.User.Identity.Name);
if (prospectorUser == null)
{
throw new ApplicationException("Context.User.Identity.Name is not a recognised user.");
}
var principal = new ExtendedWindowsPrincipal(HttpContext.Current.User.Identity, prospectorUser);
// Attach the new principal object to the current HttpContext object
HttpContext.Current.User = principal;
// Make sure the Principal's are in sync
System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User;
return;
}
}
}
My fix seems kludgy. Is there a better way to trap requests for "Content" items and prevent my custom code for my principal from firing for every request?