SuperApiAop.cs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using Admin.NET.Core;
  7. using Furion.ClayObject;
  8. using Furion.DataEncryption;
  9. using Furion.FriendlyException;
  10. using Furion.JsonSerialization;
  11. using Microsoft.AspNetCore.Authentication;
  12. using Microsoft.AspNetCore.Authentication.JwtBearer;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.Extensions.Logging;
  15. using NewLife;
  16. using ReZero.SuperAPI;
  17. namespace Admin.NET.Plugin.ReZero.Service;
  18. /// <summary>
  19. /// 超级API接口拦截器
  20. /// </summary>
  21. public class SuperApiAop : DefaultSuperApiAop
  22. {
  23. public override async Task OnExecutingAsync(InterfaceContext aopContext)
  24. {
  25. if (aopContext.InterfaceType == InterfaceType.DynamicApi)
  26. {
  27. var authenticateResult = await aopContext.HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
  28. if (!authenticateResult.Succeeded)
  29. throw Oops.Oh("没权限 Unauthorized");
  30. }
  31. await base.OnExecutingAsync(aopContext);
  32. }
  33. public override async Task OnExecutedAsync(InterfaceContext aopContext)
  34. {
  35. InitLogContext(aopContext, LogLevel.Information);
  36. await base.OnExecutedAsync(aopContext);
  37. }
  38. public override async Task OnErrorAsync(InterfaceContext aopContext)
  39. {
  40. InitLogContext(aopContext, LogLevel.Error);
  41. await base.OnErrorAsync(aopContext);
  42. }
  43. /// <summary>
  44. /// 保存超级API接口日志
  45. /// </summary>
  46. /// <param name="aopContext"></param>
  47. /// <param name="logLevel"></param>
  48. private void InitLogContext(InterfaceContext aopContext, LogLevel logLevel)
  49. {
  50. var api = aopContext.InterfaceInfo;
  51. var context = aopContext.HttpContext;
  52. var accessToken = context.Response.Headers["access-token"].ToString();
  53. var token = string.IsNullOrWhiteSpace(accessToken)
  54. ? context.Request.Headers["Authorization"].ToString()
  55. : "Bearer " + accessToken;
  56. var claims = JWTEncryption.ReadJwtToken(token)?.Claims;
  57. var userName = claims?.FirstOrDefault(u => u.Type == ClaimConst.Account)?.Value;
  58. var realName = claims?.FirstOrDefault(u => u.Type == ClaimConst.RealName)?.Value;
  59. var paths = api.Url.Split('/');
  60. var actionName = paths[paths.Length - 1];
  61. var apiInfo = Clay.Object(new
  62. {
  63. requestUrl = api.Url,
  64. httpMethod = api.HttpMethod,
  65. displayTitle = api.Name,
  66. actionTypeName = actionName,
  67. controllerName = aopContext.InterfaceType == InterfaceType.DynamicApi ? $"ReZero动态-{api.GroupName}" : $"ReZero系统-{api.GroupName}",
  68. remoteIPv4 = context.GetRemoteIpAddressToIPv4(),
  69. userAgent = context.Request.Headers["User-Agent"],
  70. returnInformation = new
  71. {
  72. httpStatusCode = context.Response.StatusCode,
  73. },
  74. authorizationClaims = new[]
  75. {
  76. new
  77. {
  78. type = ClaimConst.Account,
  79. value = userName
  80. },
  81. new
  82. {
  83. type = ClaimConst.RealName,
  84. value = realName
  85. },
  86. },
  87. exception = aopContext.Exception == null ? null : JSON.Serialize(aopContext.Exception)
  88. });
  89. var logger = App.GetRequiredService<ILoggerFactory>().CreateLogger("System.Logging.LoggingMonitor");
  90. using var scope = logger.ScopeContext(new Dictionary<object, object> {
  91. { "loggingMonitor", apiInfo.ToString() }
  92. });
  93. logger.Log(logLevel, "ReZero超级API接口日志");
  94. }
  95. }