asp.net-mvc – 在MVC2中使用FormsAuthenticationTicket cookie
我目前正在尝试在ASP.NET MVC2 Web应用程序中实现一些自定义安全性.
我正在尝试做一些非常简单的事情,因为我的代码如下所示,但出于某种原因,如果我在我的一个控制器操作上使用[Authorize(Roles =“Admins”)]属性,请检查Context.User.IsInRole(“Admins”) )或Page.User.IsInRole(“Admins”)它总是假的. User.Identity.Name也是空白也很奇怪. 请参阅下面的代码,我在cookie中使用FormsAuthenticationTicket,然后在Gloabl.asax中的Application_AuthenticateRequest事件句柄中使用它来设置Context.User和GenericPrincipal对象. 我的登录代码: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Login(string username,string password) { //this would obviously do a check against the supplied username and password if (true) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,username,DateTime.Now,DateTime.Now.AddMinutes(15),false,"Admins|Users|Members"); string encTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,encTicket); this.Response.Cookies.Add(cookie); string url = FormsAuthentication.GetRedirectUrl(username,false); Response.Redirect(url); } return View(); } 我的Global.asax代码: void MvcApplication_AuthenticateRequest(object sender,EventArgs e) { HttpApplication application = (HttpApplication)sender; HttpContext context = application.Context; var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { // Get the authentication ticket // and rebuild the principal & identity FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(cookie.Value); string[] roles = authTicket.UserData.Split(new Char[] { '|' }); GenericIdentity userIdentity = new GenericIdentity(authTicket.Name); GenericPrincipal userPrincipal = new GenericPrincipal(userIdentity,roles); context.User = userPrincipal; } 一旦我设置了context.User,我可以在监视窗口中查看对象设置完美,使用正确的名称等正确的角色,但是如果我尝试锁定控制器操作或从我的站点中的任何位置使用Principal它始终设置为空字符串,不分配任何角色! 我猜我在做一些非常愚蠢的事情,但如果有人能指出这一点,我会非常感激. 解决方法
检查您是否将新的userPrincipal分配给global.asax中的OnPostAuthenticate请求中的HttpContext和当前线程:
HttpContext.Current.User = userPrincipal; Thread.CurrentPrincipal = userPrincipal; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- asp.net-mvc-4 – ASP.NET MVC 4单独项目中的区域不工作(查
- asp.net-mvc – 基于声明的授权 – 如何管理声明
- asp.net – 在web.config中将子文件夹重写为子域
- 三重报价?如何在ASP.NET中分隔数据绑定的JavaScript字符串
- asp.net – Fulltext Query String的全文查询参数无效
- .Net Core技术研究-Span<T>和ValueTuple<T&
- asp.net-mvc-3 – 我应该尝试使用MVC3和ASP.net的F#吗?
- 如何找出重新启动ASP.NET Web应用程序的原因
- asp.net-mvc – BreadCrumb trail MVC3和Razor
- ASP.Net MVC C#另一个viewmodel中的两个viewmodel – 如何在