
给Asp.net MVC Forms 验证设置角色访问控制
发布日期:2021-05-09 04:22:22
浏览次数:17
分类:博客文章
本文共 3323 字,大约阅读时间需要 11 分钟。
当我们使用Asp.net MVC Forms方式验证用户, 然后设置Controller 或 Action 的 Authorize属性时, 默认情况下只有Users属性可以设置(这里的Users通常是指用户登录名), 我们无法直接设置用户的角色信息 , 当建立一个依赖角色的应用时(又不想麻烦配置Membership),我们有必要给认证用户加上角色信息,下面是具体方法 :
1.Web.config 配置 ,以下设置标明我们使用Forms验证 , 所有没有授权的用户无法访问带Authorize标记的 Controllers 和 Actions
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; } }
默认情况下角色信息是空的,如下图:
替换后, 如下图 :
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 = true; int version = 0; double persistentMinutes = 60.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"]); }
4. 使用角色信息控制用户对Controller 或 Action 的访问 , 因为我们上面设置用户拥有admin , user , powerUser 角色, 所以用户有权访问此方法
public class HomeController : Controller { [Authorize(Roles="admin,powerUser")] public ActionResult Index() { //用户拥有 admin,user,powerUser 角色, 所以可以访问此方法。 return View(); } }
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 > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) { return false; } if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) { return false; } return true; }
以上同样适用于 Asp.net WebForms 应用 。
发表评论
最新留言
做的很好,不错不错
[***.243.131.199]2025年03月31日 02时57分24秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Deepin_使用Python+MySQL创建工作日志记录
2021-05-09
dpdk在虚拟机上出错处理
2021-05-09
Nagios 系统监控基本安装配置过程详解
2021-05-09
Macbook 彻彻底底的卸载MySQL
2021-05-09
CSS 字体属性和文本属性的初步了解
2021-05-09
ASP.NET Core 一步步搭建个人网站(4)_主页和登录验证
2021-05-09
SSIS 转移数据库和SQL Server对象组件
2021-05-09
NumPy 学习 第一篇:ndarray 的创建和形状操纵
2021-05-09
NumPy 学习 第四篇:数组的基本操作
2021-05-09
正则表达式 第四篇:贪婪和消耗字符
2021-05-09
SQL Server 列存储索引 第二篇:设计
2021-05-09
ADF 第五篇:转换数据
2021-05-09
Databricks 第4篇:pyspark.sql 分组统计和窗口
2021-05-09
博客系列目录
2021-05-09
部署AlwaysOn第二步:配置AlwaysOn,创建可用性组
2021-05-09
PowerBI开发 第八篇:查询参数
2021-05-09
Execute SQL Task 第二篇:返回结果集
2021-05-09
我眼中的项目经理
2021-05-09
索引调优 第二篇:碎片整理
2021-05-09
SQL Server 存储中间结果集
2021-05-09