AuthenticationHeaderParser Class

Represents a parser for HTTP authentication headers.

Namespace

System.Net.Http.Headers

Assembly

System.Net.Http.dll

Remarks

This class provides functionality to parse and validate HTTP authentication headers, such as Basic, Bearer, and Digest. It helps in correctly interpreting the schemes and parameters defined in these headers.

Methods

public static bool TryParse(string value, out AuthenticationHeaderValue? parsedValue)

Attempts to parse an authentication header string into an AuthenticationHeaderValue object.

public static bool TryParse(string value, out AuthenticationHeaderValue? parsedValue)

Parameters:

Name Type Description
value string The authentication header string to parse.
parsedValue out AuthenticationHeaderValue? When this method returns, contains the parsed AuthenticationHeaderValue object if the parse succeeded, or null if the parse failed.

Returns:

true if the string was parsed successfully; otherwise, false.

public static AuthenticationHeaderValue Parse(string value)

Parses an authentication header string into an AuthenticationHeaderValue object.

public static AuthenticationHeaderValue Parse(string value)

Parameters:

Name Type Description
value string The authentication header string to parse.

Returns:

The parsed AuthenticationHeaderValue object.

Throws:

  • ArgumentNullException: if value is null.
  • FormatException: if value is not a valid authentication header.

Examples

The following example demonstrates how to use AuthenticationHeaderParser.TryParse to parse a WWW-Authenticate header.

using System;
using System.Net.Http.Headers;

public class Example
{
    public static void Main()
    {
        string headerString = "Basic realm=\"example.com\"";
        AuthenticationHeaderValue authHeader;

        if (AuthenticationHeaderParser.TryParse(headerString, out authHeader))
        {
            Console.WriteLine($"Scheme: {authHeader.Scheme}");
            Console.WriteLine($"Parameter: {authHeader.Parameter}");
        }
        else
        {
            Console.WriteLine("Failed to parse authentication header.");
        }

        // Example with Bearer token
        string bearerHeaderString = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...";
        AuthenticationHeaderValue bearerAuthHeader;

        if (AuthenticationHeaderParser.TryParse(bearerHeaderString, out bearerAuthHeader))
        {
            Console.WriteLine($"\nScheme: {bearerAuthHeader.Scheme}");
            Console.WriteLine($"Parameter: {bearerAuthHeader.Parameter.Substring(0, 20)}..."); // Displaying a part of the token
        }
        else
        {
            Console.WriteLine("Failed to parse bearer authentication header.");
        }
    }
}