ASP.NET MVC 中如何实现基于角色的权限控制

Posted on 2010-02-27 09:33  FreeSkyCD  阅读(373)  评论(0编辑  收藏  举报

阅读: 188 评论: 5 作者: Yinner 发表于 2010-02-27 09:33 原文链接

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

 

非常方便!
 

 

评论: 5 查看评论 发表评论

找优秀程序员,就在博客园


最新新闻:
· IBM发布第五代X架构 打破X86系统30年技术局限(2010-03-03 22:47)
· 互联网手机业务成香馍馍 上海电信盯牢3G市场(2010-03-03 22:38)
· Twitter信息总量即将突破100亿条大关(2010-03-03 22:34)
· Opera为何无法进一步拓展市场(2010-03-03 21:38)
· Symbian版 Skype登陆诺基亚Ovi Store(2010-03-03 21:04)

编辑推荐:Opera为何无法进一步拓展市场

网站导航:博客园首页  个人主页  新闻  闪存  小组  博问  社区  知识库

Copyright © 2024 FreeSkyCD
Powered by .NET 8.0 on Kubernetes