SysOpenAccessService.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 GenerateSignature(GenerateSignatureInput input)
  33. {
  34. // 密钥
  35. var appSecretByte = Encoding.UTF8.GetBytes(input.AccessSecret);
  36. // 拼接参数
  37. var parameter = $"{input.Method.ToString().ToUpper()}&{input.Url}&{input.AccessKey}&{input.Timestamp}&{input.Nonce}";
  38. // 使用 HMAC-SHA256 协议创建基于哈希的消息身份验证代码 (HMAC),以appSecretByte 作为密钥,对上面拼接的参数进行计算签名,所得签名进行 Base-64 编码
  39. using HMAC hmac = new HMACSHA256();
  40. hmac.Key = appSecretByte;
  41. var sign = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(parameter)));
  42. return sign;
  43. }
  44. /// <summary>
  45. /// 获取开放接口身份分页列表 🔖
  46. /// </summary>
  47. /// <param name="input"></param>
  48. /// <returns></returns>
  49. [DisplayName("获取开放接口身份分页列表")]
  50. public async Task<SqlSugarPagedList<OpenAccessOutput>> Page(OpenAccessInput input)
  51. {
  52. return await _sysOpenAccessRep.AsQueryable()
  53. .LeftJoin<SysUser>((u, a) => u.BindUserId == a.Id)
  54. .LeftJoin<SysTenant>((u, a, b) => u.BindTenantId == b.Id)
  55. .LeftJoin<SysOrg>((u, a, b, c) => b.OrgId == c.Id)
  56. .WhereIF(!string.IsNullOrWhiteSpace(input.AccessKey?.Trim()), (u, a, b, c) => u.AccessKey.Contains(input.AccessKey))
  57. .Select((u, a, b, c) => new OpenAccessOutput
  58. {
  59. BindUserAccount = a.Account,
  60. BindTenantName = c.Name,
  61. }, true)
  62. .ToPagedListAsync(input.Page, input.PageSize);
  63. }
  64. /// <summary>
  65. /// 增加开放接口身份 🔖
  66. /// </summary>
  67. /// <param name="input"></param>
  68. /// <returns></returns>
  69. [ApiDescriptionSettings(Name = "Add"), HttpPost]
  70. [DisplayName("增加开放接口身份")]
  71. public async Task AddOpenAccess(AddOpenAccessInput input)
  72. {
  73. if (await _sysOpenAccessRep.AsQueryable().AnyAsync(u => u.AccessKey == input.AccessKey && u.Id != input.Id))
  74. throw Oops.Oh(ErrorCodeEnum.O1000);
  75. var openAccess = input.Adapt<SysOpenAccess>();
  76. await _sysOpenAccessRep.InsertAsync(openAccess);
  77. }
  78. /// <summary>
  79. /// 更新开放接口身份 🔖
  80. /// </summary>
  81. /// <param name="input"></param>
  82. /// <returns></returns>
  83. [ApiDescriptionSettings(Name = "Update"), HttpPost]
  84. [DisplayName("更新开放接口身份")]
  85. public async Task UpdateOpenAccess(UpdateOpenAccessInput input)
  86. {
  87. if (await _sysOpenAccessRep.AsQueryable().AnyAsync(u => u.AccessKey == input.AccessKey && u.Id != input.Id))
  88. throw Oops.Oh(ErrorCodeEnum.O1000);
  89. var openAccess = input.Adapt<SysOpenAccess>();
  90. _sysCacheService.Remove(CacheConst.KeyOpenAccess + openAccess.AccessKey);
  91. await _sysOpenAccessRep.UpdateAsync(openAccess);
  92. }
  93. /// <summary>
  94. /// 删除开放接口身份 🔖
  95. /// </summary>
  96. /// <param name="input"></param>
  97. /// <returns></returns>
  98. [ApiDescriptionSettings(Name = "Delete"), HttpPost]
  99. [DisplayName("删除开放接口身份")]
  100. public async Task DeleteOpenAccess(DeleteOpenAccessInput input)
  101. {
  102. var openAccess = await _sysOpenAccessRep.GetFirstAsync(u => u.Id == input.Id);
  103. if (openAccess != null)
  104. _sysCacheService.Remove(CacheConst.KeyOpenAccess + openAccess.AccessKey);
  105. await _sysOpenAccessRep.DeleteAsync(u => u.Id == input.Id);
  106. }
  107. /// <summary>
  108. /// 创建密钥 🔖
  109. /// </summary>
  110. /// <returns></returns>
  111. [DisplayName("创建密钥")]
  112. public async Task<string> CreateSecret()
  113. {
  114. return await Task.FromResult(Convert.ToBase64String(Guid.NewGuid().ToByteArray())[..^2]);
  115. }
  116. /// <summary>
  117. /// 根据 Key 获取对象
  118. /// </summary>
  119. /// <param name="accessKey"></param>
  120. /// <returns></returns>
  121. [NonAction]
  122. public async Task<SysOpenAccess> GetByKey(string accessKey)
  123. {
  124. return await Task.FromResult(
  125. _sysCacheService.GetOrAdd(CacheConst.KeyOpenAccess + accessKey, _ =>
  126. {
  127. return _sysOpenAccessRep.AsQueryable()
  128. .Includes(u => u.BindUser)
  129. .Includes(u => u.BindUser, p => p.SysOrg)
  130. .First(u => u.AccessKey == accessKey);
  131. })
  132. );
  133. }
  134. /// <summary>
  135. /// Signature 身份验证事件默认实现
  136. /// </summary>
  137. [NonAction]
  138. public static SignatureAuthenticationEvent GetSignatureAuthenticationEventImpl()
  139. {
  140. return new SignatureAuthenticationEvent
  141. {
  142. OnGetAccessSecret = context =>
  143. {
  144. var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<SysOpenAccessService>>();
  145. try
  146. {
  147. var openAccessService = context.HttpContext.RequestServices.GetRequiredService<SysOpenAccessService>();
  148. var openAccess = openAccessService.GetByKey(context.AccessKey).GetAwaiter().GetResult();
  149. return Task.FromResult(openAccess == null ? "" : openAccess.AccessSecret);
  150. }
  151. catch (Exception ex)
  152. {
  153. logger.LogError(ex, "开放接口身份验证");
  154. return Task.FromResult("");
  155. }
  156. },
  157. OnValidated = context =>
  158. {
  159. var openAccessService = context.HttpContext.RequestServices.GetRequiredService<SysOpenAccessService>();
  160. var openAccess = openAccessService.GetByKey(context.AccessKey).GetAwaiter().GetResult();
  161. var identity = ((ClaimsIdentity)context.Principal!.Identity!);
  162. identity.AddClaims(new[]
  163. {
  164. new Claim(ClaimConst.UserId, openAccess.BindUserId + ""),
  165. new Claim(ClaimConst.TenantId, openAccess.BindTenantId + ""),
  166. new Claim(ClaimConst.Account, openAccess.BindUser.Account + ""),
  167. new Claim(ClaimConst.RealName, openAccess.BindUser.RealName),
  168. new Claim(ClaimConst.AccountType, ((int)openAccess.BindUser.AccountType).ToString()),
  169. new Claim(ClaimConst.OrgId, openAccess.BindUser.OrgId + ""),
  170. new Claim(ClaimConst.OrgName, openAccess.BindUser.SysOrg?.Name + ""),
  171. new Claim(ClaimConst.OrgType, openAccess.BindUser.SysOrg?.Type + ""),
  172. });
  173. return Task.CompletedTask;
  174. }
  175. };
  176. }
  177. }