VerifyAttribute.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Web;
  2. using Common;
  3. using Extensions;
  4. using Infrastructure;
  5. using Infrastructure.Model;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.AspNetCore.Mvc.Controllers;
  9. using Microsoft.AspNetCore.Mvc.Filters;
  10. using Model.Base;
  11. using Util;
  12. //本命名空间暂时先不改,改动比较大2023年9月2日
  13. namespace Filters
  14. {
  15. /// <summary>
  16. /// 授权校验访问
  17. /// 如果跳过授权登录在Action 或controller加上 AllowAnonymousAttribute
  18. /// </summary>
  19. [AttributeUsage(AttributeTargets.All)]
  20. public class VerifyAttribute : System.Attribute, IAuthorizationFilter
  21. {
  22. private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
  23. /// <summary>
  24. /// 只判断token是否正确,不判断权限
  25. /// 如果需要判断权限的在Action上加上ApiActionPermission属性标识权限类别,ActionPermissionFilter作权限处理
  26. /// </summary>
  27. /// <param name="context"></param>
  28. public void OnAuthorization(AuthorizationFilterContext context)
  29. {
  30. var noNeedCheck = false;
  31. if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
  32. {
  33. noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
  34. .Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));
  35. }
  36. if (noNeedCheck) return;
  37. string ip = HttpContextExtension.GetClientUserIp(context.HttpContext);
  38. string url = context.HttpContext.Request.Path;
  39. var isAuthed = context.HttpContext.User.Identity.IsAuthenticated;
  40. string osType = context.HttpContext.Request.Headers["os"];
  41. //使用jwt token校验2020-11-21
  42. TokenModel loginUser = JwtUtil.GetLoginUser(context.HttpContext);
  43. if (loginUser != null)
  44. {
  45. var nowTime = DateTime.UtcNow;
  46. TimeSpan ts = loginUser.ExpireTime - nowTime;
  47. //Console.WriteLine($"jwt到期剩余:{ts.TotalMinutes}分,{ts.TotalSeconds}秒");
  48. var CK = "token_" + loginUser.UserId;
  49. if (!CacheHelper.Exists(CK) && ts.TotalMinutes < 5)
  50. {
  51. var newToken = JwtUtil.GenerateJwtToken(JwtUtil.AddClaims(loginUser));
  52. CacheHelper.SetCache(CK, CK, 1);
  53. //移动端不加下面这个获取不到自定义Header
  54. if (osType != null)
  55. {
  56. context.HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "X-Refresh-Token");
  57. }
  58. logger.Info($"刷新token,userName={loginUser.Username},token={newToken}");
  59. context.HttpContext.Response.Headers.Add("X-Refresh-Token", newToken);
  60. }
  61. }
  62. if (loginUser == null)
  63. {
  64. string msg = $"请求访问[{url}]失败,无法访问系统资源";
  65. //logger.Info(msg);
  66. context.Result = new JsonResult(ApiResult.Error(ResultCode.DENY, msg));
  67. }
  68. }
  69. }
  70. }