How to get an Authenticated Proxy Server working properly from ASP.NET app?

John Mills picture John Mills · Oct 21, 2013 · Viewed 8.1k times · Source

I have an ASP.NET 4.5 web app that calls an external web service. The environment requires internet access to go through an authenticated proxy server.

On my dev PC (Win7) the following configuration works fine.

<system.net>
  <defaultProxy useDefaultCredentials="true" enabled="true">
    <proxy usesystemdefault="True" autoDetect="True" />
  </defaultProxy>
</system.net>

The above configuration doesn't work when applied to the test server. The test server is Windows Server 2008 with IIS 7. I have set the App Pool identity to be my user credentials so that proxy server would be authenticated using my credentials.

I am able to get the test server working with the proxy if I create a custom implementation of IWebProxy.

public class ManualProxy : IWebProxy
{
    private readonly Uri _proxy;
    private static readonly NameValueCollection AppSettings = ConfigurationManager.AppSettings;

    public ManualProxy()
    {
        _proxy = new Uri(AppSettings["ManualProxy.Proxy"]);
    }


    #region IWebProxy

    ICredentials IWebProxy.Credentials
    {
        get
        {
            return new NetworkCredential(AppSettings["ManualProxy.Username"], AppSettings["ManualProxy.Password"]);
        }
        set
        {
            throw new NotImplementedException();
        }
    }

    Uri IWebProxy.GetProxy(Uri destination)
    {
        return _proxy;
    }

    bool IWebProxy.IsBypassed(Uri host)
    {
        return false;
    }

    #endregion
}

The configuration.

<defaultProxy useDefaultCredentials="false" enabled="true">
  <module type="MyNamespace.ManualProxy, MyAssembly"/>
</defaultProxy>

The custom proxy is configured to authenticate using my credentials, which are the same credentials on my dev PC and for the IIS App Pool identity.

Ideally, I wouldn't need the custom proxy. How can I get the proxy server configured properly just using the existing options in the web.config?

Is there something that I'm not doing properly?

Answer

John Mills picture John Mills · Oct 23, 2013

Forcing the proxy address rather than relying on auto detect fixed the issue.

  <system.net>
    <defaultProxy useDefaultCredentials="true" enabled="true">
      <proxy usesystemdefault="False" autoDetect="False" proxyaddress="http://proxy:8080" />
    </defaultProxy>
  </system.net>