asp.net mvc 中,抛弃membership结合自定义的权限表来使用[Authorize]

来源:互联网 发布:51黑子单片机论坛 编辑:程序博客网 时间:2024/05/17 21:49

        asp.net mvc 中使用[Authorize]属性,必须要开启角色管理,同时还要使用membership。这对于自定义的权限系统来说,有种“鱼和熊掌不能兼得”的感觉,但可以通过使用FormsAuthenticationTicket,将角色信息添加到cookies中,然后将cookies读出来,获得角色信息添加到HttpContext.User中,这样当使用[Authorize]属性时,就会得到角色信息。实际上网上有这样的文章,只是没有关于这样的说明。

        另外还有人提出这样的方法:继承AuthorizeAttribute,override AuthorizeCore方法。

以下代码来自网络:

MVC2中Authorize中的代码(AuthorizeAttribute.cs)是这样的:

        // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.        protected virtual bool AuthorizeCore(HttpContextBase httpContext) {            if (httpContext == null) {                throw new ArgumentNullException("httpContext");            }            IPrincipal user = httpContext.User;            if (!user.Identity.IsAuthenticated) {                return false;            }            if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {                return false;            }            if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {                return false;            }            return true;        }

根据代码,修改httpContext.User的信息。
1。修改Global.asax

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)        {            string cookieName = FormsAuthentication.FormsCookieName;            HttpCookie authCookie = Context.Request.Cookies[cookieName];            FormsAuthenticationTicket authTicket = null;            if (authCookie!=null)            {                authTicket = FormsAuthentication.Decrypt(authCookie.Value);                string[] roles = authTicket.UserData.Split(new char[] { ',' });//如果存取多个角色,我们把它分解                FormsIdentity id = new FormsIdentity(authTicket);                GenericPrincipal principal = new GenericPrincipal(id, roles);                Context.User = principal;//存到HttpContext.User中            }


2。在MODEL的signIn的方法中添加下列代码:

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, userName, DateTime.Now, DateTime.Now.AddMinutes(60), false, "Admin,Test");            string encryptedTicket = FormsAuthentication.Encrypt(ticket);            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket);            HttpContext.Current.Response.Cookies.Add(authCookie);

代码很简单,具体内容不解释 。此文仅仅作为个人的一个工作日志

原创粉丝点击