SysOpenAccessService.cs 8.2 KB

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