【问题标题】:Form Authentication : Roles (MVC 4) C#表单身份验证:角色 (MVC 4) C#
【发布时间】:2013-12-26 23:47:37
【问题描述】:

我正在尝试在我的应用程序中实现表单身份验证。我查看了各种示例并查看了此论坛和 ASP.net MVC 中提供的示例和问题,但我无法让它工作。

我设法对我的用户进行身份验证,但角色似乎不起作用:-(

我的 Web.Config 设置如下:

<authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880" /> </authentication>

在我的控制器中,我将索引页面设置为 AllowAnonymous,然后在用户通过身份验证时签入。如果没有,则重定向到登录页面..

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

这一切都在工作 100%

我的登录代码如下所示:

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(User user, string returnUrl)
    {
        var myUser = db.Users.Where(b => 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<UserAccessLevel> levels = db.UserAccessLevels.Where(b => 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);
    }

我在 Global.asax 文件中也有以下代码:

 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 => 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
                }
            }
        }
    }

当我登录我的 FormsAuthentication_OnAuthenticate 时,一切看起来都很好。我的用户已设置,我在会话中的角色也在那里...

但是,当我单击“员工/索引”屏幕的详细信息时,它会将我带回登录屏幕(我希望它会带我到我单击的员工的详细信息,因为我已登录并且我被设置为管理员角色)

请您帮助我解决问题。我已经坐了超过 18 个小时试图弄清楚这一点。

我已经看过这些解决方案,您可以看到我的大部分代码都来自那里... 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

如果您需要有关我的代码的更多详细信息,也可以从 GitHub 下载 https://github.com/Ruandv/Training/tree/FormsAuthentication

感谢您的帮助。

【问题讨论】:

  • 你能发布你在 Authorize 属性类中的内容吗?
  • 我没有自定义 Authorize 属性类。我正在使用标准的。

标签: asp.net-mvc-4 asp.net-membership forms-authentication roles


【解决方案1】:

如果您访问您的数据库并查找为用户分配角色的表(可能由SimpleMembership 生成?),您的用户是否具有“管理员”角色?

看起来您只是在FormsAuthentication_OnAuthenticate 方法中分配角色,而没有在数据库中实际设置它。

// Your method (...)
User user = entities.Users.SingleOrDefault(u => u.UserName == username);
roles = "admin";//user.Roles;

而且,虽然我不完全确定,[Authorize(Roles = "admin")] 可能正在使用您的角色提供程序并检查用户是否在数据库中拥有/不拥有该角色。

【讨论】:

  • 感谢您指出数据库部分。我在数据库中添加了角色,一切正常。所有的时间都浪费了。
猜你喜欢
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
  • 2010-11-25
  • 1970-01-01
  • 2018-05-27
  • 2016-10-27
  • 2013-01-05
  • 1970-01-01
相关资源
最近更新 更多