Files
shanghaigangxiangtuzhuangMES/ZR.Admin.WebApi/Filters/VerifyAttribute.cs
2024-06-07 11:05:58 +08:00

57 lines
2.3 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 Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using NLog;
using ZR.Admin.WebApi.Extensions;
using ZR.Admin.WebApi.Framework;
using ZR.Model.System.Dto;
namespace ZR.Admin.WebApi.Filters
{
/// <summary>
/// 授权校验访问
/// 如果跳过授权登录在Action 或controller加上 AllowAnonymousAttribute
/// </summary>
public class VerifyAttribute : Attribute, IAuthorizationFilter
{
static readonly Logger logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// 只判断token是否正确不判断权限
/// 如果需要判断权限的在Action上加上ApiActionPermission属性标识权限类别ActionPermissionFilter作权限处理
/// </summary>
/// <param name="context"></param>
public void OnAuthorization(AuthorizationFilterContext context)
{
var noNeedCheck = false;
if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
{
noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
.Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));
}
//不需要检查 通过
if (noNeedCheck) return;
string ip = HttpContextExtension.GetClientUserIp(context.HttpContext);
string url = context.HttpContext.Request.Path;
// 这个是什么????? HttpContext的用户信息从何而来啊
Console.WriteLine("用户信息--》" + context.HttpContext.User.Identity.Name);
var isAuthed = context.HttpContext.User.Identity.IsAuthenticated;
//使用jwt token校验2020-11-21
//todo 认证是否合法用户和校验
LoginUser info = JwtUtil.GetLoginUser(context.HttpContext);
if (info == null || !isAuthed)
{
string msg = $"非法用户 请求访问[{url}]失败,无法访问系统资源";
logger.Info($"{msg}");
// 不通过终止 授权筛选器内的非null值将使筛选器管道的剩余部分短路。
context.Result = new JsonResult(new ApiResult((int)ResultCode.DENY, msg));
}
}
}
}