Blake Blackwell
Blake Blackwell

Reputation: 7795

Use App Pool Credentials for WebClient Request

I would like to use the app pool credentials to avoid a double-hop issue from a web API method. However, I do not want all requests to be impersonated but just this one particular request. The code currently looks something like this:

[Route("api/mycontroller/mymethod")]
public string GetDataFromOtherInternalSystem(int id)
{
  var client = new WebClient ( Credentials = CredentialCache.DefaultNetworkCredentials);

return client.DownloadString('http://internaldomain/api/method/id')

}

From what I understand of MSDN, the user context is the logged in user for that browser session (i.e. my account going through Active Directory and not the app pool's account).

The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running. For a client-side application, these are usually the Windows credentials (user name, password, and domain) of the user running the application. For ASP.NET applications, the default network credentials are the user credentials of the logged-in user, or the user being impersonated.

This then creates the double-hop issue which could be eliminated if the request comes cleanly from the web application as the service account (without me having to construct credentials on the fly).

Any ideas on how to impersonate the app pool without me specifying user credentials as follows:

var cred = new NetworkCredential("myusername", "mypassword")

Again I'm trying to avoid the other web service being properly set up for Kerberos or CORS.

Upvotes: 4

Views: 6653

Answers (1)

zYzil
zYzil

Reputation: 208

This can be accomplished by passing a null pointer (IntPtr.Zero) to the static Impersonate method of the WindowsIdentity class. Here is how it is described in the MSDN document for the Impersonate method:

Calling the Impersonate(IntPtr) method with a userToken value of Zero is equivalent to calling the Win32 RevertToSelf function. If another user is currently being impersonated, control reverts to the original user.

Usage would look something like the following:

using (var impersonationContext = WindowsIdentity.Impersonate(IntPtr.Zero))
{
    try
    {
        // this code is now using the application pool indentity
    }
    finally
    {
        if (impersonationContext != null)
        {
            impersonationContext.Undo();
        }
    }
}

Upvotes: 6

Related Questions