JwtHandler.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Admin.NET.Core;
  2. using Admin.NET.Core.Service;
  3. using Furion;
  4. using Furion.Authorization;
  5. using Furion.DataEncryption;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Microsoft.AspNetCore.Http;
  8. using System.Collections.Generic;
  9. using System.Threading.Tasks;
  10. namespace Admin.NET.Web.Core
  11. {
  12. public class JwtHandler : AppAuthorizeHandler
  13. {
  14. /// <summary>
  15. /// 自动刷新Token
  16. /// </summary>
  17. /// <param name="context"></param>
  18. /// <returns></returns>
  19. public override async Task HandleAsync(AuthorizationHandlerContext context)
  20. {
  21. if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext(),
  22. App.GetOptions<JWTSettingsOptions>().ExpiredTime,
  23. App.GetOptions<RefreshTokenOptions>().ExpiredTime))
  24. {
  25. await AuthorizeHandleAsync(context);
  26. }
  27. else
  28. {
  29. context.Fail(); // 授权失败
  30. DefaultHttpContext currentHttpContext = context.GetCurrentHttpContext();
  31. if (currentHttpContext == null)
  32. return;
  33. currentHttpContext.SignoutToSwagger();
  34. }
  35. }
  36. public override async Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
  37. {
  38. // 已自动验证 Jwt Token 有效性
  39. return await CheckAuthorzieAsync(httpContext);
  40. }
  41. /// <summary>
  42. /// 检查权限
  43. /// </summary>
  44. /// <param name="httpContext"></param>
  45. /// <returns></returns>
  46. private static async Task<bool> CheckAuthorzieAsync(DefaultHttpContext httpContext)
  47. {
  48. // 第三方授权模式
  49. if (App.User.FindFirst(ClaimConst.RunMode)?.Value == ((int)RunModeEnum.OpenID).ToString())
  50. return true;
  51. // 排除超管
  52. if (App.User.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString())
  53. return true;
  54. // 路由名称
  55. var routeName = httpContext.Request.Path.Value[1..].Replace("/", ":");
  56. if (httpContext.Request.Path.StartsWithSegments("/api"))
  57. routeName = httpContext.Request.Path.Value[5..].Replace("/", ":");
  58. // 默认路由
  59. var defalutRoutes = new List<string>()
  60. {
  61. "userInfo", // 获取用户信息
  62. "loginMenu", // 获取登录菜单
  63. };
  64. if (defalutRoutes.Contains(routeName)) return true;
  65. // 获取用户权限集合(按钮或API接口)
  66. var permissionList = await App.GetService<SysMenuService>().GetPermCodeList();
  67. var allPermissionList = await App.GetService<SysMenuService>().GetAllPermCodeList();
  68. // 检查授权(菜单中没有配置按钮权限,则不限制)
  69. return permissionList.Exists(p => p.Equals(routeName, System.StringComparison.CurrentCultureIgnoreCase)) ||
  70. allPermissionList.TrueForAll(p => !p.Equals(routeName, System.StringComparison.CurrentCultureIgnoreCase));
  71. }
  72. }
  73. }