Understanding HTTP Authentication
As you saw earlier in this chapter, HTTPS allows you to determine that the web server you are connecting to is what it claims to be. HTTP authentication provides the other side of this verification. HTTP authentication allows the server to determine that the web user is who they say that they are.
HTTP authentication is not tied to HTTPS. It can also be used with either HTTP or HTTPS. To access a page protected by HTTP authentication, a web user must enter both a user id and password. If a username and password are not provided, or if it is incorrect, the user will receive an HTTP error.
Most websites do not use HTTP authentication; instead, many websites use their own authentication. This works by displaying a form to the user and prompting for identifying information, usually an id and password.
HTTP Authentication in Action
You have probably seen sites that make use of HTTP authentication. Sites that use HTTP authentication popup a window that prompts you for a user id and password. HTTP authentication always pops up a second window. If you are being prompted for a user id and password on the actual webpage, then the site is performing its own authentication. To see HTTP authentication in action, visit the following URL:
https://www.httprecipes.com/1/5/auth.php
This URL will display the page show in Figure 5.3.
Figure 5.3: Ready to Enter a Protected Area

Click the URL displayed on the page, and you will be taken to the secure area. Note the user id and password prompts displayed on the page. When you enter the secure area you will see a popup that prompts you for your user id and password. This page is shown in Figure 5.4.
Figure 5.4: Enter your ID and Password

If you enter the correct user id and password you will be taken to the secure area. If you enter an invalid user id and password, you will be prompted several more times. Eventually, the browser will take you to an error page if you fail to enter the correct user id and password. For this site, the correct user id is “testuser” and the password is “testpassword”.
Supporting HTTP Authentication in C#
Most websites use their own authentication and do not rely on HTTP authentication. Chapter 7, “Accessing Forms”, will show how to access sites that make use of their own authentication. However, if the site that you would like to access makes use of HTTP authentication, then you must support that as well.
The C# HTTP classes provide support HTTP authentication. To make use of HTTP authentication, you will have to add a special HTTP class called NetworkCredential. This class allows you to specify a user id and password to login.
NetworkCredential networkCredential = new NetworkCredential("user id","password");
WebRequest http = HttpWebRequest.Create(remoteURL);
http.PreAuthenticate = true;
http.Credentials = networkCredential;Recipe 5.2 demonstrates adding this header, and using HTTP authentication.




