title: Form Authentication : Roles (MVC 4) C#
body: <p>I am trying to implement Forms Authentication in my Application. I various examples and looked at the samples and questions provided in this forum and ASP.net MVC but I just can't get it to work. </p>
  
  <p>I manage to authenticate my user but the roles does not seem to work :-(</p>
  
  <p>I have setup my Web.Config as follow :</p>
  
  <p><code>&lt;authentication mode="Forms"&gt;
        &lt;forms loginUrl="~/Account/Login" timeout="2880" /&gt;
      &lt;/authentication&gt;</code> </p>
  
  <p>In my Controller I set the Index page to AllowAnonymous and then check in there if the user is authenticated. If not then redirect to the login page..</p>
  
  <pre><code>[AllowAnonymous]
      public ActionResult Index(string sortOrder, string searchString,string currentFilter, int? page)
      {
          if (!Request.IsAuthenticated)
          {
  
              return RedirectToAction("Login", "Account");
  
          }
  //Find all the employees
          var employees = from s in db.Employees
                         select s;
  //Pass employees to the view (All works fine)
  return View(employees.ToPagedList(pageNumber, pageSize));
  }
  </code></pre>
  
  <p>This all is working 100%</p>
  
  <p>My Login code looks like this :</p>
  
  <pre><code> [HttpPost]
      [AllowAnonymous]
      [ValidateAntiForgeryToken]
      public ActionResult Login(User user, string returnUrl)
      {
          var myUser = db.Users.Where(b =&gt; b.UserName == user.UserName).FirstOrDefault();
          if(myUser != null)
          {
              if(myUser.Password==user.Password)
              {
                  //These session values are just for demo purpose to show the user details on master page
                  //Session["User"] = user;
                  ICollection&lt;UserAccessLevel&gt; levels = db.UserAccessLevels.Where(b =&gt; b.UserId == myUser.UserId).ToList();
                  //Session["levels"] = levels;
  
                  //Let us now set the authentication cookie so that we can use that later.
                  FormsAuthentication.SetAuthCookie(user.UserName, false);
  
                  return RedirectToAction("Index","Employee");
              }
          }
          ViewBag.Message = "Invalid User name or Password.";
          return View(user);
      }
  </code></pre>
  
  <p>I also have the following code in the Global.asax file :</p>
  
  <pre><code> protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
      {
          if (FormsAuthentication.CookiesSupported == true)
          {
              if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
              {
                  try
                  {
                      //let us take out the username now                
                      string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                      string roles = string.Empty;
  
                      using (TrainingContext entities = new TrainingContext())
                      {
                          User user = entities.Users.SingleOrDefault(u =&gt; u.UserName == username);
  
                          roles = "admin";//user.Roles;
                      }
                      //Let us set the Pricipal with our user specific details
                      e.User = new System.Security.Principal.GenericPrincipal(
                         new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
                  }
                  catch (Exception)
                  {
                      //somehting went wrong
                  }
              }
          }
      }
  </code></pre>
  
  <p>When I log in my FormsAuthentication_OnAuthenticate executes and everything looks good. My User is set and my roles in the session is also there...</p>
  
  <p>But when I click on the details of my Employee/Index screen it takes me back to the login screen (I expect it to take me to the details of the employee I clicked because I am logged in and I am setup as an admin role)</p>
  
  <p>Please can you assist me to try and get to the problem. I sat for more than 18 hours already trying to figure this out. </p>
  
  <p>I already looked at these solutions and as you can see most of my code comes from there...
  codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF
  codeproject.com/Articles/342061/Understanding-ASP-NET-Roles-and-Membership-A-Begin
  codeproject.com/Articles/408306/Understanding-and-Implementing-ASP-NET-Custom-Form</p>
  
  <p>in case you need more detail about my code you can also download it from GitHub
  <a href="https://github.com/Ruandv/Training/tree/FormsAuthentication" rel="nofollow">https://github.com/Ruandv/Training/tree/FormsAuthentication</a></p>
  
  <p>I will appreciate your assistance.</p>