using Furion;
using Furion.Authorization;
using Furion.DataEncryption;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace BPA.MES.Base.Web.Core;
public class JwtHandler : AppAuthorizeHandler
{
///
/// 重写 Handler 添加自动刷新收取逻辑
///
///
///
public override async Task HandleAsync(AuthorizationHandlerContext context)
{
var IsClient = App.HttpContext.Request.Headers["IsClient"].ToString();
if (IsClient == "true")
{
//获取所有未成功验证的需求
var pendingRequirements = context.PendingRequirements;
// 通过授权验证
foreach (var requirement in pendingRequirements)
{
context.Succeed(requirement);
}
}
else
{
// 自动刷新 token
if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext(), expiredTime: 43200, refreshTokenExpiredTime: 43225))
{
await AuthorizeHandleAsync(context);
}
else
{
context.Fail(); // 授权失败
}
}
}
public override Task PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
{
// 这里写您的授权判断逻辑,授权通过返回 true,否则返回 false
return Task.FromResult(CheckAuthorzie(httpContext));
}
///
/// 检查权限
///
///
///
private static bool CheckAuthorzie(DefaultHttpContext httpContext)
{
// 获取权限特性
var IsClient = App.HttpContext.Request.Headers["IsClient"].ToString();
if (IsClient == "true")
{
return true;
}
var securityDefineAttribute = httpContext.GetMetadata();
if (securityDefineAttribute == null)
{
return true;
}
else
{
return false;
}
}
}