Coding Tips & Tricks


Home > Proxy

Proxy Authentication - Helper Class

If you have ever created an application that requires you to access the internet or call a 3rd party service over the web, you may have come across the issue of the user being behind a proxy server and having to authenticate. The common issue that I have come across is the famous error message:

"The remote server returned an error: (407) Proxy Authentication Required".

Recently, I was working on the SmushMySite Application and although it worked perfectly on my machine at home - many other people were getting a proxy authentication error. As soon as I tried the application at work - BANG! - I got the same error. As I'm sure that I will come across this issue again, I decided it was probably best to write a little helper class. You may have come across better methods, but this seems to work for me. It might seem a little confusing a first, but it will all come together.

Firstly, I recommend you take a look at the following article just to get up to speed with HTTP HEAD requests and checking if the user has an internet connection. This is done by making a simple HTTP HEAD request to see if the user can connect. If they can't, we should get a "407 Proxy Authentication Required" exception.

Proxy Requires Authentication

Okay, let's break this down. The above method I am using checks if the user requires authentication when connecting to the internet. It uses the Default Credentials property to determine if the system credentials in the current security context will work. The CheckExists method is called, and if a 407 exception is returned then we know that the user needs to authenticate.

Once the user has provided us with their credentials, we need a method to verify that their details are correct and then authenticate them.

Try Authenticate

In the above method, we pass in the Credentials and attempt to connect again. Using the CheckExists method, we can determine if the user is able to connect using the credentials that they entered. If it was successful, the credentials have been set again we can access the internet as normal. However, if the authentication failed, we can prompt the user to re-enter their credentials. This could be due to incorrect username, passwords or domain.

I have put these methods in a class called ProxyHelper. Let's put it all together and call the methods that we have created.

Proxy Authentication

As you can see in the above code, I have added a little bit of extra logic to show useful messages to the user. You might want to handle this slightly differently depending on the setup of your application.

Just to make this a little easier to understand, I have put all the code above into a WPF example that is available to download.








Comments


Add your comment

300 Characters left


Please fill this in to confirm that you are human