using Furion; using Furion.Authorization; using Furion.DataEncryption; using Myshipping.Core; using Myshipping.Core.Service; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; using Furion.Logging; using System.Diagnostics; namespace Myshipping.Web.Core; public class JwtHandler : AppAuthorizeHandler { #if DEBUG public JwtHandler() { } #else private ISysMenuService _sysMenuService; public JwtHandler(ISysMenuService sysMenuService) { _sysMenuService = sysMenuService; } #endif /// /// 重写 Handler 添加自动刷新 /// /// /// public override async Task HandleAsync(AuthorizationHandlerContext context) { // 自动刷新Token if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext())) { await AuthorizeHandleAsync(context); } else context.Fail(); // 授权失败 } /// /// 授权判断逻辑,授权通过返回 true,否则返回 false /// /// /// /// public override async Task PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext) { // 此处已经自动验证 Jwt Token的有效性了,无需手动验证 return await CheckAuthorzieAsync(httpContext); } /// /// 检查权限 /// /// /// private async Task CheckAuthorzieAsync(DefaultHttpContext httpContext) { // 管理员跳过判断 if (UserManager.IsSuperAdmin) return true; // 路由名称 var routeName = httpContext.Request.Path.Value.Substring(1).Replace("/", ":"); //字典数据前端需要,允许获取 if (routeName == "sysDictType:tree") return true; if (routeName == "sysUser:tree") return true; //用户修改密码权限:默认通过,即不需要给角色授权,也具有此权限 if (routeName == "sysUser:updatePwd") return true; Stopwatch sw = Stopwatch.StartNew(); #if DEBUG var _sysMenuService = App.GetService(); var allPermission = await _sysMenuService.GetAllPermission(); #else var allPermission = await _sysMenuService.GetAllPermission(); #endif httpContext.Response.Headers["CheckTimeCheckAuthorzie1"] = sw.ElapsedMilliseconds.ToString(); if (!allPermission.Contains(routeName)) { sw.Stop(); return true; } // 获取用户权限集合(按钮或API接口) var permissionList = await _sysMenuService.GetLoginPermissionList(UserManager.UserId); httpContext.Response.Headers["CheckTimeCheckAuthorzie2"] = sw.ElapsedMilliseconds.ToString(); sw.Stop(); // 检查授权 return permissionList.Contains(routeName); } }