【问题标题】:In MVC Authorize filter, From where roles will be picked在 MVC 授权过滤器中,将从何处挑选角色
【发布时间】:2018-07-16 15:19:52
【问题描述】:

我正在学习 MVC。我想知道,从哪里接角色。

        [Authorize(Roles ="admin")]
        public class HomeController : Controller
        {
        // GET: Search
        public ActionResult search()
        {
        return View();     
        }
        }

我们应该在哪里编写授权代码以使家庭控制器仅适用于管理员。

【问题讨论】:

  • 您不必编写任何代码,这是 MVC 内置的,如果您应用该属性就会触发。
  • 但是 mvc 将从哪里选择角色,它将如何知道用户具有管理员角色。
  • 试试这个教程。可能将用户存储在数据库中,然后使用编程功能定义角色。如果您经常使用 MVC,它可以帮助我创建一个独立的应用程序来管理跨应用程序的角色。 code.msdn.microsoft.com/ASPNET-MVC-5-Security-And-44cbdb97
  • 在上面的教程中我们已经定义了角色,但是正如 CodeCaster 提到的我们不必编写任何代码,这是内置在 MVC 中的。但是 MVC 将如何了解以及它将从哪个函数中扮演角色。我们是否必须编写任何 Session 变量来定义角色或类似的东西?请告诉我。

标签: asp.net-mvc model-view-controller action-filter authorize-attribute


【解决方案1】:

假设你没有使用 ASP.NET Core,在控制器中登录时,使用此代码注册登录并附加角色:

  var role = "admin";  // or whatever role you want to use here
  var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddHours(8), false, role);
  var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
  Response.Cookies.Add(cookie);

然后在 Global.asax.cs 中添加:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
  var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
  if (authCookie != null)
  {
    //get the user cookie and get the roles from it and apply them
    var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    var roles = authTicket.UserData.Split(',');    //note that you can use multiple roles with this
    var userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles);
    Context.User = userPrincipal;
  }
}

设置好之后,您的 Authorize 属性将获取用户登录时使用的角色。

【讨论】:

    【解决方案2】:

    角色由 RoleManager(或 RoleProvider)see more herehere 提供。

    例如,您可以使用WindowsTokenRoleProvider 从 Windows 身份验证中提取角色。或者你可以通过继承RoleProvider来滚动你自己的:

    public class MyRoleProvider : RoleProvider
    {}
    

    PS。这是针对 .net 4.x 的,asp.net core 可能有所不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      • 2017-09-16
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2021-09-04
      相关资源
      最近更新 更多