详解.Net Core 权限验证与授权(AuthorizeFilter、ActionFilterAttribute)

过去的习惯,决定今天的你,所以,过去的懒惰,决定你今天的一败涂地。人来到这世界后,命运注定了他必须要拼搏,奋斗,坚持,勇敢地走下去,走出属于自己的道路,没有人能不劳而获。

在.Net Core 中使用AuthorizeFilter或者ActionFilterAttribute来实现登录权限验证和授权

一、AuthorizeFilter

新建授权类AllowAnonymous继承AuthorizeFilter,IAllowAnonymousFilter

public class AllowAnonymous : AuthorizeFilter, IAllowAnonymousFilter
{

 }

新建拦截类继承AuthorizeFilter

public class LoginAuthorzation : AuthorizeFilter
{

}

在拦截类里加入处理请求的方法

  /// <summary>
  /// 请求验证,当前验证部分不要抛出异常,ExceptionFilter不会处理
  /// </summary>
  /// <param name="context">请求内容信息</param>
  public override async Task OnAuthorizationAsync(AuthorizationFilterContext context)
  {
   if (IsHaveAllow(context.Filters))
   {
    return;
   }
 

   //解析url
   // {/ Home / Index}
   var url = context.HttpContext.Request.Path.Value;
   if (string.IsNullOrWhiteSpace(url))
   {
    return;
   }

   var list = url.Split("/");
   if (list.Length<=0||url=="/")
   {
    return;
   }
   var controllerName = list[1].ToString().Trim();
   var actionName = list[2].ToString().Trim();
 

   //验证
   var flag=PowerIsTrue.IsHavePower(controllerName, actionName);
   if (flag.Item1!=0)
   {

    context.Result = new RedirectResult("/Home/Index");
   }
  }
 

//判断是否不需要权限

public static bool IsHaveAllow(IList<IFilterMetadata> filers)
  {
   for (int i = 0; i < filers.Count; i++)
   {
    if (filers[i] is IAllowAnonymousFilter)
    {
     return true;
    }
   }
   return false;

  } 

新建一个业务逻辑判断的类

public static (int,string) IsHavePower(string controllerName,string actionName)
  {

   return (0,"通过");

  }

在Startup注册

 services.AddMvc(options =>
   {

    options.Filters.Add<LoginAuthorzation>(); // 添加身份验证过滤器

   }

context.HttpContext.Request.Path.Value 获取请求过来的url

二、ActionFilterAttribute

创建权限判断类继承ActionFilterAttribute

public class ActionFilterAttributeLogin: ActionFilterAttribute
 {
  public override void OnActionExecuting(ActionExecutingContext filterContext)

   {
   var isDefined = false;
   var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
   if (controllerActionDescriptor != null)
   {
    isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
     .Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)));
   }
   if (isDefined) return;
   if (string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Query["LoginInfo"].ToString()))
   {
    var item = new ContentResult();
    item.Content = "没得权限";
    
    filterContext.Result = new RedirectResult("/Account/Login");
   }
   base.OnActionExecuting(filterContext);
  }

  public class NoPermissionRequiredAttribute : ActionFilterAttribute
  {
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
    base.OnActionExecuting(filterContext);

   }

  }
 }

在Startup注册

services.AddMvc(options =>
   {
    options.Filters.Add<ActionFilterAttributeLogin>(); // 添加身份验证过滤器 -- 菜单操作权限

   }

filterContext.ActionDescriptor as ControllerActionDescriptor 获取请求进来的控制器与方法

controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true )

.Any(a => a.GetType().Equals( typeof (NoPermissionRequiredAttribute))) 判断请求的控制器和方法有没有加上NoPermissionRequiredAttribute(不需要权限)

string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Query["LoginInfo"].ToString()) 判断请求头是否有标识

本文详解.Net Core 权限验证与授权(AuthorizeFilter、ActionFilterAttribute)到此结束。我们人这一辈子不是别人的楷模,就是别人的借鉴。小编再次感谢大家对我们的支持!

标签: Core Net