Authentication
If the web server requires user authentication we can create user credentials and pass it to the web request. The interfaces and classes that are of use here are ICredentials, NetworkCredential, and CredentialCache.
For user authentication we can create an object of type NetworkCredential. This class provides credential information for basic, digest, NTLM, and Kerberos authentication.
In the constructor of the NetworkCredential class we can pass a username, password, and optionally a domain that authorizes the user.
NetworkCredential credentials =
new NetworkCredential("UserName", "Password");
This credential information can be set with the Credentials property of the WebRequest class to authorize the user:
WebRequest request =
WebRequest.Create("http://requireslogon.com/myfile.aspx");
request.Credentials = credentials;
If we want to use multiple credential information for different URIs, we can use the CredentialCache class as below. With this cache we can also define the authentication type for a specific connection. Here, I'm using basic authentication for the web site www.unsecure.com, and digest authentication for the web site www.moresecure.com where a hash is sent across the network instead of the password.
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri("http://www.unsecure.com"), "Basic",
new NetworkCredential("username", "password"));
credentialCache.Add(new Uri("http://www.moresecure.com"), "Digest",
new NetworkCredential("username", "password",
"domain"));
To use the Windows logon credentials of the currently logged on user, we can use the default credentials that can be accessed with CredentialCache.DefaultCredentials(). For security reasons these credentials can only be used for the NTLM, Negotiate, and Kerberos authentication types, and it is not possible to read the username and domain from it.