You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/Infrastructure/Extensions/HttpClientExtensions.cs

39 lines
1.8 KiB

using System.Linq;
using System.Net;
using System.Net.Http;
namespace Infrastructure.Extensions
{
public static class HttpClientExtensions
{
public static byte[] GetByteDigest(this HttpClient httpClient, string url, string userName, string password)
{
return httpClient.GetDigest(url, userName, password).ReadAsByteArrayAsync().Result;
}
public static HttpContent GetDigest(this HttpClient httpClient, string url, string userName, string password)
{
var task = httpClient.GetAsync(url);
var result = task.Result.Content;
if (task.Result.StatusCode == HttpStatusCode.Unauthorized)
{
var dictionary = task.Result.Headers.GetValues("WWW-Authenticate").ToList().SelectMany(o => o.Split(',')).ToDictionary(o => o.Split('=')[0].Trim(), o => o.Split('=')[1].Trim().Trim('"'));
var hc2 = new HttpClient();
var realm = dictionary["realm"];
var nonce = dictionary["nonce"];
var qop = dictionary["Digest qop"];
var uri = url.Substring(7).Substring(url.Substring(7).IndexOf('/'));
var cnonce = nonce;
var ha1 = $"{userName}:{realm}:{password}".Md5();
var ha2 = $"GET:{uri}".Md5();
var nc = "00000001";
var response = $"{ha1}:{nonce}:{nc}:{cnonce}:{qop}:{ha2}".Md5();
var authorization = $"Digest username=\"{userName}\",realm=\"{realm}\",nonce=\"{nonce}\",uri=\"{uri}\",cnonce=\"{cnonce}\",nc={nc},response=\"{response}\",qop=\"{qop}\"";
hc2.DefaultRequestHeaders.Add("Authorization", authorization);
var task2 = hc2.GetAsync(url);
result = task2.Result.Content;
}
return result;
}
}
}