当我们使用Asp.net MVC Forms方式验证用户, 然后设置Controller 或 Action 的 Authorize属性时, 默认情况下只有Users属性可以设置(这里的Users通常是指用户登录名), 我们无法直接设置用户的角色信息 , 当建立一个依赖角色的应用时(又不想麻烦配置Membership),我们有必要给认证用户加上角色信息,下面是具体方法 :

1.Web.config 配置 ,以下设置标明我们使用Forms验证

  1. <authentication mode="Forms">
  2. <forms loginUrl="~/Account/LogIn" timeout="" slidingExpiration="true" cookieless="UseCookies" path="/" name=".MYASPXAUTH" />
  3. </authentication>
  4. <!--<authorization>
  5. <deny users="?"/>
  6. </authorization>-->

具体配置参考:http://msdn.microsoft.com/zh-cn/library/1d3t3c61(v=vs.100).aspx

  1. <forms
  2. name="name"
  3. loginUrl="URL"
  4. defaultUrl="URL"
  5. protection="[All|None|Encryption|Validation]"
  6. timeout="[MM]"
  7. path="path"
  8. requireSSL="[true|false]"
  9. slidingExpiration="[true|false]">
  10. enableCrossAppRedirects="[true|false]"
  11. cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]"
  12. domain="domain name"
  13. ticketCompatibilityMode="[Framework20|Framework40]">
  14. <credentials>...</credentials>
  15. </forms>

slidingExpiration:是否滑动过期,应设置为true    
    name属性:如果服务器有多个应用程序,每个应用程序的name属性应不同。
    上面代码注释掉了deny 设置,如果设置了上面的项,则所有页面都需要用户登录。注释掉之后,只在访问在Controller或Action上面设置了验证用户或角色的页面时,才提示登录。
2 Global.asax.cs 添加验证请求事件代码 ,如果用户信息已经设置, 则重新构造带角色信息的用户对象 , 角色信息从身份凭证票据的UserData属性中获取,多个角色以逗号隔开。

  1. protected void Application_AuthenticateRequest(object sender, EventArgs e)
  2. {
  3. var app = sender as HttpApplication;
  4.  
  5. if (app.Context.User != null)
  6. {
  7. var user = app.Context.User;
  8. var identity = user.Identity as FormsIdentity;
  9.  
  10. // We could explicitly construct an Principal object with roles info using System.Security.Principal.GenericPrincipal
  11. var principalWithRoles = new GenericPrincipal(identity, identity.Ticket.UserData.Split(','));
  12.  
  13. // Replace the user object
  14. app.Context.User = principalWithRoles;
  15. }
  16. }

上面代码是Asp.net请求管道中的一个环节,每次请求时都会执行。
    如果UserData中还想保存其它数据,需要使用其它分隔符进行分割并处理。
    这种方式主要用于系统功能简单,角色较少的应用。
经过上面角色的转换,系统就可以直接使用内部定义的验证方式进行验证了。

3.用户合法性验证通过后, 构造带角色信息的加密身份凭据 , 角色信息存储在票据的UserData中。

  1. [HttpPost]
  2. public ActionResult LogOn(User user)
  3. {
  4. // check user by quering database or other ways. skip this logic.
  5.  
  6. string userRoles = "admin,user,powerUser";
  7. bool isPersistent = false;
  8. int version = ;
  9. double persistentMinutes = 30.00; // minutes
  10. string userName = user.Name;
  11.  
  12. string cookiePath = FormsAuthentication.FormsCookiePath;
  13.  
  14. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(version, userName, DateTime.Now, DateTime.Now.AddMinutes(persistentMinutes), isPersistent, userRoles, cookiePath);
  15. string encryptedTicket = FormsAuthentication.Encrypt(ticket);
  16.  
  17. HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
  18. Response.Cookies.Add(cookie);
  19.  
  20. return Redirect(Request.QueryString["returnUrl"]);
  21. }

isPersistent:是否将cookie持久化保存到客户端硬盘。一般应该选择false,即每次访问都要登录。但可以将用户名保存到客户端,用户登录时直接取得并设为默认。

  1. HttpCookie userNmaecook=new HttpCookie("MyAppUserName",userName);
  2. vljidcook.Expires=DateTime.Now.AddDays();
  3. this.Context.Response.Cookies.Add(userNmaecook);

4. 使用角色信息控制用户对Controller 或 Action 的访问 , 因为我们上面设置用户拥有admin , user , powerUser 角色, 所以用户有权访问此方法

  1. public class HomeController : Controller
  2. {
  3. [Authorize(Roles="admin,powerUser")]
  4. public ActionResult Index()
  5. {
  6. //用户拥有 admin,user,powerUser 角色, 所以可以访问此方法。
  7. return View();
  8. }
  9. }

一般权限应按ontroller设置,后台管理和前台浏览使用不同的controller。

5. 以下是AuthorizeAttribute AuthorizeCore方法的源码 , 我们可以看到其中只要用户有AuthorizeAttribute.Roles设置中的任意角色, 就可以通过AuthorizeAttribute 的审核

  1. // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
  2. protected virtual bool AuthorizeCore(HttpContextBase httpContext)
  3. {
  4. if (httpContext == null)
  5. {
  6. throw new ArgumentNullException("httpContext");
  7. }
  8.  
  9. IPrincipal user = httpContext.User;
  10. if (!user.Identity.IsAuthenticated)
  11. {
  12. return false;
  13. }
  14.  
  15. if (_usersSplit.Length > && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
  16. {
  17. return false;
  18. }
  19.  
  20. if (_rolesSplit.Length > && !_rolesSplit.Any(user.IsInRole))
  21. {
  22. return false;
  23. }
  24.  
  25. return true;
  26. }

给Asp.net MVC Forms 验证设置角色访问控制的更多相关文章

  1. 【MVC】ASP.NET MVC Forms验证机制

    http://www.cnblogs.com/bomo/p/3309766.html 随笔 - 121  文章 - 0  评论 - 92 [MVC]ASP.NET MVC Forms验证机制 ASP. ...

  2. ASP.NET MVC Forms验证机制

    ASP.NET MVC 3 使用Forms身份验证 身份验证流程 一.用户登录 1.验证表单:ModelState.IsValid 2.验证用户名和密码:通过查询数据库验证 3.如果用户名和密码正确, ...

  3. Asp.Net MVC 身份验证-Forms

    Asp.Net MVC 身份验证-Forms 在MVC中对于需要登录才可以访问的页面,只需要在对应的Controller或Action上添加特性[Authorize]就可以限制非登录用户访问该页面.那 ...

  4. ASP.NET MVC异步验证是如何工作的03,jquery.validate.unobtrusive.js是如何工作的

    在上一篇"ASP.NET MVC异步验证是如何工作的02,异步验证表单元素的创建"中了解了ASP.NET异步验证是如何创建表单元素的,本篇体验jquery.validate.uno ...

  5. Asp.Net的Forms验证,解决Cookie和Seesion失效时间

    网站开发中用户验证一般采用Asp.Net的Forms验证,验证票据存储到Cookie的方式. Session方式是将验证信息存储在内存中,如果你使用的虚拟主机给你分配很小的内存,实际上都是如此,那么s ...

  6. ASP.NET MVC Model验证(五)

    ASP.NET MVC Model验证(五) 前言 上篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现, 然而在MVC框架中还给我们提供了其它 ...

  7. ASP.NET MVC Model验证(四)

    ASP.NET MVC Model验证(四) 前言 本篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现,前者是Model验证提供程序,而Mod ...

  8. ASP.NET MVC 5 - 验证编辑方法(Edit method)和编辑视图(Edit view)

    在本节中,您将验证电影控制器生成的编辑方法(Edit action methods)和视图.但是首先将修改点代码,使得发布日期属性(ReleaseDate)看上去更好.打开Models \ Movie ...

  9. 通过扩展改善ASP.NET MVC的验证机制[实现篇]

    原文:通过扩展改善ASP.NET MVC的验证机制[实现篇] 在<使用篇>中我们谈到扩展的验证编程方式,并且演示了本解决方案的三大特性:消息提供机制的分离.多语言的支持和多验证规则的支持, ...

随机推荐

  1. 在C#中dagagridview绑定list泛型

    今天在项目中由于需要使用到datagridview绑定list的数据源,在针对list的添加.删除.修改都可以很好地完成,可是在初始化datagridview时,却发现了问题,绑定数据源后,并没有在列 ...

  2. leetcode:Partition List

    题目:Given a linked list and a value x, partition it such that all nodes less than x come before nodes ...

  3. 如何使用LiveSuite debian img格式的镜像文件刷入nand

    1. liveSuite启动后 2. 选择固件(就是对应的img文件) 3. 将cubieboard板子的fel按钮按住不要松,然后使用otg接口线插入电脑和cubieboard板子,直到liveSu ...

  4. 51nod1084 矩阵取数问题 V2

    O(n4)->O(n3)妈呀为什么跑这么慢woc #include<cstdio> #include<cstring> #include<cctype> #i ...

  5. [转] POJ数学问题

    转自:http://blog.sina.com.cn/s/blog_6635898a0100magq.html 1.burnside定理,polya计数法 这个大家可以看brudildi的<组合 ...

  6. C语言之复杂指针详解

    在<C陷阱与缺陷>第二章第一节中有这样一个声明: (*(void(*)())0)(): 看到这样的表达式估计让不少人都“不寒而栗”了吧,其实虽然看起来复杂,但是构造这类表达式其实只有一条简 ...

  7. 用canvas实现图片滤镜效果详解之灰度效果

    前面展示了一些canvas实现图片滤镜效果的展示,并且给出了相应的算法,下面来介绍一下具体的实现方法. 前面介绍的特效中灰度效果最简单,就从这里开始介绍吧. 1.获取图像数据 img.src = ’h ...

  8. Ensemble Learning 之 Gradient Boosting 与 GBDT

    之前一篇写了关于基于权重的 Boosting 方法 Adaboost,本文主要讲述 Boosting 的另一种形式 Gradient Boosting ,在 Adaboost 中样本权重随着分类正确与 ...

  9. 【自动化测试】Selenium的智能等待

    dr.implicitly_wait(30) --- 智能等待 http://www.cnblogs.com/fnng/p/3214112.html =========== selenium 调用键盘 ...

  10. 【解题报告】zju-1145 Dreisam Equations

    原题地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=145 题目大意:在给定的等式右边数字之间加上加.减.乘运算符,使等式成 ...