Access Denied when logged into ASP Net site with Basic Auth

Topics: Errors
Oct 17, 2013 at 7:36 PM
I am writing a small intranet application in ASP .Net, using Basic Authentication. I can respond to the challenge prompt with my Active Directory credentials and the HttpContext.Current.Identity is set properly, as is the current thread's identity. The application pool is set (the default on our apps) to use a service account. When I don't send the username and password properties and try to connect to another server on our network, I get everyone's favorite error: "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"

When I manually set the username and password in the TaskScheduler constructor to the values that I know to be the case for the HttpContext.Current.Identity, I can successfully connect to that server. Is there a way to see the specific username and password it is trying to use? Thanks for any help you can provide.
Oct 18, 2013 at 2:12 AM
Edited Oct 18, 2013 at 2:33 AM
Like I said in my original post: I knew the current user was correct, and I knew the code worked if I explicitly passed in that user's name and password.... so why not impersonate yourself? This sounds silly, but it was the easiest way to make this work. I eagerly await anyone who has a better answer, but in the meantime, I wrote a static method on the base class of this and other classes that require authentication, like starting/stopping Windows services:
public static TOut DoImpersonatedActivity<TOut>(Func<TOut> action)
{
    TOut retVal;
    WindowsImpersonationContext impersonation = null;
    try
    {
        impersonation = ((WindowsIdentity)System.Web.HttpContext.Current.User.Identity).Impersonate();
        retVal = action();
    }
    finally
    {
        if (impersonation != null) impersonation.Undo();
    }
    return retVal;
}
To call this code, you'd simply wrap the line of code that needs authentication in an empty lambda and pass it to the above method. I hate it when someone on a message board only gives me half a solution, so here's more info on Funcs, if you require. Basically, since .Net 3.5, lambdas, Funcs, and delegates are basically identical as they are all anonymous methods in the C# language specification.
using (var ts = DoImpersonatedActivity(() => new TaskService(serverName)))
{
    //do fun stuff
}
Marked as answer by rjcantrell on 10/17/2013 at 7:12 PM