ASP.NET MVC 페이지 기반 권한 관리

7923 단어
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
Authorize Attribute에서 계승하여 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 페이지.
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 페이지.
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는 설정하지 않았고 불법이며 되돌아오는 오류 정보만 다르다.)
비고: 이 방법은 본 블로그의 한 인형이 쓴 것에서 비롯된 것으로 글의 링크를 잊어버렸습니다. 이에 감사를 드립니다.

좋은 웹페이지 즐겨찾기