Building upon the good work of @kitwalker, here's a delegating handler I wrote for DotNetCore 3.
/// <summary>
/// Respond to a Digest auth challenge and retry the request.
/// See <c>https://en.wikipedia.org/wiki/Digest_access_authentication</c>.
/// </summary>
/// <example>
/// Example response header with challenge details:
/// header: www-authenticate
/// value: <c>Digest realm="Signaling Controller", charset="UTF-8", algorithm=MD5, nonce="6088c71a:a699df7b2e03c53cfe06f8d070f4345c", qop="auth"</c>
/// </example>
public class DigestAuthenticationHandler : DelegatingHandler
{
private readonly ILogger _logger;
private readonly CredentialSettings _settings;
public DigestAuthenticationHandler(ILogger<DigestAuthenticationHandler> logger, CredentialSettings settings)
{
_logger = logger;
_settings = settings;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var username = _settings?.Username;
var password = _settings?.Password;
if (string.IsNullOrEmpty(username))
{
throw new ArgumentNullException(nameof(username), "Missing credentials.");
}
if (string.IsNullOrEmpty(password))
{
throw new ArgumentNullException(nameof(password), "Missing credentials.");
}
var response = await base.SendAsync(request, cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
var header = response.Headers.WwwAuthenticate;
var value = header.FirstOrDefault();
_logger.LogDebug("Challenged with scheme: '{Scheme}'", value?.Scheme ?? "(unknown)");
if (string.Compare(value?.Scheme, "Digest", StringComparison.OrdinalIgnoreCase) != 0)
{
_logger.LogDebug("Authentication challenge is not of type 'Digest' - give up");
return response;
}
var details = new DigestAuthenticationDetails(value?.Parameter);
_logger.LogDebug("Authentication challenge details: {Details}", details);
var qop = details["qop"];
var realm = details["realm"];
var nonce = details["nonce"];
var algorithm = details["algorithm"];
if (algorithm != "MD5")
{
_logger.LogError("Algorithm '{Algorithm}' unsupported; cannot respond to Digest auth challenge - give up", algorithm);
return response;
}
var cnonce = new Random().Next(123400, 9999999).ToString();
var nc = 1;
var uri = request.RequestUri.PathAndQuery;
var digest = BuildDigestHeader(username, password, request.Method, uri, realm, algorithm, nonce, cnonce, qop, nc);
request.Headers.Add("Authorization", digest);
var retry = await base.SendAsync(request, cancellationToken);
return retry;
}
return response;
}
private static string BuildDigestHeader(
string username,
string password,
HttpMethod method,
string uri,
string realm,
string algorithm,
string nonce,
string cnonce,
string qop,
int nc)
{
static string CalculateMd5Hash(string input)
{
var bytes = Encoding.ASCII.GetBytes(input);
var hash = MD5.Create().ComputeHash(bytes);
var builder = new StringBuilder();
foreach (var b in hash)
{
builder.Append(b.ToString("x2"));
}
return builder.ToString();
}
var ha1 = CalculateMd5Hash($"{username}:{realm}:{password}");
var ha2 = CalculateMd5Hash($"{method}:{uri}");
var digestResponse = CalculateMd5Hash($"{ha1}:{nonce}:{nc:00000000}:{cnonce}:{qop}:{ha2}");
return "Digest "
+ $"username=\"{username}\", "
+ $"realm=\"{realm}\", "
+ $"nonce=\"{nonce}\", "
+ $"uri=\"{uri}\", "
+ $"algorithm=\"{algorithm}\", "
+ $"response=\"{digestResponse}\", "
+ $"qop={qop}, "
+ $"nc={nc:00000000}, "
+ $"cnonce=\"{cnonce}\"";
}
private class DigestAuthenticationDetails
{
private readonly Dictionary<string, string?> _values;
public DigestAuthenticationDetails(string? authentication)
{
_values = new Dictionary<string, string?>();
if (authentication != null)
{
foreach (var pair in authentication.Split(","))
{
var item = pair.Split("=");
string? key = null;
string? value = null;
if (item.Length == 1)
{
key = item.ElementAt(0);
}
else
{
key = item.ElementAt(0);
value = item.ElementAt(1);
}
key = key
.Trim()
.Replace("\"", "")
.Replace("'", "")
.ToLower();
value = value
?.Trim()
.Replace("\"", "")
.Replace("'", "");
_values.Add(key, value);
}
}
}
public string this[string key] => GetValueOrThrow(key);
public override string ToString()
{
var builder = new StringBuilder();
foreach (var (key, value) in _values)
{
builder.Append($"'{key}'='{value}' ");
}
return builder.ToString();
}
private string GetValueOrThrow(string key)
{
if (_values.TryGetValue(key, out var value))
{
if (value != null)
{
return value;
}
throw new ArgumentNullException(nameof(value), $"No value for key '{key}'.");
}
throw new ArgumentOutOfRangeException(nameof(key), $"Key '{key}' was not found in Digest auth challenge.");
}
}
}
Then wherever you register services, add the delegating handler to the HttpClient
that needs digest auth capability:
services.AddTransient<DigestAuthenticationHandler>();
services.AddHttpClient<ServiceThatNeedsHttpClient>()
.AddHttpMessageHandler<DigestAuthenticationHandler>();
Note: No support for caching the previous digest header used.