【发布时间】:2014-03-28 09:17:09
【问题描述】:
从 .net 版本 3.5 升级到 4.5 后,FormsAuthentication 中的角色停止工作。用户已通过身份验证,但框架似乎没有获取角色信息,并且用户被拒绝访问管理内容。
这是登录用户的代码:
int timeout = int.Parse(ConfigurationManager.AppSettings["loginTimeoutMinutes"]);
HttpContext.Current.Session.Timeout = timeout;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(timeout),
false,
roles,
FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(cookie);
在 Global.asax 中,此代码使用角色信息更新当前用户。当我调试时,我可以看到角色是管理员:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated &&
HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity) HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
这是主 web.config 的身份验证位:
<roleManager enabled="true"></roleManager>
<authentication mode="Forms">
<forms name="theForm" loginUrl="/login.aspx"/>
</authentication>
登录后,用户将被重定向到文件夹中的文件,该文件带有以下web.config:
<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<authorization>
<allow roles="admin" />
<deny users="*"/>
</authorization>
</system.web>
</configuration>
当我调试时一切看起来都很好,但用户被拒绝访问管理页面。
我错过了什么吗?帮助表示赞赏。 (我知道之前有人问过这个问题,但我在 stackoverflow 上阅读了大约 50 个问题/答案,并尝试了所有建议但没有找到答案)
(另外一个奇怪的是升级.net版本后我不得不添加
<add key="enableSimpleMembership" value="false"/>
到 web.config 以获取重定向以转到正确的登录页面。)
【问题讨论】:
标签: c# asp.net .net authentication webforms