2022-04-06 22:22:45 +08:00
|
|
|
|
using Microsoft.AspNetCore.Mvc.Filters;
|
2022-04-09 16:16:32 +08:00
|
|
|
|
using Microsoft.IdentityModel.JsonWebTokens;
|
2022-04-06 22:22:45 +08:00
|
|
|
|
using System;
|
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
|
using System.Linq;
|
2022-05-04 15:54:40 +08:00
|
|
|
|
using System.Text.RegularExpressions;
|
2022-04-06 22:22:45 +08:00
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
|
|
namespace Yi.Framework.WebCore.AttributeExtend
|
|
|
|
|
|
{
|
|
|
|
|
|
[AttributeUsage(AttributeTargets.Method)]
|
|
|
|
|
|
public class PermissionAttribute : ActionFilterAttribute
|
|
|
|
|
|
{
|
|
|
|
|
|
private string permission { get; set; }
|
|
|
|
|
|
|
|
|
|
|
|
public PermissionAttribute(string permission)
|
|
|
|
|
|
{
|
|
|
|
|
|
this.permission = permission;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// 动作鉴权
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
/// <param name="context"></param>
|
|
|
|
|
|
/// <exception cref="Exception"></exception>
|
|
|
|
|
|
public override void OnActionExecuting(ActionExecutingContext context)
|
|
|
|
|
|
{
|
|
|
|
|
|
base.OnActionExecuting(context);
|
|
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrEmpty(permission))
|
|
|
|
|
|
{
|
|
|
|
|
|
throw new Exception("权限不能为空!");
|
|
|
|
|
|
}
|
2022-04-09 16:16:32 +08:00
|
|
|
|
var result = false;
|
|
|
|
|
|
|
2022-04-06 22:22:45 +08:00
|
|
|
|
|
|
|
|
|
|
//可以从Redis得到用户菜单列表,或者直接从jwt中获取
|
2022-04-09 16:16:32 +08:00
|
|
|
|
var sid = context.HttpContext.User.Claims.FirstOrDefault(u => u.Type == JwtRegisteredClaimNames.Sid);
|
2022-04-06 22:22:45 +08:00
|
|
|
|
|
2022-04-09 16:16:32 +08:00
|
|
|
|
//jwt存在的权限列表
|
|
|
|
|
|
var perList = context.HttpContext.User.Claims.Where(u => u.Type == "permission").Select(u=> u.Value.ToString().ToLower()). ToList();
|
|
|
|
|
|
//判断权限是否存在Redis中,或者jwt中
|
2022-04-06 22:22:45 +08:00
|
|
|
|
|
2022-05-04 15:54:40 +08:00
|
|
|
|
//进行正则表达式的匹配
|
|
|
|
|
|
Regex regex = new Regex($"{permission.ToLower()}");
|
|
|
|
|
|
foreach (var p in perList)
|
|
|
|
|
|
{
|
2022-05-06 22:47:26 +08:00
|
|
|
|
//过滤多余的标签
|
|
|
|
|
|
p.Replace("Entity","");
|
|
|
|
|
|
p.Replace("entity","");
|
2022-05-04 15:54:40 +08:00
|
|
|
|
if (regex.IsMatch(p))
|
|
|
|
|
|
{
|
|
|
|
|
|
result = true;
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
//用户的增删改查直接可以user:*即可
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
//这里暂时全部放行即可
|
|
|
|
|
|
result = true;
|
2022-04-06 22:22:45 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (!result)
|
|
|
|
|
|
{
|
|
|
|
|
|
throw new Exception("拦截未授权请求!");
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|