亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

ASP.NET MVC 中實(shí)現(xiàn)基于角色的權(quán)限控制的處理方法

 更新時(shí)間:2013年03月20日 15:42:53   作者:  
在ASP.NET MVC中,通過(guò)使用其所提供的內(nèi)置

[Authorize]
public ActionResult Index()

標(biāo)記的方式,可以實(shí)現(xiàn)所標(biāo)記的ACTION必須是認(rèn)證用戶才能訪問(wèn);

通過(guò)使用

[Authorize(Users="username")]

的方式,可以實(shí)現(xiàn)所標(biāo)記的ACTION必須是某個(gè)具體的用戶才能訪問(wèn),以上兩種方式使用起來(lái)非常方便,在NeedDinner示例程序中已有具休的實(shí)現(xiàn)過(guò)程,

但是,我們?cè)趯?shí)際的應(yīng)用中所使用的大都是基于角色(Roles)的認(rèn)證方式,NeedDinner中卻未給出,本文給出具體實(shí)現(xiàn)(基于ASP.NET Forms驗(yàn)證)過(guò)程:

step 1
在完成UserName和Password認(rèn)證后,向客戶端寫入認(rèn)證Cookie

代碼

復(fù)制代碼 代碼如下:

        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
            1,
            userName,
            DateTime.Now,
            DateTime.Now.AddMinutes(20),
            false,
            "admin"http://寫入用戶角色
            );

        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

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

step 2
在Global.asax.cs文件中加入以下代碼,用于在用戶登陸網(wǎng)站時(shí)讀取Cookie

代碼

復(fù)制代碼 代碼如下:

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

step 3

這樣以來(lái),就可以使用實(shí)現(xiàn)以下效果

復(fù)制代碼 代碼如下:

  [Authorize(Roles="admin")]
    public ActionResult Index(int ? page)

相關(guān)文章

最新評(píng)論