using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using Dpz.Core.Infrastructure;
using Microsoft.Extensions.Configuration;
namespace Dpz.Core.Service.Network;
public class AuthUpyunHeaderHandler:DelegatingHandler
{
private readonly IConfiguration _configuration;
public AuthUpyunHeaderHandler(IConfiguration configuration)
{
_configuration = configuration;
InnerHandler = new HttpClientHandler();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var upyunOperator = _configuration.GetSection("upyun").Get<UpyunOperator>();
if (upyunOperator == null)
throw new BusinessException("configuration error,need upyun config node.");
var utcNow = DateTime.UtcNow;
var pwd = upyunOperator.Password.GenerateHashMd5();
var method = request.Method.ToString().ToUpper();
var uri = request.RequestUri?.AbsolutePath ?? "";
var message = $"{method}&{uri}&{utcNow:R}";
// if (!string.IsNullOrEmpty(contentMd5))
// {
// message += "&" + contentMd5;
// }
var keyBytes = Encoding.UTF8.GetBytes(pwd);
var sha1 = new HMACSHA1(keyBytes);
var byteArray = Encoding.UTF8.GetBytes(message);
var stream = new MemoryStream(byteArray);
var sha1Result = await sha1.ComputeHashAsync(stream, cancellationToken);
var signBase64 = Convert.ToBase64String(sha1Result);
request.Headers.Authorization =
AuthenticationHeaderValue.Parse($"UPYUN {upyunOperator.Operator}:{signBase64}");
request.Headers.Date = utcNow;
return await base.SendAsync(request, cancellationToken);
}
}