自定义授权筛选器

Posted 很久很久以前

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义授权筛选器相关的知识,希望对你有一定的参考价值。

Demo

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class AdminAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (SkipAuthorization(filterContext))
            {
                return;
            }
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");

            //判断是否已登陆
            if (HttpContext.Current == null ||
                !HttpContext.Current.Request.IsAuthenticated ||
                !(HttpContext.Current.User.Identity is FormsIdentity))
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
            else
            {
                //判断角色权限
                var authenticationService = DependencyResolver.Current.GetService<IFormsAuthenticationService>();
                var roleRelationFunction = new List<CustomerRoleFunction>();
                var controllerName = filterContext.RouteData.Values["controller"].ToString();
                var actionName = filterContext.RouteData.Values["action"].ToString();
                var customer = authenticationService.GetCustomer();
                if (customer != null)
                {
                    roleRelationFunction.AddRange(customer.CustomerRoles.SelectMany(roles => roles.CustomerRoleFunctions));
                }
                if (!roleRelationFunction.Any(c => c.ActionName == actionName && c.ControllerName == controllerName))
                {
                    HandleUnauthorizedRequest(filterContext, "你无此权限,如需要请通知管理员添加,点击返回");
                }
            }
        }

        private void HandleUnauthorizedRequest(AuthorizationContext filterContext, string message)
        {
            var content = new ContentResult
            {
                Content = string.Format("<a href=‘javascript:history.go(-1);‘>{0}</a>", message)
            };
            filterContext.Result = content;
        }

        /// <summary>
        /// 过滤 AllowAnonymousAttribute 特性
        /// </summary>
        /// <param name="filterContext"></param>
        /// <returns></returns>
        private static bool SkipAuthorization(AuthorizationContext filterContext)
        {
            Contract.Assert(filterContext != null);

            return filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any()
                   || filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Any();
        }
    }

 

以上是关于自定义授权筛选器的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET MVC 如何使用自定义过滤器(筛选器)

VSCode自定义代码片段——CSS选择器

VSCode自定义代码片段6——CSS选择器

VSCode自定义代码片段(vue主模板)

VSCode自定义代码片段——声明函数

VSCode自定义代码片段——.vue文件的模板