SuperApiAop.cs 4.3 KB

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