0

I am currently using the AspNetWindowsTokenRoleProvider to provide the authorization for my controller actions:

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

Rather than hard code the role name ("domain\group"), or use a constant. I would like to be to replace it with a call to a settings class which will get it from a database or file.

I figure that either there is a way to do this built into the provider or I need to replace the provider with my own implementation. I have drawn a blank googling, so I guess I am not asking the right questions!

Could anyone please point me in the right direction to achieve this. Thanks

Lobsterpants
  • 1,188
  • 2
  • 13
  • 33
  • MVC Attributes are quite extensible. In this particular case, you'd probably write your own attribute, either from scratch or by inheriting the existing one, and customize the logic of role retrieval. – Wiktor Zychla Mar 03 '15 at 11:37
  • Thanks Wiktor, creating my own attribute turned out not to be what I wanted but it started me thinking along the right lines. – Lobsterpants Mar 03 '15 at 16:26

1 Answers1

1

I kind of worked it out, so here is the solution in case anyone wants to do the same thing.

  1. Create a new class inheriting from 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;
    }
}

Then change the web.config to use the new class:

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

Then I can use the settings key in the code:

 [Authorize(Roles = MysADProvider.Admins)]
    public ActionResult Index()
    {}
Lobsterpants
  • 1,188
  • 2
  • 13
  • 33