Files
number_zj/20220330_Vote/Ewide.Web.Core/Handlers/JwtHandler.cs
2022-03-30 17:54:33 +08:00

79 lines
2.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Ewide.Core;
using Ewide.Core.Service;
using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace Ewide.Web.Core
{
public class JwtHandler : AppAuthorizeHandler
{
/// <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>
private static async Task<bool> CheckAuthorzieAsync(DefaultHttpContext httpContext)
{
// 管理员跳过判断
var userManager = App.GetService<IUserManager>();
if (userManager.SuperAdmin) return true;
// 路由名称
var routeName = httpContext.Request.Path.Value.Substring(1).Replace("/", ":");
// 默认路由(获取登录用户信息)
var defalutRoute = App.Configuration.GetSection("CoreSettings:DefalutRoute").Get<List<string>>();
//var defalutRoute = new List<string>()
//{
// "getLoginUser",
// "logout",
// "sysFileInfo:upload",
// "sysFileInfo:download",
// "sysFileInfo:preview",
// "sysUser:updateInfo"
//};
if (defalutRoute.Contains(routeName)) return true;
// 获取用户权限集合按钮或API接口
var permissionList = await userManager.GetLoginPermissionList();
// 检查授权
return permissionList.Contains(routeName);
}
}
}