Asp.Net MVC 許可權控制(一):使用 Authorize Roles 簡單實現

來源:互聯網
上載者:User

標籤:style   blog   http   使用   strong   檔案   

最近由於項目的需要對許可權控製做了幾個Demo,貼出來供大家拍磚!

 

首先建立一個 BaseController ,讓所有的Controller繼承自BaseController 。

    [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.zip

(註:由於dll太多,檔案壓縮過大,已將demo中dll包刪除)

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.