SignatureAuthenticationHandler.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. using System.Security.Claims;
  10. using System.Security.Cryptography;
  11. using System.Text.Encodings.Web;
  12. using Microsoft.AspNetCore.Authentication;
  13. namespace Admin.NET.Core;
  14. /// <summary>
  15. /// Signature 身份验证处理
  16. /// </summary>
  17. public sealed class SignatureAuthenticationHandler : AuthenticationHandler<SignatureAuthenticationOptions>
  18. {
  19. private SysCacheService _cacheService;
  20. public SignatureAuthenticationHandler(IOptionsMonitor<SignatureAuthenticationOptions> options,
  21. ILoggerFactory logger,
  22. UrlEncoder encoder,
  23. ISystemClock clock,
  24. SysCacheService cacheService)
  25. : base(options, logger, encoder, clock)
  26. {
  27. _cacheService = cacheService;
  28. }
  29. private new SignatureAuthenticationEvent Events
  30. {
  31. get => (SignatureAuthenticationEvent)base.Events;
  32. set => base.Events = value;
  33. }
  34. /// <summary>
  35. /// 确保创建的 Event 类型是 DigestEvents
  36. /// </summary>
  37. /// <returns></returns>
  38. protected override Task<object> CreateEventsAsync() => throw new NotImplementedException($"{nameof(SignatureAuthenticationOptions)}.{nameof(SignatureAuthenticationOptions.Events)} 需要提供一个实例");
  39. protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
  40. {
  41. var accessKey = Request.Headers["accessKey"].FirstOrDefault();
  42. var timestampStr = Request.Headers["timestamp"].FirstOrDefault();//精确到秒
  43. var nonce = Request.Headers["nonce"].FirstOrDefault();
  44. var sign = Request.Headers["sign"].FirstOrDefault();
  45. if (string.IsNullOrEmpty(accessKey))
  46. return await AuthenticateResultFailAsync("accessKey 不能为空");
  47. if (string.IsNullOrEmpty(timestampStr))
  48. return await AuthenticateResultFailAsync("timestamp 不能为空");
  49. if (string.IsNullOrEmpty(nonce))
  50. return await AuthenticateResultFailAsync("nonce 不能为空");
  51. if (string.IsNullOrEmpty(sign))
  52. return await AuthenticateResultFailAsync("sign 不能为空");
  53. //验证请求数据是否在可接受的时间内
  54. if (!long.TryParse(timestampStr, out var timestamp))
  55. return await AuthenticateResultFailAsync("timestamp 值不合法");
  56. var requestDate = DateTimeUtil.ToLocalTimeDateBySeconds(timestamp);
  57. if (requestDate > Clock.UtcNow.Add(Options.AllowedDateDrift).LocalDateTime || requestDate < Clock.UtcNow.Subtract(Options.AllowedDateDrift).LocalDateTime)
  58. return await AuthenticateResultFailAsync("timestamp 值已超过允许的偏差范围");
  59. //获取 accessSecret
  60. var getAccessSecretContext = new GetAccessSecretContext(Context, Scheme, Options) { AccessKey = accessKey };
  61. var accessSecret = await Events.GetAccessSecret(getAccessSecretContext);
  62. if (string.IsNullOrEmpty(accessSecret))
  63. return await AuthenticateResultFailAsync("accessKey 无效");
  64. //校验签名
  65. var appSecretByte = Encoding.UTF8.GetBytes(accessSecret);
  66. string serverSign = SignData(appSecretByte, GetMessageForSign(Context));
  67. if (serverSign != sign)
  68. return await AuthenticateResultFailAsync("sign 无效的签名");
  69. //重放检测
  70. var cacheKey = $"{CacheConst.KeyOpenAccessNonce}{accessKey}|{nonce}";
  71. if (_cacheService.ExistKey(cacheKey))
  72. return await AuthenticateResultFailAsync("重复的请求");
  73. _cacheService.Set(cacheKey, null, Options.AllowedDateDrift * 2);//缓存过期时间为偏差范围时间的2倍
  74. //已验证成功
  75. var signatureValidatedContext = new SignatureValidatedContext(Context, Scheme, Options)
  76. {
  77. Principal = new ClaimsPrincipal(new ClaimsIdentity(SignatureAuthenticationDefaults.AuthenticationScheme)),
  78. AccessKey = accessKey
  79. };
  80. await Events.Validated(signatureValidatedContext);
  81. // ReSharper disable once ConditionIsAlwaysTrueOrFalse
  82. if (signatureValidatedContext.Result != null)
  83. return signatureValidatedContext.Result;
  84. // ReSharper disable once HeuristicUnreachableCode
  85. signatureValidatedContext.Success();
  86. return signatureValidatedContext.Result;
  87. }
  88. protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
  89. {
  90. var authResult = await HandleAuthenticateOnceSafeAsync();
  91. var challengeContext = new SignatureChallengeContext(Context, Scheme, Options, properties)
  92. {
  93. AuthenticateFailure = authResult.Failure,
  94. };
  95. await Events.Challenge(challengeContext);
  96. //质询已处理
  97. if (challengeContext.Handled) return;
  98. await base.HandleChallengeAsync(properties);
  99. }
  100. /// <summary>
  101. /// 获取用于签名的消息
  102. /// </summary>
  103. /// <returns></returns>
  104. private static string GetMessageForSign(HttpContext context)
  105. {
  106. var method = context.Request.Method;//请求方法(大写)
  107. var url = context.Request.Path;//请求 url,去除协议、域名、参数,以 / 开头
  108. var accessKey = context.Request.Headers["accessKey"].FirstOrDefault();//身份标识
  109. var timestamp = context.Request.Headers["timestamp"].FirstOrDefault();//时间戳,精确到秒
  110. var nonce = context.Request.Headers["nonce"].FirstOrDefault();//唯一随机数
  111. return $"{method}&{url}&{accessKey}&{timestamp}&{nonce}";
  112. }
  113. /// <summary>
  114. /// 对数据进行签名
  115. /// </summary>
  116. /// <param name="secret"></param>
  117. /// <param name="data"></param>
  118. /// <returns></returns>
  119. private static string SignData(byte[] secret, string data)
  120. {
  121. if (secret == null)
  122. throw new ArgumentNullException(nameof(secret));
  123. if (data == null)
  124. throw new ArgumentNullException(nameof(data));
  125. using HMAC hmac = new HMACSHA256();
  126. hmac.Key = secret;
  127. return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(data)));
  128. }
  129. /// <summary>
  130. /// 返回验证失败结果,并在 Items 中增加 <see cref="SignatureAuthenticationDefaults.AuthenticateFailMsgKey"/>,记录身份验证失败消息
  131. /// </summary>
  132. /// <param name="message"></param>
  133. /// <returns></returns>
  134. private Task<AuthenticateResult> AuthenticateResultFailAsync(string message)
  135. {
  136. //写入身份验证失败消息
  137. Context.Items[SignatureAuthenticationDefaults.AuthenticateFailMsgKey] = message;
  138. return Task.FromResult(AuthenticateResult.Fail(message));
  139. }
  140. }