OdeToCode IC Logo

Impersonation and Application_Start in ASP.NET

Thursday, July 13, 2006
Q: I want to query my database and cache some static data during the Application_Start event. SQL Server requires a trusted connection, and I'm using impersonation in web.config.

<identity impersonate="true" userName="jacque" password="crackme"/>

This works everywhere except Application_Start. The code in that method can't connect to the database. What's the dilly?

A: The short answer is that impersonation isn't "on" during Application_Start, so SQL Server is seeing the worker process identity (NETWORK SERVICE or ASPNET) instead of Jacque's identity.

Application_Start is an odd event. It's not really a request related event, but of course it won't fire until the first event arrives. The ASP.NET runtime doesn't start impersonation until it begins to process the request in earnest. This event fires just before impersonation begins, during a time when ASP.NET is laying out the cocktail napkins and setting up for the party.

There are at least a couple workarounds for the problem. You could use a Singleton* design pattern, and initialize the Singleton during a request when impersonation is active (perhaps during the BeginRequest event). You could also run the worker process under an identity with rights in SQL Server.

* Note: The article points to a "Double-Check Locking Is Broken" paper. DBCL is a problem in NET 1.x without special pre-cautions, but is not an issue in the stronger memory model of 2.0 (see rule #5 in section "Strong Model 2" of this Vance Morrison article).