在 @kitwalker 的优秀工作基础上,这是我为 DotNetCore 3 编写的委托处理程序。
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.");
}
}
}
然后在您注册服务的任何位置,将委托处理程序添加到需要摘要身份验证功能的 HttpClient
中:
services.AddTransient<DigestAuthenticationHandler>();
services.AddHttpClient<ServiceThatNeedsHttpClient>()
.AddHttpMessageHandler<DigestAuthenticationHandler>();
注意:不支持缓存先前使用的摘要头。
DigestAuthFixer digest = new DigestAuthFixer(baseUrl, username, password); string strReturn = digest.GrabResponse(urlPath);
例如:DigestAuthFixer digest = new DigestAuthFixer("http://localhost:8080/", username, password); string strReturn = digest.GrabResponse("GetSomething/Index");
- Sahin