asp.net許可權認證:Forms認證

來源:互聯網
上載者:User

標籤:後台   override   orm   net   生產環境   role   foreach   dir   技術   

摘要:

明天就除夕了,閑著也是閑著,特地總結一些關於.net下的許可權認證的方法。

 

一、Forms認證

Forms認證即是表單認證,需提供身份id和密碼password的進行認證和授權管理。

應該是大家比較熟悉的一種,剛接觸.net可能都會學學這個東西。

下面看看他的工作方式:

 

二、看圖太乏味,我準備了一個demo

  

 

因為預設首頁為:IndexController/Index,這個頁面只要一行字 “Index”,

:

OK,頁面沒有做任何許可權控制,顯示正常。

 

接下來看看DefaultController/Index

using System.Web.Mvc;namespace Forms.Controllers{    public class DefaultController : Controller    {        [Authorize]        public ActionResult Index()        {            return View();        }    }}

  

訪問:http://localhost:12463/default

很明顯 沒有許可權查看,因為我們設定了許可權認證

[Authorize]public ActionResult Index()

 

一般情況下生產環境不會允許直接顯示這種401的錯誤

如果使用者沒有登入憑證,我們會要求使用者返回登入頁面完成認證操作,

Forms認證支援在web.config裡邊設定登入地址

 

好了,我們再試試:http://localhost:12463/default

如期跳轉至認證頁面!點擊login,認證成功的話會跳回 http://localhost:12463/default

我們看看login對應的幕後處理邏輯

        public ActionResult Index()        {            var returnUrl = Request["ReturnUrl"];            if (Request.HttpMethod == "POST")            {                var userid = Request["userid"];                var password = Request["password"];                if (userid == "123456" && password == "123456")                {                    var ticket = new FormsAuthenticationTicket(                        1,                        userid,                        DateTime.Now,                        DateTime.Now.AddMinutes(20),                        true,                        "role1,role2,role3",                        "/"                    );                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));                    cookie.HttpOnly = true;                    HttpContext.Response.Cookies.Add(cookie);                    return Redirect(returnUrl);                }            }            ViewBag.ReturnUrl = returnUrl;            return View();        }

  

  

 

好了,如願顯示!至此,簡單許可權認證完成了。

 

三、添加角色功能

前邊只是做了簡單的登入認證,如果項目要求許可權的認證粒度比較細的話,就不能滿足了。

比如:IndexNeedRole4隻對某role4開放

[MyAuthorize(Roles = "role4")]public ActionResult IndexNeedRole4(){    return View();}

 

我們需要建立用於驗證角色和使用者名稱的Authorize特性:MyAuthorize

    public class MyAuthorizeAttribute : AuthorizeAttribute    {        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)        {            var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];            var ticket = FormsAuthentication.Decrypt(cookie.Value);            var roles = ticket.UserData;            var inRoles = false;            foreach (var role in roles.Split(‘,‘))            {                if (Roles.Contains(role))                {                    inRoles = true;                    break;                }            }            return inRoles;        }    }

  

代碼加好了,我們再試試:http://localhost:12463/default/IndexNeedRole4

返回正常,回到了許可權認證介面。

點擊 login,發現這個頁面只是重新整理了,所有input都清空了

這是正常的,因為在login/index裡邊登入邏輯的ticket角色只賦值了"role1,role2,role3"

加上role4

        public ActionResult Index()        {            var returnUrl = Request["ReturnUrl"];            if (Request.HttpMethod == "POST")            {                var userid = Request["userid"];                var password = Request["password"];                if (userid == "123456" && password == "123456")                {                    var ticket = new FormsAuthenticationTicket(                        1,                        userid,                        DateTime.Now,                        DateTime.Now.AddMinutes(20),                        true,                        "role1,role2,role3,role4",                        "/"                    );                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));                    cookie.HttpOnly = true;                    HttpContext.Response.Cookies.Add(cookie);                    return Redirect(returnUrl);                }            }            ViewBag.ReturnUrl = returnUrl;            return View();        }

  

再次點擊login

OK, 如期顯示正常

 

asp.net許可權認證:Forms認證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.