Mar*_*B29 5 asp.net-mvc asp.net-mvc-2
我目前正在尝试在ASP.NET MVC2 Web应用程序中实现一些自定义安全性.
我正在尝试做一些非常简单的事情,因为我的代码如下所示,但出于某种原因,如果我[Authorize(Roles="Admins")]
在我的某个控制器操作上使用该属性,请检查Context.User.IsInRole("Admins")
或者Page.User.IsInRole("Admins")
它始终为false.
这User.Identity.Name
也是空白的,这也很奇怪.
请参阅下面的代码,我在cookie中使用FormsAuthenticationTicket,然后Application_AuthenticateRequest
我在Gloabl.asax 中的事件句柄中使用它来设置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();
}
Run Code Online (Sandbox Code Playgroud)
我的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;
}
Run Code Online (Sandbox Code Playgroud)
一旦我设置了context.User,我可以在监视窗口中查看对象设置完美,使用正确的名称等正确的角色,但是如果我尝试锁定控制器操作或从我的站点中的任何位置使用Principal它始终设置为空字符串,不分配任何角色!
我猜我在做一些非常愚蠢的事情,但如果有人能指出这一点,我会非常感激.
检查您是否将新的 userPrincipal 分配给 Global.asax 中 OnPostAuthenticate 请求中的 HttpContext 和当前线程:
HttpContext.Current.User = userPrincipal;
Thread.CurrentPrincipal = userPrincipal;
Run Code Online (Sandbox Code Playgroud)