System.Net.Http.Headers.WwwAuthenticateHeaderValue

Represents the WWW-Authenticate header.

Overview

The WwwAuthenticateHeaderValue class in .NET represents the WWW-Authenticate HTTP header. This header is sent by the server to the client in response to an unauthorized request (status code 401) to indicate how the client should authenticate itself.

It typically includes one or more authentication schemes, such as Basic, Bearer, Digest, etc., along with any parameters required by those schemes.

Key Properties and Methods

Common Usage Examples

Creating a Basic Authentication Header


using System.Net.Http.Headers;

// ...

var authHeader = new WwwAuthenticateHeaderValue("Basic", "realm=\"Secure Area\"");
string headerString = authHeader.ToString();
// headerString will be: Basic realm="Secure Area"
            

Creating a Bearer Token Authentication Header


using System.Net.Http.Headers;

// ...

var authHeader = new WwwAuthenticateHeaderValue("Bearer", "\"my-opaque-token\"");
string headerString = authHeader.ToString();
// headerString will be: Bearer "my-opaque-token"
            

Parsing an Incoming Header


using System.Net.Http.Headers;

// Assume this comes from an incoming HTTP response
string incomingHeader = "Digest realm=\"testrealm\", nonce=\"dcd98b7102dd2f0e8b94784911577547\", opaque=\"5 filede7f5d50c192f3515970038116c64\"";

WwwAuthenticateHeaderValue parsedValue;
if (WwwAuthenticateHeaderValue.TryParse(incomingHeader, out parsedValue))
{
    Console.WriteLine($"Scheme: {parsedValue.Scheme}"); // Output: Scheme: Digest
    // Accessing specific parameters for Digest might require custom parsing logic
    // or relying on specific parsing behavior if implemented by the framework.
    // For complex schemes like Digest, you might need to parse the parameters string manually.
}
else
{
    Console.WriteLine("Failed to parse WWW-Authenticate header.");
}
            

Handling Multiple Schemes

The WWW-Authenticate header can technically contain multiple schemes, though in practice, a single scheme is most common for a given challenge. Libraries typically parse the first one or require specific handling if multiple are present.

For example, a server might send:

WWW-Authenticate: Negotiate
WWW-Authenticate: Kerberos realm="example.com"

When parsing, you'd often process these individually.

Underlying Implementation

The WwwAuthenticateHeaderValue class is part of the System.Net.Http.Headers namespace, provided by the .NET Framework and .NET Core/5+. It helps abstract the complexities of parsing and constructing these HTTP headers, making it easier for developers to implement client authentication logic.

The class relies on RFC specifications (like RFC 7235 for HTTP Authentication) to correctly interpret the structure of the WWW-Authenticate header.