欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

[Authorize]
public ActionResult Index()

標記的方式,可以實現(xiàn)所標記的ACTION必須是認證用戶才能訪問;

通過使用

[Authorize(Users="username")]

的方式,可以實現(xiàn)所標記的ACTION必須是某個具體的用戶才能訪問,以上兩種方式使用起來非常方便,在NeedDinner示例程序中已有具休的實現(xiàn)過程,

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

step 1
在完成UserName和Password認證后,向客戶端寫入認證Cookie

代碼

復制代碼 代碼如下:

        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)站時讀取Cookie

代碼

復制代碼 代碼如下:

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

這樣以來,就可以使用實現(xiàn)以下效果

復制代碼 代碼如下:

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

相關(guān)文章

最新評論