我正在将我的应用程序从mvc4 asp.net4更新为.net4.5,用户角色无效。
目前我正在使用此代码
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
string[] roles = authTicket.UserData.Split(new Char[] { ',' });
GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
Context.User = userPrincipal;
//Or
//HttpContext.Current.User = userPrincipal;
}
}
我可以在上面的帮助下向当前用户添加角色,并检查控制器中的用户角色 [授权(Roles =“Admin,Guest”)]或User.IsInRole(“Admin”)
但是我的代码在MVC4 ASP.Net 4.5中不起作用
我不想使用角色提供程序。例如Roles.CreateRole或Roles.AddUserToRole
有人可以帮我解决这个问题 感谢
答案 0 :(得分:0)
即使在MVC 4 .NET 4.0下我也可以重现这个问题。不知道为什么它不会在.NET 4.0下为你重现。
看起来甚至你在Application_AuthenticateRequest中替换了主体。委托人最终将通过简单的成员资格代码替换为System.Web.Security.RolePrincipal,我相信RolePrincipal将查询数据库以获取用户的角色数据。由于您不使用RoleProvider,因此RolePrincipal将不包含任何角色数据,它将删除先前主体的角色数据。
可能的解决方法是将Application_AuthenticateRequest更改为Application_AuthorizeRequest,这在简单成员资格设置RolePrincipal之后发生。 顺便说一下,你应该将HttpContext.User和Thread.CurrentPrincipal都设置为同一个用户。
如果上述解决方法适合您,请告诉我。
答案 1 :(得分:0)
在.NET 4.5中,GenericPrincipal现在继承自System.Security.Claims.ClaimsPrincipal;以前它继承自System.Object。
我们的应用程序将其存储在会话中(在数据库中),但它似乎以不同的方式序列化和反序列化一些声明内部,因为我遇到了类似的问题,缺少角色。