ASP.NET MVC 基于页面的权限管理

2748人阅读 评论(0) 收藏 举报
分类:

ASP.NET MVC 中运用AOP的思想(Filter)来实现页面级别的权限。在每个页面里,我们再去管理更小级别的权限。

1.Models

1)PermissionItem

namespace AspNetMvcAuthDemo1.Models
{
    public class PermissionItem
    {
        public int ID { set; get; }

        public int PermissionID { set; get; }

        public string Name { set; get; }

        public string Route { set; get; }
    }
}
2)PermissionList

namespace AspNetMvcAuthDemo1.Models
{
    public class PermissionList
    {
        public int ID { set; get; }

        public int PermissionID { set; get; }

        public int UserID { set; get; }
    }
}
3)UrlAuthorizeEntities

namespace AspNetMvcAuthDemo1.Models
{
    public class UrlAuthorizeEntities
    {
        public IEnumerable<PermissionItem> PermissionItems = new List<PermissionItem> 
        {
            new PermissionItem{ ID = 1 , PermissionID = 1, Name = "Test Page 1", Route = "/Home/Page1" },
            new PermissionItem{ ID = 2 , PermissionID = 2, Name = "Test Page 2", Route = "/Home/Page2" },
            new PermissionItem{ ID = 3 , PermissionID = 3, Name = "Test Page 3", Route = "/Home/Page3" },
            new PermissionItem{ ID = 4 , PermissionID = 1, Name = "Test Page 4", Route = "/Home/Page4" },
            new PermissionItem{ ID = 5 , PermissionID = 2, Name = "Test Page 5", Route = "/Home/Page5" }
        };

        public IEnumerable<PermissionList> PermissionList = new List<PermissionList>
        {
            new PermissionList{ ID = 1 , PermissionID = 2, UserID = 1},
            new PermissionList{ ID = 2 , PermissionID = 3, UserID = 1},
        };
    }
}
2.账户帮助类-AccountHelper

包含两个方法,获取所有权限列表并缓存,获取用户权限并缓存。

namespace AspNetMvcAuthDemo1.UrlAuthorize
{
    /// <summary>
    /// Account Helper
    /// </summary>
    public static class AccountHelper
    {
        /// <summary>
        /// Get all permission list
        /// </summary>
        /// <returns>Permission List</returns>
        public static List<PermissionItem> GetPermissionItems()
        {
            if (HttpContext.Current.Cache["PermissionItems"] == null)
            {
                UrlAuthorizeEntities db = new UrlAuthorizeEntities();
                var items = db.PermissionItems.Where(c => c.PermissionID > 0).ToList();
                HttpContext.Current.Cache["PermissionItems"] = items;
            }

            return (List<PermissionItem>)HttpContext.Current.Cache["PermissionItems"];
        }

        /// <summary>
        /// Get User Permission
        /// </summary>
        /// <param name="userID">User ID</param>
        /// <returns>User Permission Array</returns>
        public static Int32[] GetUserPermission(int userID)
        {
            if (HttpContext.Current.Session["Permission"] == null)
            {
                UrlAuthorizeEntities db = new UrlAuthorizeEntities();
                var permissions = db.PermissionList.Where(c => c.UserID == userID).Select(c=>c.PermissionID).ToArray();
                HttpContext.Current.Session["Permission"] = permissions;
            }
            return (Int32[])HttpContext.Current.Session["Permission"];
        }
    }
}
3.Filter(AOP)-UrlAuthorizeAttribute

继承自AuthorizeAttribute,重写其OnAuthorization方法,实现AOP。

namespace AspNetMvcAuthDemo1.UrlAuthorize
{
    /// <summary>
    /// URL permission
    /// </summary>
    public class UrlAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// Rewrite OnAuthorization
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //Get permission list
            List<PermissionItem> pItems = AccountHelper.GetPermissionItems();

            //Get current page permission ID,if items is null,the page you what to access has not been configed.
            var item = pItems.FirstOrDefault(c => c.Route == filterContext.HttpContext.Request.Path);

            if (item != null)
            {
                int[] permissions = AccountHelper.GetUserPermission(int.Parse(filterContext.HttpContext.Session["UserID"].ToString()));
                if (Array.IndexOf<Int32>(permissions, item.PermissionID) == -1)
                {
                    //have not permission
                    filterContext.HttpContext.Response.Write("You have no permission to access this page.");
                    filterContext.HttpContext.Response.End();
                }
            }
            else
            {
                //the page you what to access has not been configed.
                filterContext.HttpContext.Response.Write("The page you want to access has not been configed permission.");
                filterContext.HttpContext.Response.End();
            }
        }
    }
}
4.控制器

namespace AspNetMvcAuthDemo1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public string Login()
        {
            HttpContext.Session["UserID"] = 1;
            return "Login success.";
        }

        [UrlAuthorize]
        public string Page1()
        {
            return "Page1";
        }

        [UrlAuthorize]
        public string Page2()
        {
            return "Page2";
        }

        [UrlAuthorize]
        public string Page3()
        {
            return "Page3";
        }

        [UrlAuthorize]
        public string Page4()
        {
            return "Page4";
        }

        [UrlAuthorize]
        public string Page5()
        {
            return "Page5";
        }

        [UrlAuthorize]
        public string Page6()
        {
            return "Page6";
        }
    }
}
6.Route Config

namespace AspNetMvcAuthDemo1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
            );
        }
    }
}
效果:

1)访问:http://localhost:5598/Home/Page1,结果:You have no permission to access this page.

2)访问:http://localhost:5598/Home/Page2,结果:Page2

3)访问:http://localhost:5598/Home/Page3,结果:Page3

4)访问:http://localhost:5598/Home/Page4,结果:You have no permission to access this page.

5)访问:http://localhost:5598/Home/Page5,结果:Page5

6)访问:http://localhost:5598/Home/Page6,结果:The page you want to access has not been configed permission.

具体逻辑请参照代码进行推理。(UserID =1 的用户有2,3权限,而2,3权限可以看2,3,5页面,所以,只有访问2,3,5才是合法的,其他都是非法,Page6没有配置,也是非法的,只是返回的错误信息不同。)

备注:这个做法是源于看过的博客园里面一个仁兄的做法写的,忘记文章链接了,在此表示感谢。










1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:392514次
    • 积分:7614
    • 等级:
    • 排名:第3014名
    • 原创:369篇
    • 转载:82篇
    • 译文:2篇
    • 评论:52条
    最新评论