基于MVC中角色的基于表单的认证

时间:2018-02-13 10:03:09

标签: asp.net-mvc form-authentication

我想使用表单身份验证基于角色创建身份验证。请在下面找到我的控制器代码: -

[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;
    }

重定向我的代码时如下: -

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

基于用户的身份验证正在运行,但是当我在Roles上执行此操作时,它无效。

请告诉我必须在我的代码中进行的更改,以便它可以正常工作。

谢谢,

的Rahul

1 个答案:

答案 0 :(得分:0)

找到答案,刚刚在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
                }
            }
        }
    }
相关问题