ASP.NET Windows Authentication Impersonate Problem

asp.netiiswindows-authentication

In my previous questions I was asking how to use windows authentication within my application. That is now working, users can login with there account but I have one database access scenario I can't find anything on.

Basically I will have several servers and here is the problem.

On some servers they will have Windows Authentication accounts for the SQL Server database server, so using impersonate their credentials should be used. But I notice its a global setting in the web.config (not per connection) and it one case I want to use the applications (IIS or ASP) Windows Authentication account rather than the users. (Access to my configuration database)

How could I achieve this?

Web Application is ASP.NET MVC hosted on Server 2003/2008 IIS 6/7/7.5 with clients being Windows XP and above. Using SQL Server Express/Standard 2005/2008 mixed.

Best Answer

Impersonation is on a site wide basis, or you can manually turn it on. What you can't do is manually turn it off I'm afraid, nor can it be done via the connection strings.

So basically turn impersonation off, then wrap the database calls when impersonation is needed like so:

using System.Security.Principal;

WindowsIdentity winId = (WindowsIdentity)HttpContext.Current.User.Identity;
WindowsImpersonationContext ctx = null;
try
{
    ctx = winId.Impersonate();
    // Do your thing
}
catch
{
}
finally
{
    if (ctx != null)
        ctx.Undo();
}

The MSDN P&P guide to asp.net impersonation has more.