【MVC5】使用权限+角色
2015-10-27 11:24
274 查看
1.在Ticket中设置用户角色
在权限的Ticket中设置用户的角色(这里是逗号分割)。List<string> roles = new List<string>(); if (isAdmin) { roles.Add("Admin"); } roles.Add("Guest"); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, model.UserId, DateTime.Now, DateTime.Now.AddDays(30), // 设置记住登录的时间(这里是30天) true, String.Join(",", roles)); // 设置用户角色 HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); // 设置cookie的过期时间(这里是50年) cookie.Expires = DateTime.Now.AddYears(50); Response.Cookies.Add(cookie);
2.在Global.asax.cs中添加Application_AuthenticateRequest方法
protected void Application_AuthenticateRequest(object sender, EventArgs e) { // 取得认证Check的Cookie HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) return; // 解密 FormsAuthenticationTicket ticket = null; try { ticket = FormsAuthentication.Decrypt(cookie.Value); } catch (Exception) { return; } if (ticket == null) return; // 取得ticket.UserData中设定的角色 string[] roles = ticket.UserData.Split(new char[] { ',' }); // From认证中,使用IPrincipal对象中的GenericPrincipal类。 // 该类由表示资格情报的FormsIdentity类和角色信息(string[]对象)组成。 FormsIdentity identity = new FormsIdentity(ticket); GenericPrincipal principal = new GenericPrincipal(identity, roles); // 把FormsIdentity赋值到Context.User中 // 可以从Page.User中取得该值 Context.User = principal; }
3.在Controller中使用Authorize特性
// 允许匿名访问 [AllowAnonymous] public class HomeController : Controller { ...... } // 只允许登录用户访问 [Authorize] public class SampleController : Controller { ...... } // 只允许具有"Admin"角色的用户访问 [Authorize(Roles = "Admin")] public class SampleController : Controller { ...... } // 该特性同样可用于Action
参照:http://www.atmarkit.co.jp/ait/articles/0307/26/news002_2.html
已同步到【MVC5】ASP.NET MVC 项目笔记汇总
相关文章推荐
- 设置IE文本模式,兼容css
- 使用xhprof对php性能追踪分析
- sz 与 rz 命令
- 虚拟主机配置
- centos6.5 安装svn可视化管理工具 if.svnadmin
- 【NOIP2011】聪明的质检员 二分
- 单元测试——破除依赖
- 微信开发、申请测试号
- 10.26 作业
- 忽略某些文件
- Hadoop-1.x 单机模式部署与测试
- 论文笔记:Ten years of pedestrian detection, what have we learned?
- Unity鼠标设置
- tomcat整合axis2
- HR说简历还是这个格式比较好
- OC --- Category
- poj 2739
- Adaptive to the device and user Device Compatibility , language configuration comments
- 教你如何更改xshell中的转发规则
- Linux下Tomcat的启动、关闭、杀死进程