views:

51

answers:

3

Is it possible to have security in ASP.NET MVC configurable at runtime? For example, if I have a controller that has been marked as

[Authorize(Roles="Admin")]

Is there a way to add/remove roles at runtime? Or, do you have to change it in code and re-compile?

+1  A: 

Yes, you will have to provide your own IPrincipal implementation that will allow for that. All the Authorize method does is to call the User.IsInRole("Admin") method.

Javier Lozano
A: 

If you want to build something custom, you can create your own custom authorization scheme.

Take a look at AuthorizeAttribute - here's an article that has a simple comparison of the two mechanisms.

chris
A: 

I suppose you need this kind of functionality because you are adding new roles at runtime and you are trying to connect them to the functionality your application provides. If I am correct in my thinking, you must also have a list of functionality stored somewhere (in a DB or registry or config file). Given all that, I believe you are putting users in roles and attach roles to the functionality and you store those relations in datastore.

So given all that, you may want to come up with a custom attribute (decorator) for your actions that will say somethings like

[AuthorizeUsers]

instead of

[Authorize(Roles="Admin")] 

so emitting any reference to any kind of role and rather go into the datastore and enumerate all of the relations and check all the roles/users and their, should I say, permissions. And then you would either deny their request (e.g. return them to another View that they do have access for) or give them an option to opt for permissions (something like SharePoint does when you access parts of page that you don't have permissions for).

For the exact code sample on how to author custom Authorize, go to ASP.NET MVC source code - the System.Web.Mvc namespace.

HTH

mare