SysOpenAccessService.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using System.Security.Claims;
  7. using System.Security.Cryptography;
  8. namespace Admin.NET.Core.Service;
  9. /// <summary>
  10. /// 开放接口身份服务 🧩
  11. /// </summary>
  12. [ApiDescriptionSettings(Order = 244)]
  13. public class SysOpenAccessService : IDynamicApiController, ITransient
  14. {
  15. private readonly SqlSugarRepository<SysOpenAccess> _sysOpenAccessRep;
  16. private readonly SysCacheService _sysCacheService;
  17. /// <summary>
  18. /// 开放接口身份服务构造函数
  19. /// </summary>
  20. public SysOpenAccessService(SqlSugarRepository<SysOpenAccess> sysOpenAccessRep,
  21. SysCacheService sysCacheService)
  22. {
  23. _sysOpenAccessRep = sysOpenAccessRep;
  24. _sysCacheService = sysCacheService;
  25. }
  26. /// <summary>
  27. /// 获取生成的签名
  28. /// </summary>
  29. /// <param name="input"></param>
  30. /// <returns></returns>
  31. [DisplayName("获取生成的签名")]
  32. public string GetGenerateSignature([FromQuery] GenerateSignatureInput input)
  33. {
  34. // 密钥
  35. var appSecretByte = Encoding.UTF8.GetBytes(input.AppSecret);
  36. // 时间戳,精确到秒
  37. DateTimeOffset currentTime = DateTimeOffset.UtcNow;
  38. var timestamp = currentTime.ToUnixTimeSeconds();
  39. // 唯一随机数,可以使用guid或者雪花id,以下是sqlsugar提供获取雪花id的方法
  40. var nonce = YitIdHelper.NextId();
  41. //// 请求方式
  42. //var sMethod = method.ToString();
  43. // 拼接参数
  44. var parameter = $"{input.Method}&{input.Url}&{input.AccessKey}&{timestamp}&{nonce}";
  45. // 使用 HMAC-SHA256 协议创建基于哈希的消息身份验证代码 (HMAC),以appSecretByte 作为密钥,对上面拼接的参数进行计算签名,所得签名进行 Base-64 编码
  46. using HMAC hmac = new HMACSHA256();
  47. hmac.Key = appSecretByte;
  48. var sign = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(parameter)));
  49. return sign;
  50. }
  51. /// <summary>
  52. /// 获取开放接口身份分页列表 🔖
  53. /// </summary>
  54. /// <param name="input"></param>
  55. /// <returns></returns>
  56. [DisplayName("获取开放接口身份分页列表")]
  57. public async Task<SqlSugarPagedList<OpenAccessOutput>> Page(OpenAccessInput input)
  58. {
  59. return await _sysOpenAccessRep.AsQueryable()
  60. .LeftJoin<SysUser>((u, a) => u.BindUserId == a.Id)
  61. .LeftJoin<SysTenant>((u, a, b) => u.BindTenantId == b.Id)
  62. .LeftJoin<SysOrg>((u, a, b, c) => b.OrgId == c.Id)
  63. .WhereIF(!string.IsNullOrWhiteSpace(input.AccessKey?.Trim()), (u, a, b, c) => u.AccessKey.Contains(input.AccessKey))
  64. .Select((u, a, b, c) => new OpenAccessOutput
  65. {
  66. BindUserAccount = a.Account,
  67. BindTenantName = c.Name,
  68. }, true)
  69. .ToPagedListAsync(input.Page, input.PageSize);
  70. }
  71. /// <summary>
  72. /// 增加开放接口身份 🔖
  73. /// </summary>
  74. /// <param name="input"></param>
  75. /// <returns></returns>
  76. [ApiDescriptionSettings(Name = "Add"), HttpPost]
  77. [DisplayName("增加开放接口身份")]
  78. public async Task AddOpenAccess(AddOpenAccessInput input)
  79. {
  80. if (await _sysOpenAccessRep.AsQueryable().AnyAsync(u => u.AccessKey == input.AccessKey && u.Id != input.Id))
  81. throw Oops.Oh(ErrorCodeEnum.O1000);
  82. var openAccess = input.Adapt<SysOpenAccess>();
  83. await _sysOpenAccessRep.InsertAsync(openAccess);
  84. }
  85. /// <summary>
  86. /// 更新开放接口身份 🔖
  87. /// </summary>
  88. /// <param name="input"></param>
  89. /// <returns></returns>
  90. [ApiDescriptionSettings(Name = "Update"), HttpPost]
  91. [DisplayName("更新开放接口身份")]
  92. public async Task UpdateOpenAccess(UpdateOpenAccessInput input)
  93. {
  94. if (await _sysOpenAccessRep.AsQueryable().AnyAsync(u => u.AccessKey == input.AccessKey && u.Id != input.Id))
  95. throw Oops.Oh(ErrorCodeEnum.O1000);
  96. var openAccess = input.Adapt<SysOpenAccess>();
  97. _sysCacheService.Remove(CacheConst.KeyOpenAccess + openAccess.AccessKey);
  98. await _sysOpenAccessRep.UpdateAsync(openAccess);
  99. }
  100. /// <summary>
  101. /// 删除开放接口身份 🔖
  102. /// </summary>
  103. /// <param name="input"></param>
  104. /// <returns></returns>
  105. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  106. [DisplayName("删除开放接口身份")]
  107. public async Task DeleteOpenAccess(DeleteOpenAccessInput input)
  108. {
  109. var openAccess = await _sysOpenAccessRep.GetFirstAsync(u => u.Id == input.Id);
  110. if (openAccess != null)
  111. _sysCacheService.Remove(CacheConst.KeyOpenAccess + openAccess.AccessKey);
  112. await _sysOpenAccessRep.DeleteAsync(u => u.Id == input.Id);
  113. }
  114. /// <summary>
  115. /// 创建密钥 🔖
  116. /// </summary>
  117. /// <returns></returns>
  118. [DisplayName("创建密钥")]
  119. public async Task<string> CreateSecret()
  120. {
  121. return await Task.FromResult(Convert.ToBase64String(Guid.NewGuid().ToByteArray())[..^2]);
  122. }
  123. /// <summary>
  124. /// 根据 Key 获取对象
  125. /// </summary>
  126. /// <param name="accessKey"></param>
  127. /// <returns></returns>
  128. [NonAction]
  129. public async Task<SysOpenAccess> GetByKey(string accessKey)
  130. {
  131. return await Task.FromResult(
  132. _sysCacheService.GetOrAdd(CacheConst.KeyOpenAccess + accessKey, _ =>
  133. {
  134. return _sysOpenAccessRep.AsQueryable()
  135. .Includes(u => u.BindUser)
  136. .Includes(u => u.BindUser, p => p.SysOrg)
  137. .First(u => u.AccessKey == accessKey);
  138. })
  139. );
  140. }
  141. /// <summary>
  142. /// Signature 身份验证事件默认实现
  143. /// </summary>
  144. [NonAction]
  145. public static SignatureAuthenticationEvent GetSignatureAuthenticationEventImpl()
  146. {
  147. return new SignatureAuthenticationEvent
  148. {
  149. OnGetAccessSecret = context =>
  150. {
  151. var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<SysOpenAccessService>>();
  152. try
  153. {
  154. var openAccessService = context.HttpContext.RequestServices.GetRequiredService<SysOpenAccessService>();
  155. var openAccess = openAccessService.GetByKey(context.AccessKey).GetAwaiter().GetResult();
  156. return Task.FromResult(openAccess == null ? "" : openAccess.AccessSecret);
  157. }
  158. catch (Exception ex)
  159. {
  160. logger.LogError(ex, "开发接口身份验证");
  161. return Task.FromResult("");
  162. }
  163. },
  164. OnValidated = context =>
  165. {
  166. var openAccessService = context.HttpContext.RequestServices.GetRequiredService<SysOpenAccessService>();
  167. var openAccess = openAccessService.GetByKey(context.AccessKey).GetAwaiter().GetResult();
  168. var identity = ((ClaimsIdentity)context.Principal!.Identity!);
  169. identity.AddClaims(new[]
  170. {
  171. new Claim(ClaimConst.UserId, openAccess.BindUserId + ""),
  172. new Claim(ClaimConst.TenantId, openAccess.BindTenantId + ""),
  173. new Claim(ClaimConst.Account, openAccess.BindUser.Account + ""),
  174. new Claim(ClaimConst.RealName, openAccess.BindUser.RealName),
  175. new Claim(ClaimConst.AccountType, ((int)openAccess.BindUser.AccountType).ToString()),
  176. new Claim(ClaimConst.OrgId, openAccess.BindUser.OrgId + ""),
  177. new Claim(ClaimConst.OrgName, openAccess.BindUser.SysOrg?.Name + ""),
  178. new Claim(ClaimConst.OrgType, openAccess.BindUser.SysOrg?.Type + ""),
  179. });
  180. return Task.CompletedTask;
  181. }
  182. };
  183. }
  184. }