FormsAuthenticationTicket UserData为角色返回空

时间:2014-03-26 23:57:21

标签: c# asp.net asp.net-membership

我有一个简单的代码,它基于article

但我的代码不起作用,我不知道我的错在哪里。我使用非会员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相同的变量等于“”。为什么会这样?

1 个答案:

答案 0 :(得分:1)

问题是,如果您创建 FormsAuthenticationTicket manullay,则无需调用 RedirectFromLoginPage

 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);  */