.Net Core 权限验证与授权(AuthorizeFilterActionFilterAttribute)

Posted hulizhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.Net Core 权限验证与授权(AuthorizeFilterActionFilterAttribute)相关的知识,希望对你有一定的参考价值。

在.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 权限验证与授权(AuthorizeFilterActionFilterAttribute)的主要内容,如果未能解决你的问题,请参考以下文章

[Asp.Net Core]鉴权授权

.Net Core 2.1 WepAPI 中使用 JWT 的身份验证和授权

[Asp.Net Core]NET5策略鉴权

[Asp.Net Core]NET5策略鉴权

asp.net core 2.0 web api基于JWT自定义策略授权

ASP.NET Core - AddJwtBearer - 授权 URL,它是如何工作的?