代码改变世界

ASP.NET Core 下自定义权限验证

2019-04-24 20:36  音乐让我说  阅读(3134)  评论(0编辑  收藏  举报

效果图:

 

 

 

 

如果没有权限时,显示:

代码:

 

    public class AuthorizeAdminAttribute : TypeFilterAttribute
    {
        #region 字段

        private readonly bool _ignoreFilter;

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ignore">是否忽略过滤。默认为false</param>
        public AuthorizeAdminAttribute(bool ignore = false) : base(typeof(AuthorizeAdminFilter))
        {
            this._ignoreFilter = ignore;
            this.Arguments = new object[] { ignore };
        }

        #endregion

        #region 属性

        /// <summary>
        /// 获取是否忽略过滤?
        /// </summary>
        public bool IgnoreFilter => _ignoreFilter;

        #endregion


        #region 内部过滤器

        /// <summary>
        /// 管理员授权过滤器
        /// </summary>
        private class AuthorizeAdminFilter : IAuthorizationFilter
        {
            #region 字段

            private readonly bool _ignoreFilter;
            //private readonly IPermissionService _permissionService; 
            //假设这个 IPermissionService 是我们业务上需要访问数据库获取用户是否有权限访问的类。

            #endregion

            #region 构造函数

            public AuthorizeAdminFilter(bool ignoreFilter /*, IPermissionService permissionService*/ )
            {
                this._ignoreFilter = ignoreFilter;
                //this._permissionService = permissionService;
            }

            #endregion

            #region 方法

            public void OnAuthorization(AuthorizationFilterContext filterContext)
            {
                if (filterContext == null)
                    throw new ArgumentNullException(nameof(filterContext));

                //检查是否已经被 Action 方法重写了
                var actionFilter = filterContext.ActionDescriptor.FilterDescriptors
                    .Where(filterDescriptor => filterDescriptor.Scope == FilterScope.Action)
                    .Select(filterDescriptor => filterDescriptor.Filter).OfType<AuthorizeAdminAttribute>().FirstOrDefault();


                if (actionFilter?.IgnoreFilter ?? _ignoreFilter)
                    return;

                if (filterContext.Filters.Any(filter => filter is AuthorizeAdminFilter))
                {
                    //下面是访问自定义的服务,获取当前登录用户是否有权限访问
                    //bool hasPermission =  _permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel);
                    bool hasPermission = new Random().Next(1, 11) > 5 ? true : false;
                    if (!hasPermission)
                        filterContext.Result = new ChallengeResult();
                }
            }

            #endregion
        }

        #endregion
    }

 

使用方法:

 

谢谢浏览!