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

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);

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值