用户名:
密 码: 记住
您当前的位置:首页 > 网络编程 > Net教程

ASP.NET MVC 中实现基于角色的权限控制的处理方法

时间:2015-01-29  来源:互联网  作者:佚名

[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)

来顶一下
返回首页
返回首页
推荐资讯
Repeater控件动态变更列(Header,Item和Foot)信息实现思路 Repeater控件动态变更列(Header,It需求开发一个小报表,显示最近五个月的summary的数量统计,报
Repeater的FooterTemplate显示某列总计思路与代码 Repeater的FooterTemplate显示某列练习一个小功能,在Repeater的FooterTemplate显示某列总计,
相关文章
栏目更新
栏目热门