Asp.Net MVC 权限控制(一):使用 Authorize Roles 简单实现_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > Asp.Net MVC 权限控制(一):使用 Authorize Roles 简单实现

Asp.Net MVC 权限控制(一):使用 Authorize Roles 简单实现

 2014/7/4 18:56:40  Jetlian  程序员俱乐部  我要评论(0)
  • 摘要:最近由于项目的需要对权限控制做了几个Demo,贴出来供大家拍砖!首先创建一个BaseController,让所有的Controller继承自BaseController。[Authorize]publicclassBaseController:Controller{}系统登录需要一个AccountController,继承自BaseController,并添加匿名访问标记AllowAnonymous。AccountController实现系统的登录功能,并将用户信息保存到Cookie中
  • 标签:

最近由于项目的需要对权限控制做了几个Demo,贴出来供大家拍砖!

 

首先创建一个 BaseController ,让所有的Controller继承自BaseController 。

class="brush:csharp;gutter:true;">    [Authorize]
    public class BaseController : Controller
    {

    }

 

系统登录需要一个 AccountController ,继承自BaseController ,并添加匿名访问标记 AllowAnonymous。

AccountController 实现系统的登录功能,并将用户信息保存到Cookie中。

    [AllowAnonymous]
    public class AccountController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            string roles = "";
            var userName = model.UserName;
            if (userName == "admin")
            {
                roles = "Admin";
            }
            else if (userName == "ib")
            {
                roles = "IBusiness";
            }
            else if(userName == "ia")
            {
                roles = "IApproval";
            }
            
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
            1,
            userName,
            DateTime.Now,
            DateTime.Now.AddMinutes(20),
            false,
            roles//写入用户角色
            );

            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

            return string.IsNullOrEmpty(returnUrl) ?
                RedirectToAction("Index", "Home")
                : RedirectToLocal(returnUrl);
        }

        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}

 

在系统的业务Controller中添加角色验证标记。

    [Authorize(Roles = "Admin,IBusiness,IApproval")]
    public class InfrastructureController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [Authorize(Roles = "IBusiness")]
        public ActionResult Add()
        {
            return View();
        }

        [Authorize(Roles = "IApproval")]
        public ActionResult Approval()
        {
            return this.View();
        }

    }

  

 最后在Global.asax中添加验证。

        /// <summary>
        /// 构造方法
        /// </summary>
        public MvcApplication()
        {
            AuthorizeRequest += new EventHandler(Application_AuthenticateRequest);
        }

        protected void Application_AuthenticateRequest(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);
            }
        }

  

截图:

 

 下载:AuthorizationPro

(注:由于dll太多,文件压缩过大,已将demo中dll包删除)

 

  • 相关文章
发表评论
用户名: 匿名