ASP.NET MVC如何创建自定义角色提供程序

12

由于我相对较新于ASP MVC,我不确定哪一个更适合我的需求。我使用Windows身份验证构建了一个内部网站,并且能够使用Active Directory角色来保护控制器和操作,例如:

[Authorize(Roles="Administrators")]
[Authorize(Users="DOMAIN\User")]
public ActionResult SecureArea()
{
    ViewBag.Message = "This is a secure area.";
    return View();
}

我需要定义自己的安全角色,独立于AD角色。期望的功能是,根据应用程序数据库中与其配置文件相关联的一个或多个角色,授予已验证用户对特定操作的访问权限,例如:“管理者”,“用户”,“访客”,“分析师”,“开发人员”等。

如何创建自定义角色提供程序和/或自定义授权属性?


我认为询问最佳/最干净的方法会得到很多不同的答案。一个好的方法是自上而下。也就是在控制器级别进行授权,然后根据需要在方法/操作级别进行限制。您还可以实现一个区域基本控制器,然后该区域中的每个控制器都实现基本控制器。如果未达到授权级别,区域基本控制器可以重定向到适当的页面。 - Ben Sampica
2个回答

42

我的解决方案是创建一个自定义角色提供程序。以下是我采取的步骤,以防其他人以后需要帮助:

创建自定义用户和角色类

using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Security.Models.Security
{
    public class AppRole : IdentityRole
    {
    }
}

using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Security.Models.Security
{
    public class AppUser : IdentityUser
    {
    }
}

设置数据库上下文

using Microsoft.AspNet.Identity.EntityFramework;
using Security.Models.Security;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace Security.Models.DAL
{
    public class UserContext : IdentityDbContext<AppUser>
    {
        public UserContext() : base("UserContext")
        {
            Database.SetInitializer<UserContext>(new CreateDatabaseIfNotExists<UserContext>());
        }
    }
}

创建您的角色提供程序并实现以下方法

using Security.Models.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace Security.Models.Security
{
    public class AppRoleProvider : RoleProvider
    {
        public override string[] GetAllRoles()
        {
            using (var userContext = new UserContext())
            {
                return userContext.Roles.Select(r => r.Name).ToArray();
            }
        }

        public override string[] GetRolesForUser(string username)
        {
            using (var userContext = new UserContext())
            {
                var user = userContext.Users.SingleOrDefault(u => u.UserName == username);
                var userRoles = userContext.Roles.Select(r => r.Name);

                if (user == null)
                    return new string[] { };
                return user.Roles == null ? new string[] { } :
                    userRoles.ToArray();
            }
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            using (var userContext = new UserContext())
            {
                var user = userContext.Users.SingleOrDefault(u => u.UserName == username);
                var userRoles = userContext.Roles.Select(r => r.Name);

                if (user == null)
                    return false;
                return user.Roles != null &&
                    userRoles.Any(r => r == roleName);
            }
        }
    }
}

编辑web.config文件以设置数据库连接和角色提供程序引用

<connectionStrings>
    <add name="UserContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UserContext.mdf;Initial Catalog=UserContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

<system.web>
    ...
    <authentication mode="Windows" />        
    <roleManager enabled="true" defaultProvider="AppRoleProvider">
      <providers>
        <clear/>
        <add name="AppRoleProvider" type="Security.Models.Security.AppRoleProvider" connectionStringName = "UserContext"/>
      </providers>
      ...
    </roleManager>
  </system.web>

在包管理器控制台中启用迁移

enable-migrations
在新创建的 Configurations.cs 中设置用户/角色存储和管理器,并配置用户管理器验证程序以接受 '\' 字符。
namespace Security.Migrations
{
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Security.Models.Security;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<Security.Models.DAL.UserContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            ContextKey = "Security.Models.DAL.UserContext";
        }

        protected override void Seed(Security.Models.DAL.UserContext db)
        {
            // Set up the role store and the role manager
            var roleStore = new RoleStore<AppRole>(db);
            var roleManager = new RoleManager<AppRole>(roleStore);

            // Set up the user store and the user mananger
            var userStore = new UserStore<AppUser>(db);
            var userManager = new UserManager<AppUser>(userStore);

            // Ensure that the user manager is able to accept special characters for userNames (e.g. '\' in the 'DOMAIN\username')            
            userManager.UserValidator = new UserValidator<AppUser>(userManager) { AllowOnlyAlphanumericUserNames = false };

            // Seed the database with the administrator role if it does not already exist
            if (!db.Roles.Any(r => r.Name == "Administrator"))
            {
                var role = new AppRole { Name = "Administrator" };
                roleManager.Create(role);
            }

            // Seed the database with the administrator user if it does not already exist
            if (!db.Users.Any(u => u.UserName == @"DOMAIN\admin"))
            {
                var user = new AppUser { UserName = @"DOMAIN\admin" };
                userManager.Create(user);
                // Assign the administrator role to this user
                userManager.AddToRole(user.Id, "Administrator");
            }
        }
    }
}
在包管理器控制台中,请确保已创建和填充数据库。
update-database

创建自定义授权属性,在失败时重定向到拒绝访问页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Security.Models.Security
{
    public class AccessDeniedAuthorizationAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);

            if(filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectResult("~/Home/AccessDenied");
            }
        }
    }
}
完成了!现在您可以创建一个访问被拒绝的页面(在此例中为~/Home/AccessDenied),并将属性应用于任何操作,例如:
using Security.Models.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Security.Controllers
{
    public class HomeController : Controller
    {
         ...    

        [AccessDeniedAuthorizationAttribute(Roles = "Administrator")]
        public ActionResult SecureArea()
        {
            return View();
        }

        public ActionResult AccessDenied()
        {
            return View();
        }

        ...
    }
}

希望这篇文章能够帮助未来的某个人。祝好运!


0

这篇帖子帮了我很多。

但是

var userRoles = userContext.Roles.Select(r => r.Name);

不能获取当前用户的角色,而是获取所有角色。

我一直在想为什么每个人都能访问,哈哈。


1
这是对原帖的回答,还是一般性的评论? - SiKing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接