asp.net mvc 控制器&动作方法 角色 权限验证

来源:互联网 发布:网络稳定软件 编辑:程序博客网 时间:2024/05/21 10:37

环境:
Visual Studio Community 2015
Asp.net MVC5


第一步:
检查项目根目录的 Web.config 中的 system.web 节点中是否有下面这个节点,没有请添加
其中 loginUrl=”~/Account/Login” 表示当前用户无权访问动作方法或控制器时,自动被系统重定向到
Account控制器的 Login方法

    <authentication mode="Forms">      <forms loginUrl="~/Account/Login" timeout="2800" />    </authentication>

第二步:
在项目根目录的 Global.asax 里添加下面代码:
其中包含 MvcApplication 构造方法
这些代码用于在系统验证控制器或动作方法访问权限时,进行一个额外的角色验证

        public MvcApplication()        {            AuthorizeRequest += new EventHandler(ApplicationAuthenticateRequest);        }        protected void ApplicationAuthenticateRequest(Object sender, EventArgs e)        {            HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];            if (authCookie == null || authCookie.Value == "")            {                return;            }            FormsAuthenticationTicket authTicket = null;            try            {                authTicket = FormsAuthentication.Decrypt(authCookie.Value);            }            catch            {                return;            }            string[] roles = authTicket.UserData.Split(new char[] { ',' });            if (Context.User != null)            {                Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);            }        }

第三步:
登陆通过后,调用下面的方法,把角色写入cookie
其中第一个参数 userName 指可以唯一标识当前登陆用户的Id值
第二个参数roleName指当前用户的角色,例如可以是admin(管理员)

        private void SetAuthCookie(string userName, string roleName)        {            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(10), false, roleName);            string encryptTicket = FormsAuthentication.Encrypt(ticket);            System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);            System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);        }

第四步:
在动作方法或控制器上方加上以下特性
这种验证能实现,得益于第二步

   //表示只有角色为 admin 的用户才能访问   [Authorize(Roles = "admin")]

   //表示角色为 admin 或 normal 的用户能访问   [Authorize(Roles = "admin,normal")]
0 0
原创粉丝点击