MdpPurchaseHandoffAuthenticationHandler.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  2. using System.Net;
  3. using System.Security.Claims;
  4. using System.Security.Cryptography;
  5. using System.Text.Encodings.Web;
  6. using Microsoft.AspNetCore.Authentication;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.Logging;
  9. using Microsoft.Extensions.Options;
  10. namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  11. public sealed class MdpPurchaseHandoffAuthenticationHandler(
  12. IOptionsMonitor<AuthenticationSchemeOptions> options,
  13. ILoggerFactory logger,
  14. UrlEncoder encoder,
  15. IConfiguration configuration) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
  16. {
  17. public const string SchemeName = "MdpPurchaseHandoff";
  18. protected override Task<AuthenticateResult> HandleAuthenticateAsync()
  19. {
  20. var remoteAddress = Context.Connection.RemoteIpAddress;
  21. var loopback = remoteAddress is not null
  22. && IPAddress.IsLoopback(remoteAddress.IsIPv4MappedToIPv6 ? remoteAddress.MapToIPv4() : remoteAddress);
  23. if ((!Request.IsHttps && !loopback) || !HasValidToken())
  24. return Task.FromResult(AuthenticateResult.Fail("Invalid purchase handoff credential."));
  25. var principal = new ClaimsPrincipal(new ClaimsIdentity(Scheme.Name));
  26. return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name)));
  27. }
  28. private bool HasValidToken()
  29. {
  30. var key = PurchaseDispatchProof.ReadKey(configuration[PurchaseDispatchProof.CredentialSetting]);
  31. if (key is null || !Request.Headers.TryGetValue(PurchaseDispatchProof.DigestHeader, out var digest)
  32. || digest.Count != 1 || digest[0]?.Length != 64
  33. || !Request.Headers.TryGetValue(PurchaseDispatchProof.ProofHeader, out var proof) || proof.Count != 1)
  34. return false;
  35. var submitted = PurchaseDispatchProof.ReadKey(proof[0]);
  36. return submitted is not null && CryptographicOperations.FixedTimeEquals(submitted,
  37. PurchaseDispatchProof.Sign(key, Request.Method, (Request.PathBase + Request.Path).Value!, digest[0]!));
  38. }
  39. }