1

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

例如,假设有两个角色,管理员和开发人员。并且像下面提到的那样只允许具有管理员角色的用户访问以下操作。

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

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

4

2 回答 2

6

最近我在不使用 Membership provider的情况下实现了角色授权。认为这可能会对您有所帮助。我有一个包含用户名、密码和角色的数据库表,我需要根据数据库检查角色。

下面是我的自定义 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();
}
于 2013-06-10T12:32:03.023 回答
1

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

如果您没有任何特殊要求,那么提出自己的角色提供者实现通常是不值得的。

祝你好运!

编辑:快速教程

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

第 1 步:web.config。把它放在这个system.web部分。这指示 ASP.NET 使用SimpleRole 和 Membership 的两个提供程序:

 <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...

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

于 2013-06-10T10:57:48.037 回答