asp.netcookiesform-authentication

If FormsAuthentication Ticket is set, why doesn't User.IsInRole(“Admin”) work?


In the debugger, if I dig into the User object, I can see the current member's UserData property, ((System.Web.Security.FormsIdentity(User.Identity)).Ticket.UserData, has "admin" in it.

User.Identity.IsAuthenticated works but User.IsInRole("admin") returns false.

If "admin" is in the UserData property, then why doesn't User.IsInRole("admin") return true?

In my login method I have the authentication ticket set up as follows:

 FormsAuthenticationTicket _ticket = new FormsAuthenticationTicket(1, lUserName.Text, DateTime.Now, DateTime.Now.AddMonths(1), chk_remember.Checked, Role, FormsAuthentication.FormsCookiePath);
        string encTicket = FormsAuthentication.Encrypt(_ticket);
        HttpCookie _cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        if (chk_remember.Checked)
            _cookie.Expires = DateTime.Now.AddMonths(1);
        Response.Cookies.Add(_cookie);

Solution

  • you need to put this code in your Global.asax

    protected void Application_AuthenticateRequest(Object sender,
    EventArgs e)
    {
      if (HttpContext.Current.User != null)
      {
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
         if (HttpContext.Current.User.Identity is FormsIdentity)
         {
            FormsIdentity id =
                (FormsIdentity)HttpContext.Current.User.Identity;
            FormsAuthenticationTicket ticket = id.Ticket;
    
            // Get the stored user-data, in this case, our roles
            string userData = ticket.UserData;
            string[] roles = userData.Split(',');
            HttpContext.Current.User = new GenericPrincipal(id, roles);
         }
        }
      }
    }
    

    for more information you can see this link form authentication