我有一个简单的代码,它基于文章
但是我的代码不起作用,我也不知道哪里是我的错。我使用非成员API。请提供以下建议:
Button_Click:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(1), true, role, FormsAuthentication.FormsCookiePath);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);Global.asax - Application_AuthenticateRequest
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity formsIdentity = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = formsIdentity.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(formsIdentity, roles);
}
}
}web.config
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="login.aspx"
timeout="1"
slidingExpiration="true"
cookieless="AutoDetect"
protection="All"
defaultUrl="logined.aspx"
path="/">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
<location path="default.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="register.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="adminPage.aspx">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>在调试器中,我看到字符串角色不是从Button_Click方法获得到Application_AuthenticateRequest中的。因此,如果Button_Click中的角色对于它的用户名等于"Admin“,那么在Application_AuthenticateRequest中,与ticket.userData相同的变量是相等的。为什么会发生这种事?
发布于 2014-03-27 00:14:58
问题是,如果创建RedirectFromLoginPage manullay,则不需要调用FormsAuthenticationTicket。
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
txtUsername.Text,
DateTime.Now, DateTime.Now.AddMinutes(1),
true,
role,
FormsAuthentication.FormsCookiePath);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
if (ticket.IsPersistent)
cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
/* Delete this line
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); */https://stackoverflow.com/questions/22675584
复制相似问题