using Furion; using Furion.Authorization; using Furion.DataEncryption; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using YBEE.EQM.Application; using YBEE.EQM.Core; namespace YBEE.EQM.Web.Core; public class JwtHandler : AppAuthorizeHandler { /// /// 重写 Handler 添加自动刷新 /// /// /// public override async Task HandleAsync(AuthorizationHandlerContext context) { // 自动刷新Token if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext(), App.GetOptions().ExpiredTime, App.GetOptions().ExpiredTime)) { await AuthorizeHandleAsync(context); } else { context.Fail(); // 授权失败 DefaultHttpContext currentHttpContext = context.GetCurrentHttpContext(); if (currentHttpContext == null) { return; } currentHttpContext.SignoutToSwagger(); } } /// /// 授权判断逻辑,授权通过返回 true,否则返回 false /// /// /// /// public override async Task PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext) { // 此处已经自动验证 Jwt Token的有效性了,无需手动验证 return await CheckAuthorzieAsync(httpContext); } /// /// 检查权限 /// /// /// private static async Task CheckAuthorzieAsync(DefaultHttpContext httpContext) { // 管理员跳过判断 //var isSuperAdmin = bool.Parse() if (bool.TryParse(App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value ?? "False", out bool isSuperAdmin)) { if (isSuperAdmin) { return true; } } // 路由名称 var routeName = httpContext.Request.Path.Value[1..].Replace("/", ":"); // 默认路由(获取登录用户信息) var defalutRoute = new List() { "get-login-user", //登录 }; if (defalutRoute.Contains(routeName)) { return true; } // 获取用户权限集合(按钮或API接口) var allPermissionList = await App.GetService().GetAllPermissionList(); var currUserId = int.Parse(App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value ?? "0"); var permissionList = await App.GetService().GetLoginPermissionList(currUserId); // 检查授权 // 菜单中没有配置按钮权限,则不限制 return allPermissionList.All(u => u != routeName) || permissionList.Contains(routeName); } }