给Asp.net MVC Forms 验证设置角色访问控制
当我们使用Asp.net MVC Forms方式验证用户, 然后设置Controller 或 Action 的 Authorize属性时, 默认情况下只有Users属性可以设置(这里的Users通常是指用户登录名), 我们无法直接设置用户的角色信息 , 当建立一个依赖角色的应用时(又不想麻烦配置Membership),我们有必要给认证用户加上角色信息,下面是具体方法 :
1.Web.config 配置 ,以下设置标明我们使用Forms验证
- <authentication mode="Forms">
- <forms loginUrl="~/Account/LogIn" timeout="" slidingExpiration="true" cookieless="UseCookies" path="/" name=".MYASPXAUTH" />
- </authentication>
- <!--<authorization>
- <deny users="?"/>
- </authorization>-->
具体配置参考:http://msdn.microsoft.com/zh-cn/library/1d3t3c61(v=vs.100).aspx
- <forms
- name="name"
- loginUrl="URL"
- defaultUrl="URL"
- protection="[All|None|Encryption|Validation]"
- timeout="[MM]"
- path="path"
- requireSSL="[true|false]"
- slidingExpiration="[true|false]">
- enableCrossAppRedirects="[true|false]"
- cookieless="[UseUri|UseCookies|AutoDetect|UseDeviceProfile]"
- domain="domain name"
- ticketCompatibilityMode="[Framework20|Framework40]">
- <credentials>...</credentials>
- </forms>
slidingExpiration:是否滑动过期,应设置为true
name属性:如果服务器有多个应用程序,每个应用程序的name属性应不同。
上面代码注释掉了deny 设置,如果设置了上面的项,则所有页面都需要用户登录。注释掉之后,只在访问在Controller或Action上面设置了验证用户或角色的页面时,才提示登录。
2 Global.asax.cs 添加验证请求事件代码 ,如果用户信息已经设置, 则重新构造带角色信息的用户对象 , 角色信息从身份凭证票据的UserData属性中获取,多个角色以逗号隔开。
- protected void Application_AuthenticateRequest(object sender, EventArgs e)
- {
- var app = sender as HttpApplication;
- if (app.Context.User != null)
- {
- var user = app.Context.User;
- var identity = user.Identity as FormsIdentity;
- // We could explicitly construct an Principal object with roles info using System.Security.Principal.GenericPrincipal
- var principalWithRoles = new GenericPrincipal(identity, identity.Ticket.UserData.Split(','));
- // Replace the user object
- app.Context.User = principalWithRoles;
- }
- }
上面代码是Asp.net请求管道中的一个环节,每次请求时都会执行。
如果UserData中还想保存其它数据,需要使用其它分隔符进行分割并处理。
这种方式主要用于系统功能简单,角色较少的应用。
经过上面角色的转换,系统就可以直接使用内部定义的验证方式进行验证了。
3.用户合法性验证通过后, 构造带角色信息的加密身份凭据 , 角色信息存储在票据的UserData中。
- [HttpPost]
- public ActionResult LogOn(User user)
- {
- // check user by quering database or other ways. skip this logic.
- string userRoles = "admin,user,powerUser";
- bool isPersistent = false;
- int version = ;
- double persistentMinutes = 30.00; // minutes
- string userName = user.Name;
- string cookiePath = FormsAuthentication.FormsCookiePath;
- FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(version, userName, DateTime.Now, DateTime.Now.AddMinutes(persistentMinutes), isPersistent, userRoles, cookiePath);
- string encryptedTicket = FormsAuthentication.Encrypt(ticket);
- HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
- Response.Cookies.Add(cookie);
- return Redirect(Request.QueryString["returnUrl"]);
- }
isPersistent:是否将cookie持久化保存到客户端硬盘。一般应该选择false,即每次访问都要登录。但可以将用户名保存到客户端,用户登录时直接取得并设为默认。
- HttpCookie userNmaecook=new HttpCookie("MyAppUserName",userName);
- vljidcook.Expires=DateTime.Now.AddDays();
- this.Context.Response.Cookies.Add(userNmaecook);
4. 使用角色信息控制用户对Controller 或 Action 的访问 , 因为我们上面设置用户拥有admin , user , powerUser 角色, 所以用户有权访问此方法
- public class HomeController : Controller
- {
- [Authorize(Roles="admin,powerUser")]
- public ActionResult Index()
- {
- //用户拥有 admin,user,powerUser 角色, 所以可以访问此方法。
- return View();
- }
- }
一般权限应按ontroller设置,后台管理和前台浏览使用不同的controller。
5. 以下是AuthorizeAttribute AuthorizeCore方法的源码 , 我们可以看到其中只要用户有AuthorizeAttribute.Roles设置中的任意角色, 就可以通过AuthorizeAttribute 的审核
- // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
- protected virtual bool AuthorizeCore(HttpContextBase httpContext)
- {
- if (httpContext == null)
- {
- throw new ArgumentNullException("httpContext");
- }
- IPrincipal user = httpContext.User;
- if (!user.Identity.IsAuthenticated)
- {
- return false;
- }
- if (_usersSplit.Length > && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
- {
- return false;
- }
- if (_rolesSplit.Length > && !_rolesSplit.Any(user.IsInRole))
- {
- return false;
- }
- return true;
- }
给Asp.net MVC Forms 验证设置角色访问控制的更多相关文章
- 【MVC】ASP.NET MVC Forms验证机制
http://www.cnblogs.com/bomo/p/3309766.html 随笔 - 121 文章 - 0 评论 - 92 [MVC]ASP.NET MVC Forms验证机制 ASP. ...
- ASP.NET MVC Forms验证机制
ASP.NET MVC 3 使用Forms身份验证 身份验证流程 一.用户登录 1.验证表单:ModelState.IsValid 2.验证用户名和密码:通过查询数据库验证 3.如果用户名和密码正确, ...
- Asp.Net MVC 身份验证-Forms
Asp.Net MVC 身份验证-Forms 在MVC中对于需要登录才可以访问的页面,只需要在对应的Controller或Action上添加特性[Authorize]就可以限制非登录用户访问该页面.那 ...
- ASP.NET MVC异步验证是如何工作的03,jquery.validate.unobtrusive.js是如何工作的
在上一篇"ASP.NET MVC异步验证是如何工作的02,异步验证表单元素的创建"中了解了ASP.NET异步验证是如何创建表单元素的,本篇体验jquery.validate.uno ...
- Asp.Net的Forms验证,解决Cookie和Seesion失效时间
网站开发中用户验证一般采用Asp.Net的Forms验证,验证票据存储到Cookie的方式. Session方式是将验证信息存储在内存中,如果你使用的虚拟主机给你分配很小的内存,实际上都是如此,那么s ...
- ASP.NET MVC Model验证(五)
ASP.NET MVC Model验证(五) 前言 上篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现, 然而在MVC框架中还给我们提供了其它 ...
- ASP.NET MVC Model验证(四)
ASP.NET MVC Model验证(四) 前言 本篇主要讲解ModelValidatorProvider 和ModelValidator两种类型的自定义实现,前者是Model验证提供程序,而Mod ...
- ASP.NET MVC 5 - 验证编辑方法(Edit method)和编辑视图(Edit view)
在本节中,您将验证电影控制器生成的编辑方法(Edit action methods)和视图.但是首先将修改点代码,使得发布日期属性(ReleaseDate)看上去更好.打开Models \ Movie ...
- 通过扩展改善ASP.NET MVC的验证机制[实现篇]
原文:通过扩展改善ASP.NET MVC的验证机制[实现篇] 在<使用篇>中我们谈到扩展的验证编程方式,并且演示了本解决方案的三大特性:消息提供机制的分离.多语言的支持和多验证规则的支持, ...
随机推荐
- 在C#中dagagridview绑定list泛型
今天在项目中由于需要使用到datagridview绑定list的数据源,在针对list的添加.删除.修改都可以很好地完成,可是在初始化datagridview时,却发现了问题,绑定数据源后,并没有在列 ...
- leetcode:Partition List
题目:Given a linked list and a value x, partition it such that all nodes less than x come before nodes ...
- 如何使用LiveSuite debian img格式的镜像文件刷入nand
1. liveSuite启动后 2. 选择固件(就是对应的img文件) 3. 将cubieboard板子的fel按钮按住不要松,然后使用otg接口线插入电脑和cubieboard板子,直到liveSu ...
- 51nod1084 矩阵取数问题 V2
O(n4)->O(n3)妈呀为什么跑这么慢woc #include<cstdio> #include<cstring> #include<cctype> #i ...
- [转] POJ数学问题
转自:http://blog.sina.com.cn/s/blog_6635898a0100magq.html 1.burnside定理,polya计数法 这个大家可以看brudildi的<组合 ...
- C语言之复杂指针详解
在<C陷阱与缺陷>第二章第一节中有这样一个声明: (*(void(*)())0)(): 看到这样的表达式估计让不少人都“不寒而栗”了吧,其实虽然看起来复杂,但是构造这类表达式其实只有一条简 ...
- 用canvas实现图片滤镜效果详解之灰度效果
前面展示了一些canvas实现图片滤镜效果的展示,并且给出了相应的算法,下面来介绍一下具体的实现方法. 前面介绍的特效中灰度效果最简单,就从这里开始介绍吧. 1.获取图像数据 img.src = ’h ...
- Ensemble Learning 之 Gradient Boosting 与 GBDT
之前一篇写了关于基于权重的 Boosting 方法 Adaboost,本文主要讲述 Boosting 的另一种形式 Gradient Boosting ,在 Adaboost 中样本权重随着分类正确与 ...
- 【自动化测试】Selenium的智能等待
dr.implicitly_wait(30) --- 智能等待 http://www.cnblogs.com/fnng/p/3214112.html =========== selenium 调用键盘 ...
- 【解题报告】zju-1145 Dreisam Equations
原题地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=145 题目大意:在给定的等式右边数字之间加上加.减.乘运算符,使等式成 ...