如何将自定义角色管理器插入AuthorizeAttribute?

时间:2015-06-10 19:27:53

标签: asp.net-mvc asp.net-identity

我有一个我无法更改的旧数据库架构。它有一个带有整数字段的用户表来指定用户级别,其中1是标准用户,5是管理员。我正在编写一个MVC前端,我想使用ASP.NET身份。我已经从研究和样板代码中找到了其他所有东西。我似乎无法弄清楚如何创建自定义角色系统。我意识到它与实现角色管理器和角色存储有关。那没关系,但我如何将其与MVC连接以让AuthorizeAttribute确认我的经理?

我很抱歉,如果这是显而易见的,但我已经完成了我的研究,而且我无法确定它。

2 个答案:

答案 0 :(得分:0)

从您的问题来看,我假设您已经找到了如何创建角色管理器,而您只是错过了实际使用它的配置。如果我的假设是错误的,请告诉我,我将添加有关如何创建CustomRoleManager的说明。

的Web.config

<configuration>
  <system.web>
    <roleManager enabled="true" defaultProvider="CustomRoleProvider">
      <providers>
        <clear/>
        <add name="CustomRoleProvider"
             type="MyNamespace.CustomRoleProvider,
                   MyNamespace, Version=1.0.0.0, Culture=neutral"
             connectionStringName="MyConnectionString"
             enablePasswordRetrieval="false"
             enablePasswordReset="false"
             requiresQuestionAndAnswer="false"
             writeExceptionsToEventLog="false" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

答案 1 :(得分:0)

以下是我使用的RoleProvider,如果有人有相同的琐碎要求。如果您知道此实施不安全的任何原因,请告诉我。我在Web.Config中使用@ Pluc的答案将此提供程序连接到我的应用程序。它运作得非常好。

public class AppRole : IRole<int>
{
    public AppRole(int a_id, string a_name)
    {
        Id = a_id;
        Name = a_name;
    }

    public int Id { get; private set; }
    public string Name { get; set; }
}

public class AppRoleProvider : RoleProvider
{
    private readonly IServiceLocator _container = UnityConfig.GetServiceLocator();
    private ITrainingRepository _repository; // Thin wrapper around my DbContext

    private AppRole[] _roles = new[]
        {
            new AppRole(0, "User"),
            new AppRole(5, "Admin"),
        };

    public AppRoleProvider()
    {
        ApplicationName = "TrainingCenter";

        _repository = _container.GetInstance<ITrainingRepository>();
    }

    public override string ApplicationName { get; set; }

    public override bool IsUserInRole(string username, string roleName)
    {
        var user = _repository.GetUserByUserName(username);
        if (user == null)
            return false;

        var role = _roles.FirstOrDefault(i => i.Name.Equals(roleName, StringComparison.OrdinalIgnoreCase));

        if (role == null)
            return false;

        if (user.UserLevel >= role.Id)
            return true;

        return false;
    }

    public override string[] GetRolesForUser(string username)
    {
        var user = _repository.GetUserByUserName(username);
        if (user == null)
            return new string[] {};

        return _roles.Where(i => i.Id <= user.UserLevel).Select(i => i.Name).ToArray();
    }

    public override void CreateRole(string roleName)
    {
        // Does not create.
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        // Does not delete.
        return false;
    }

    public override bool RoleExists(string roleName)
    {
        return _roles.Any(i => i.Name.Equals(roleName, StringComparison.OrdinalIgnoreCase));
    }

    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        // Does not add user to role.
    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        // Does not remove users from roles.
    }

    public override string[] GetUsersInRole(string roleName)
    {
        // Does not get users in role.
        return new string[] {};
    }

    public override string[] GetAllRoles()
    {
        return _roles.Select(i => i.Name).ToArray();
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        // Does not find users in role.
        return new string[] { };
    }

}