码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2019-04-27 19:33:04      阅读:429      评论:0      收藏:0      [点我收藏+]

标签:over   request   class   iss   请求   使用   list   添加   ext   

在.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)

标签:over   request   class   iss   请求   使用   list   添加   ext   

原文地址:https://www.cnblogs.com/hulizhong/p/10779687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!