ASP.NET MVC 中實現基於角色的許可權控制的處理方法_實用技巧

來源:互聯網
上載者:User

[Authorize]
public ActionResult Index()

標記的方式,可以實現所標記的ACTION必須是認證使用者才能訪問;

通過使用

[Authorize(Users="username")]

的方式,可以實現所標記的ACTION必須是某個具體的使用者才能訪問,以上兩種方式使用起來非常方便,在NeedDinner樣本程式中已有具休的實現過程,

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

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

代碼

複製代碼 代碼如下:

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

        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檔案中加入以下代碼,用於在使用者登陸網站時讀取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

這樣以來,就可以使用實現以下效果

複製代碼 代碼如下:

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

聯繫我們

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