Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine (elegantly) if proxy authentication is required in C# winforms app

My use case is this, I want to call out to a webservice and if I am behind a proxy server that requires authentication I want to just use the default credentials...

  WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;

Otherwise I'll just simply make the call, It would be very nice to determine if the auth is required up front, rather than handle the exception after I attempt to make the call.

Ideas?

like image 763
Tim Jarvis Avatar asked Jan 29 '09 01:01

Tim Jarvis


People also ask

What is a proxy authentication required?

The HTTP 407 Proxy Authentication Required client error status response code indicates that the request has not been applied because it lacks valid authentication credentials for a proxy server that is between the browser and the server that can access the requested resource.

How do I set up proxy authentication?

Configure the App Host to connect through the proxy using an HTTPS or HTTP connection, or both. To configure the proxy connection with a user account for authentication, add --http-proxy-user <user> or --https-proxy-user <user> . You are prompted for the proxy password.


1 Answers

It was only after I had first deployed my app that I realised some users were behind firewalls... off to work to test it. Rather than do a test for a '407 authentication required' I just do the same Proxy setup whether it might be needed or not...

System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri.AbsoluteUri);
//HACK: add proxy
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
req.Proxy = proxy;
req.PreAuthenticate = true;
//HACK: end add proxy
req.AllowAutoRedirect = true;
req.MaximumAutomaticRedirections = 3;
req.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; DeepZoomPublisher.com)";
req.KeepAlive = true;
req.Timeout = 3 * 1000; // 3 seconds

I'm not sure what the relative advantages/disadvantages are (try{}catch{} without proxy first, versus just using the above), but this code now seems to work for me both at work (authenticating proxy) and at home (none).

like image 191
Conceptdev Avatar answered Oct 21 '22 10:10

Conceptdev