How to edit the roles in run time in webconfig

Jul 16, 2013 at 4:44 PM
That's a great extension and working beautifully but i need to be able to maintain the permissions on the controllers/actions dynamically through a page in my application, is that doable?
Coordinator
Jul 18, 2013 at 3:10 AM
Edited Jul 18, 2013 at 3:17 AM
Yes, it is possible. You need to override AuthorizationProvider like below and implement the logic to get the permissions from your database. Once they are retrieved they will be cached, so they will not be loaded every request (provided that your custom implementation is a static instance and not per request):
public class CustomAuthorizationProvider : AuthorizationProvider
{
  protected override GlobalAuthorizationDescriptor LoadGlobalAuthorizationDescriptor()
  {
    ... Load global permissions here...
  }
  protected override AreaAuthorizationDescriptor LoadAreaAuthorizationDescriptor(string areaName)
  {
    ... Load area permissions here...
  }
  protected override ControllerAuthorizationDescriptor LoadControllerAuthorizationDescriptor(string controllerName, string areaName)
  {
    ... Load controller permissions here...
  }
  protected override ActionAuthorizationDescriptor LoadActionAuthorizationDescriptor(string controllerName, string actionName, string areaName)
  {
    ... Load action permissions here...
  }
}
Then have ResolveDependenciesUsing() configured to return your implementation of the AuthorizationProvider like below, or using your DI container:
AuthorizationProvider.ResolveDependenciesUsing((type) => {
  if (serviceType == typeof(IAuthorizationProvider))
  {
    // This will load your custom provider instead of the default one based on web.config
    // Note that resolving your type this way will get a new instance each request, so caching will not be as effective.
    // Provided that you are not storing any request specific state in your implementation it is best to use a static instance of your provider
    return new CustomAuthorizationProvider();
  }
});