栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

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

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/57916.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号