Monday, May 6, 2013

Role not found or none after implementing Form Authentication in website ASP.net C#

You add the code to check username/password and login functionality. But when you check

HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.IsInRole("admin"))

User is authenticated but role is none then you have to add the below code in Global.asax

  protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            FormsIdentity fi = (FormsIdentity)(User.Identity);
            FormsAuthenticationTicket k = fi.Ticket;
            String ud = k.UserData;
            String[] ar = ud.Split('|');
            HttpContext.Current.User = new GenericPrincipal(fi, ar);
        }
    }