今天将使用Simplemembership进行权限控制

我们使用mvc的AuthorizeAttribute来实现对Controller and Action权限控制

看如下标为红色的代码片段:

 /// <summary>
        /// 删除数据操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
         [MVCSystemAuthorizeAttribute(permission = "删除")]
        [HttpPost]
        public JsonResult ArticlesDelete(int id)
        {
            if (id > 0)
            {
                var aList = db.DB_Articles.Find(id);
                db.DB_Articles.Remove(aList);
                db.SaveChanges();
                return Json(1, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(0, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 添加修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [MVCSystemAuthorizeAttribute(permission = "添加")]
        public ActionResult ArticleAddEdit(int id)
        {
            ViewBag.Type = db.DB_ArticleTypes.ToList();
            ViewBag.Member = db.DB_Members.ToList();
            if (id == 0)
            {

                var aList = new M_Articles();
                return View(aList);
            }
            else {
                var aList = db.DB_Articles.Find(id);
                return View(aList);
            }
        }

从之前生成的表可以看出,Permission表存储各个Action的名字(例如一个一个controller中的曾删改查各个Action),PermissionsInRoles表就是存储权限和角色关系。

然后我们在Filters/InitializeSimpleMembershipAttribute.cs中建立一个自己的MVCSystemAuthorizeAttribute继承AuthorizeAttribute,并重写AuthorizeCore和HandleUnauthorizedRequest方法。

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using WebMatrix.WebData;
using MVCSystem.Web.Models;
using MVCSystem.Web.Common;
using System.Web;

namespace MVCSystem.Web.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // 确保每次启动应用程序时只初始化一次 ASP.NET Simple Membership
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<MVCSystemContext>(null);

                try
                {
                    using (var context = new MVCSystemContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // 创建不包含 Entity Framework 迁移架构的 SimpleMembership 数据库
                           // ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("无法初始化 ASP.NET Simple Membership 数据库。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class MVCSystemAuthorizeAttribute : AuthorizeAttribute
    {
        private bool _authorize;

        private bool _isPermissionFail = false;

        public string permission { get; set; }

        public MVCSystemAuthorizeAttribute()
        {
            if (HttpContext.Current.User.Identity.Name != "")
            {
                _authorize = true;
            }
            else
            {
                _authorize = false;
            }
        }

        public MVCSystemAuthorizeAttribute(string permission)
        {
            if (HttpContext.Current.User.Identity.Name != "")
            {
                _authorize = PermissionManager.CheckUserHasPermision(HttpContext.Current.User.Identity.Name, permission);
                if (_authorize == false)
                {
                    _isPermissionFail = true;
                }
            }
            else
            {
                _authorize = false;
            }
            //_authorize = true;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("HttpContext");
            }
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }
            else
            {
                _authorize = PermissionManager.CheckUserHasPermision(HttpContext.Current.User.Identity.Name, permission);
                if (_authorize == false)
                {
                    _isPermissionFail = true;
                    return false;
                }
                return true;
            }
            // return false;
        }
        //protected override bool AuthorizeCore(HttpContextBase httpContext)
        //{
        //    return _authorize;
        //}

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (_isPermissionFail)
            {
                filterContext.HttpContext.Response.Redirect("/Admin/Error/ErrorNoper");
            }
            else
            {
                base.HandleUnauthorizedRequest(filterContext);
            }

        }
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-03-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案