Represents a username and password combination for network authentication.
The System.Net.Security.NetworkCredential class represents a user's credentials, typically a username and password, for network authentication. This class is fundamental for scenarios where your application needs to authenticate with network resources such as web servers, FTP servers, or other services that require credentials.
It provides a secure way to store and transmit authentication information. You can create instances of this class to specify the credentials needed to access protected network resources.
public class NetworkCredential : System.Net.ICredentials
Namespace: System.Net
Assembly: System (in System.dll)
| Name | Description |
|---|---|
NetworkCredential() |
Initializes a new instance of the NetworkCredential class with default values. |
NetworkCredential(string userName, string password) |
Initializes a new instance of the NetworkCredential class with the specified user name and password. |
NetworkCredential(string userName, byte[] password) |
Initializes a new instance of the NetworkCredential class with the specified user name and password as a byte array. |
NetworkCredential(string userName, string password, string domain) |
Initializes a new instance of the NetworkCredential class with the specified user name, password, and domain. |
NetworkCredential(string userName, byte[] password, string domain) |
Initializes a new instance of the NetworkCredential class with the specified user name, password as a byte array, and domain. |
| Name | Description |
|---|---|
Domain |
Gets or sets the domain associated with the credentials. |
Password |
Gets or sets the password associated with the credentials. |
UserName |
Gets or sets the user name associated with the credentials. |
| Name | Description |
|---|---|
Reset() |
Resets the properties of the NetworkCredential object to their default values. |
When using the NetworkCredential class, be mindful of security. Passwords should be handled with care and ideally encrypted or stored securely. The framework may handle some encryption internally, but it's good practice to be aware of the security implications of transmitting credentials over a network.
The Domain property is particularly relevant for Windows authentication environments, where it specifies the security domain to which the user belongs. For other authentication schemes, it might be unused or have a different meaning.
The following example demonstrates how to create a NetworkCredential object and use it with an HttpClient for basic authentication.
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
public class Example
{
public static void Main(string[] args)
{
// Define credentials
string userName = "myuser";
string password = "mypassword";
string domain = "MYDOMAIN"; // Optional, can be null or empty
// Create NetworkCredential object
NetworkCredential credentials = new NetworkCredential(userName, password, domain);
// Example with HttpClient (conceptual - actual request may vary)
using (HttpClient client = new HttpClient())
{
// Construct the Basic Authentication header
string authHeader = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes($"{userName}:{password}"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{credentials.UserName}:{credentials.Password}")));
Console.WriteLine($"Attempting to connect with credentials: User='{credentials.UserName}', Domain='{credentials.Domain}'");
// Replace with your actual URL
// try
// {
// HttpResponseMessage response = await client.GetAsync("http://example.com/protected/resource");
// response.EnsureSuccessStatusCode();
// string responseBody = await response.Content.ReadAsStringAsync();
// Console.WriteLine("Request successful.");
// // Process responseBody
// }
// catch (HttpRequestException e)
// {
// Console.WriteLine($"Request exception: {e.Message}");
// }
}
// Example demonstrating constructor overloads
NetworkCredential credentialsSimple = new NetworkCredential("simpleUser", "simplePass");
Console.WriteLine($"Simple Credentials: User='{credentialsSimple.UserName}'");
NetworkCredential credentialsBytes = new NetworkCredential("byteUser", new byte[] { 0x61, 0x62, 0x63 }); // 'abc'
Console.WriteLine($"Byte Password Credentials: User='{credentialsBytes.UserName}'");
}
}
This example shows how to create NetworkCredential instances and then uses them conceptually within an HttpClient. In a real-world application, you would replace the placeholder URL and handle the actual HTTP response.
using System;
using System.Net;
public class LegacyExample
{
public static void Main(string[] args)
{
try
{
// Create a WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/api/data");
// Set credentials
request.Credentials = new NetworkCredential("apiUser", "apiKey123", "RESOURCEHOST");
// Send the request and get the response (simplified)
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine($"Status Code: {response.StatusCode}");
// Process response...
}
}
catch (WebException e)
{
Console.WriteLine($"Error: {e.Message}");
if (e.Response != null)
{
using (var errorResponse = (HttpWebResponse)e.Response)
{
Console.WriteLine($"Status Code: {errorResponse.StatusCode}");
// Read error stream if necessary
}
}
}
}
}