【问题标题】:MVC4 role based controller's action accessMVC4 基于角色的控制器的动作访问
【发布时间】:2013-06-10 09:08:50
【问题描述】:

我想建立一个注册系统,在添加用户时,您可以选择可以赋予他/她的角色类型。并且根据他/她的角色,将决定是否可以访问控制器中的某些操作。

例如,假设有两个角色,管理员和开发人员。 并且具有如下所述的内容只会允许具有管理员角色的用户访问以下操作。

[Authorize(Roles = "admin"]
public ActionResult CreateUser()
{
   return View();
}

据我所知,我必须实现我的自定义 RoleProviderIPrincipal? 我试图找到一些例子,但并没有完全得到我正在寻找的东西。 这是我的 RegisterModel 目前的样子

public class RegisterModel
    {
        [Key]
        public Guid Id;
        [Required]
        [Display(Name="First Name")]
        public string FirstName {get; set;}

        [Required]
        [Display(Name="Last Name")]
        public string LastName {get; set;}

        [Required]
        [Display(Name="Email Id")]
        [DataType(DataType.EmailAddress)]
        public string EmailId {get; set;}

        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required]
        [Display(Name = "Password")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Required]
        [Display(Name = "Confirm Password")]
        [DataType(DataType.Password)]
        public string ConfirmPassword { get; set; }

       [Required]
       [Display(Name = "Role")]
       public UserRole Role { get; set; }

    }



  public class UserRole
    {
        [Key]
        public int RoleId { get; set; }

        public string RoleName { get; set; }
    }

问题是我希望在添加用户并使用自定义授权属性时确定角色。任何人都知道可以解决我的问题的文章或博客?或者有什么建议,怎么做?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 authorization roleprovider


    【解决方案1】:

    最近我实现了角色授权没有使用会员提供者。认为这可能会对您有所帮助。我有一个包含用户名、密码和角色的数据库表,我需要根据数据库检查角色。

    下面是我的自定义 RoleFilter 类。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MvcApplicationrazor.Models.ActionFilters
    {
        public class RoleFilter : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (GetCurrentUserRole() != "Admin")// Check the Role Against the database Value
                {
                    filterContext.Result = new RedirectResult("~/Redirect/NoPermission");
                    return;
                }
            }
        }
    }
    

    控制器:

    [RoleFilter]//Check the Role, if not allowed redirect to NoPermission view
    public ActionResult Index()
    {
       return View();
    }
    

    【讨论】:

    • 谢谢,这在某种程度上很有帮助,我现在会接受它作为答案:D
    【解决方案2】:

    MVC 4 使用来自 WebMatrix 的一些帮助类来实现安全性和成员资格。你可以在这里阅读一个非常好的教程: http://www.asp.net/web-pages/tutorials/security/16-adding-security-and-membership

    如果您没有任何特殊要求,通常不值得自己实现 Role Provider。

    祝你好运!

    编辑:快速教程

    以下基于名为“UserProfile”的模型类,对应的表名称相同。此表有一个名为“UserId”的列用于 id,一个名为“UserName”的列用于登录。当然,它可以包含您需要的所有信息,但这些是 WebSecurity 初始化数据库所需的唯一信息。

    第 1 步:web.config。把它放在system.web 部分。这指示 ASP.NET 使用两个 Simple 提供程序来表示角色和成员资格:

     <roleManager enabled="true" defaultProvider="simple">
         <providers>
             <clear/>
             <add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
         </providers>
     </roleManager>
     <membership defaultProvider="simple">
         <providers>
             <clear/>
             <add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData"/>
         </providers>
     </membership>
    

    第 2 步:Application_Start。为您的数据库添加角色和成员表的初始化:

    protected void Application_Start()
    {
         try
         {
             // Initializes the DB, using the "DefaultConnection" connection string from the web.config,
             // the "UserProfile" table, the "UserId" as the column for the ID,
             // the "UserName" as the column for usernames and will create the tables if they don't exists.
             // Check the docs for this. Basically the table you specify
             // is a table that already exists and where you already save your user information.
             // WebSecurity will simply link this to its own security info.
             if (!WebSecurity.Initialized)
                 WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
         }
         catch (Exception ex)
         {
             throw new InvalidOperationException("Cannot init ASP.NET Simple Membership database", ex);
         }        
    }
    

    InitializeDatabaseConnection 第一次触发时,会创建 4 个表:

    webpages_Membership
    webpages_OAuthMembership
    webpages_Roles
    webpages_UsersInRoles
    

    第 3 步:您现在可以使用 Authorize 属性:

        [Authorize(Roles="Admin")]
    

    此外,您现在将有很多方法来创建和登录您的用户:

    WebSecurity.CreateUserAndAccount(model.UserName, model.Password); // to create users. You can also pass extra properties as anonymous objects
    
    WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe); // for logins
    
    WebSecurity.Logout();
    
    WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
    
    // and so on...
    

    我发现这种方法比滚动您自己的实现更灵活(也更快)。

    【讨论】:

    • 所以如果我只有我提到的两种类型的用户,并根据这些类型决定是否允许用户访问某些操作。不值得创建自定义角色提供者?
    • 绝对不是。该链接提供了一个很好的教程来放置所有东西。我会在有时间的时候编辑答案并添加我过去所做的事情。
    • 你去吧,我在答案中添加了更多信息......它有点浓缩但我希望它有所帮助:)
    猜你喜欢
    • 2010-09-11
    • 2020-06-22
    • 2013-08-28
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多