我目前正在使用AspNetWindowsTokenRoleProvider为我的控制器操作提供授权:
[Authorize(Roles = "domain\\group")]
public ActionResult Index()
{
code.....
}
而不是硬编码角色名称(" domain \ group"),或使用常量。我想通过调用一个设置类来替换它,它将从数据库或文件中获取它。
我认为有一种方法可以在提供程序中构建这个或者我需要用我自己的实现替换提供程序。 我画了一个空白的谷歌搜索,所以我想我不是在问正确的问题!
有谁能请我指出正确的方向来实现这一目标。 感谢
答案 0 :(得分:1)
我有点努力,所以这里有解决方案以防任何人想要做同样的事情。
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()
{}