【问题标题】:Authorise attribute using active directory role provider MVC4使用活动目录角色提供程序 MVC4 授权属性
【发布时间】:2015-03-03 10:54:45
【问题描述】:

我目前正在使用 AspNetWindowsTokenRoleProvider 为我的控制器操作提供授权:

[Authorize(Roles = "domain\\group")]
public ActionResult Index()
{
code.....
}

而不是硬编码角色名称(“域\组”),或者使用常量。我想将其替换为对设置类的调用,该类将从数据库或文件中获取它。

我认为要么有一种方法可以在提供程序中内置,要么我需要用我自己的实现替换提供程序。 我画了一个空白的谷歌搜索,所以我想我没有问正确的问题!

谁能指出我正确的方向来实现这一目标。 谢谢

【问题讨论】:

  • MVC 属性是相当可扩展的。在这种特殊情况下,您可能会从头开始或通过继承现有属性来编写自己的属性,并自定义角色检索的逻辑。
  • 感谢 Wiktor,创建我自己的属性结果不是我想要的,但它让我开始思考正确的路线。

标签: asp.net-mvc-4 active-directory web-config authorization roleprovider


【解决方案1】:

我已经解决了,所以如果有人想做同样的事情,这里有一个解决方案。

  1. 创建一个继承自 WindowsTokenRoleProvider 的新类
   public class MyADProvider : WindowsTokenRoleProvider
    {
        //settings key
        public const string Users = "Authorisation.AdGRoup.Users";
        public const string Admins = "Authorisation.AdGRoup.Admins";

    private ISettingsRepository settingsRepository;


    public override string[] GetRolesForUser(string username)
    {
        // settings repository reads from settings file or DB
        // actual implementation is up to you
        this.settingsRepository = new SettingsRepository();

        // get all the AD roles the user is in 
        var roles = base.GetRolesForUser(username);

        List<string> returnedRoles = new List<string>
                        {
                            this.GetADRole(roles, Admins), 
                            this.GetADRole(roles, Users)
                        };

        return returnedRoles.ToArray();
    }

    private string GetADRole(string[] usersAdRoles, string roleSettingName)
    {
//Get the actual name of the AD group we want from the settings
        var settingName = this.settingsRepository.GetSetting(roleSettingName);

        return usersAdRoles.Contains(settingName) ? roleSettingName : string.Empty;
    }
}

然后更改 web.config 以使用新类:

  <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
  <providers>
    <clear />
    <add name="AspNetWindowsTokenRoleProvider" type="MyADProvider" applicationName="/" />
  </providers>
</roleManager>

然后我可以使用代码中的设置键:

 [Authorize(Roles = MysADProvider.Admins)]
    public ActionResult Index()
    {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多