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.
52 lines
2.3 KiB
52 lines
2.3 KiB
using System.Linq;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System;
|
|
|
|
namespace Infrastructure.Extensions
|
|
{
|
|
public static class HttpClientExtensions
|
|
{
|
|
public static byte[] GetByteDigest(this HttpClient httpClient, Uri url, string userName, string password)
|
|
{
|
|
if (httpClient == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(httpClient));
|
|
}
|
|
return httpClient.GetDigest(url, userName, password).ReadAsByteArrayAsync().Result;
|
|
}
|
|
|
|
public static HttpContent GetDigest(this HttpClient httpClient, Uri url, string userName, string password)
|
|
{
|
|
if (httpClient == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(httpClient));
|
|
}
|
|
if (url == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(url));
|
|
}
|
|
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.ToString().Substring(7).Substring(url.ToString().Substring(7).IndexOf('/', StringComparison.CurrentCulture));
|
|
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}\"";
|
|
httpClient.DefaultRequestHeaders.Add("Authorization", authorization);
|
|
var task2 = httpClient.GetAsync(url);
|
|
result = task2.Result.Content;
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
} |