You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BookingHeChuan/Myshipping.Web.Core/Handlers/JwtHandler.cs

104 lines
3.1 KiB
C#

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