Introduction
The basic story is that I had some code that went off to a timestamp server using HttpWebRequest
and worked fine in .NET 2.0. Then, I had to use it with .NET 3.0, and got the error:
(407) Proxy Authentication Required.
Now, I already had all the code to add a proxy to the request, and the very same code worked in .NET 2.0, so it was a bit of a mystery. At the time of writing, WPF is still pretty new, and so there is not a lot of documentation. Hence, a week of wasted time began, and once I had the solution, I figured I should document it here to save others.
For the reference information that helped me tie down the problem, you can visit:
Using the code
It turns out that .NET 3.0 uses a custom CredentialPolicy
for HttpWebRequest
calls. This is apparently a security enhancement for XBAP applications to stop sending passwords to remote proxies. As a result, if .NET 3.0 feels that your proxy is not a local machine, then it will not send any authentication information. This piggy-backs on another annoying Microsoft issue in that it is really poor at deciding which machines are local and which aren't. Hence, it often refuses to pass the credentials even when the proxy is a local machine (as was the case for me).
The solution is to supply your own CredentialPolicy
that allows the username/password information to be sent to the proxy. This is done by creating a class that implements the ICredentialPolicy
interface and returns true
to the ShouldSendCredential
method. Then, using an instance of this class, set AuthenticationManager.CredentialPolicy
. Some demonstration code is included below.
class ProxyCredentials : ICredentialPolicy {
bool ICredentialPolicy.ShouldSendCredential(Uri challengeUri, WebRequest request,
NetworkCredential credential, IAuthenticationModule authenticationModule) {
return true;
}
}
class DemoRequest {
static DemoRequest() {
AuthenticationManager.CredentialPolicy = new ProxyCredentials();
}
public DoRequest() {
HttpWebRequest httprequest =
(HttpWebRequest)WebRequest.Create("http://www.ensigma.com.au/");
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
httprequest.Proxy = proxy;
httprequest.PreAuthenticate = true;
....
}
}