NTLM and Kerberos Authentication for a WebRequest and a WebProxy
Posted by jpluimers on 2016/02/16
This was very useful to get a WebClient with a WebProxy configured to use a proxy server that is based on NTLM authentication.
The note in the MSDN NTLM and Kerberos Authentication. documentation however was totally wrong.
String MyURI = "http://www.contoso.com/";
WebRequest WReq = WebRequest.Create MyURI;
WReq.Credentials = CredentialCache.DefaultCredentials;Note NTLM authentication does not work through a proxy server.
This code works perfectly fine as the CredentialsCache.DefaultCredentials contains your NTLM or Kerberos credentials.
It even works when you have a local Fiddler http proxy as a facade in front of your NTLM proxy.
[TestMethod, TestCategory("Lengthy")]
public void TestNtlmWebProxy()
{
WebClient webClient = new WebClient();
WebProxy webProxy = new WebProxy("10.110.128.15", 8080);
webProxy.Credentials = CredentialCache.DefaultCredentials;
webClient.Proxy = webProxy;
AssertWebClientGetsValidExternalIpAddress(webClient);
}
[TestMethod, TestCategory("Lengthy")]
public void TestLocalFiddlerNtlmWebProxy()
{
WebClient webClient = new WebClient();
WebProxy webProxy = new WebProxy("127.0.0.1", 8888);
webProxy.Credentials = CredentialCache.DefaultCredentials;
webClient.Proxy = webProxy;
AssertWebClientGetsValidExternalIpAddress(webClient);
}
private static void AssertWebClientGetsValidExternalIpAddress(WebClient webClient)
{
try
{
string url;
//url = "http://ifconfig.me/ip";
//url = "http://shtuff.it/myip/short";
//url = "http://curlmyip.com";
//url = "http://ident.me";
//url = "http://tnx.nl/ip";
//url = "http://ipecho.net/plain";
//url = "http://ip.appspot.com";
//url = "http://icanhazip.com";
url = "http://whatismyip.akamai.com/";
string content = webClient.DownloadString(url);
var endsWithLineFeed = content.EndsWith("\n", StringComparison.InvariantCulture);
if (endsWithLineFeed)
content = content.Trim();
IPAddress ipAddress;
var isValidIpAddress = IPAddress.TryParse(content, out ipAddress);
Assert.IsTrue(isValidIpAddress, "invalid IP address");
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
WebResponse resp = e.Response;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string response = sr.ReadToEnd();
Assert.Fail(string.Format("Response: {1}{0}{1}Exception: {1}{2}{1}", response, e.ToString(), Environment.NewLine));
}
}
else
throw;
}
}
Based on the above, I also found the link below that shows how to with the case where you (don’t) need a proxy, and how to check if credentials are actually required:
–jeroen






Leave a comment