Search code examples
asp.net-mvcform-authentication

Form based Authentication based on Role in MVC


I want to create Authentication based on Role using Form Authentication. Please Find my controller code below:-

[HttpPost]
    public ActionResult Login(tblUser user)
    {
        DataClasses1DataContext dbcontext = new DataClasses1DataContext();
        List<Mvc4API.linqtosql.tblUser> lstuser = dbcontext.tblUsers.ToList();
        string message = string.Empty;
        bool userlogin = lstuser.Exists(x => x.UserName == user.UserName && x.Password == user.Password);

        if (userlogin)
        {
            FormsAuthentication.SetAuthCookie(user.UserName, true);
            //role = "BB";
            string Role = GetRoles(user.UserName);
            return RedirectToAction("InsertProduct", "Product");
        }
        else
        {
            message = "Invalid User";
        }
        ViewBag.Message = message;
        return View(user);
    }

    private string GetRoles(string UserName)
    {
        UserEntities userEntities = new Mvc4API.UserEntities();
        List<tblUser> lstuser = userEntities.tblUsers.ToList();
        List<tblRole> lstrole = userEntities.tblRoles.ToList();
        var role = from u in lstuser
                   join r in lstrole on u.RoleId equals r.Id
                   where u.UserName == UserName
                   select r.RoleName.ToString();
        string roletype = "";
        foreach (var item in role)
        {
            roletype = item.ToString();
        }


        return roletype;
    }

While redirecting my code as follows:-

      [Authorize(Users="B,Test")] // This is working
    //[Authorize(Roles="Admin")] This is not working
    public ActionResult InsertProduct()
    {
        return View();
    }

Authentication based on Users is working but when I do it on Roles it is not working.

Please tell the changes I have to make in my code so that it can work.

Thanks,

Rahul


Solution

  • Found an answer, Just added the following code in Global.asax.cs

    protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs e)
        {
            string rolename = string.Empty;
            if (FormsAuthentication.CookiesSupported == true)
            {
                if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
                {
                    try
                    {          
                        string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
                        string roles = string.Empty;
    
                        using (UserEntities entities = new UserEntities())
                        {
                            var roleid = entities.tblUsers.Where(u => u.UserName == username).Select(u => u.RoleId);
    
                            int role = 0;
                            foreach (int i in roleid)
                            {
                                role = i;
                            }
    
                            rolename = entities.tblRoles.Where(r => r.Id == role).Select(r=>r.RoleName).First().ToString();
                        }
                        e.User = new System.Security.Principal.GenericPrincipal(//, rolename.Split(';')); for more than one role
                           new System.Security.Principal.GenericIdentity(username, "Forms"),new String[] { rolename});
                    }
                    catch (Exception)
                    {
                        //somehting went wrong
                    }
                }
            }
        }