barbod
barbod

Reputation: 1

how to asp.net mvc permission by action?

I need to create a custom authorization and authentication user security by looping on area/controller/action list (that dynamically i saved in Database) and action that assign to user by admin , is it good solution? (i need dynamic authorization and authentication Instead of authorization tag on action. how can i write it?)

Upvotes: 0

Views: 771

Answers (2)

NightOwl888
NightOwl888

Reputation: 56909

You could potentially inherit AuthorizeAttribute and override the IsAuthorized method in order to implement your custom logic. You can then register your custom AuthorizeAttribute as a global filter site-wide in order to achieve this behavior.

global.asax:

protected void Application_Start()
{
    ....
    RegsterFilterProviders(FilterProviders.Providers);
}

private void RegsterFilterProviders(FilterProviderCollection providers)
{
    providers.Add(new CustomAuthorizeAttribute());
}

However, if you go this route, you should try using some kind of caching mechanism (such as session state) to load all of your settings at once so you are not continually making database calls to retrieve your security settings.

Do note that the standard way of achieving the same effect is to use a set number of roles, hard coding the AuthorizeAttribute with the allowed roles on each controller and/or action, and then using the database to dynamically assign users to roles. You could make these roles as broad or granular as needed to fit your use case. This would be much more efficient and maintainable than what you are trying to achieve.

Upvotes: 0

Chris Pratt
Chris Pratt

Reputation: 239460

One of the main selling points of MVC architecture is decoupling the interface, be it views or even URLs, from the underlying architecture of controllers, actions, etc. What you're proposing isn't horrible, but it's also not ideal, either. What if you need to add a new action? What if you need to remove an action. What if you need to move the duties of one action into a different action. All of these things fundamentally alter your permissions, requiring a lot of maintenance.

This is a job that is really better suited to roles, and really that's what roles exist for. If you want to control who can edit a widget, you don't give them explicit access to WidgetArea > WidgetController > EditWidget; you give them a role of CanEditWidget. Then, any action that involves editing widgets can be protected with that role. This not only allows you to continue using just the Authorize attribute and avoi custom code, but you also get portability. If the underlying architecture changes, your permission system is unaffected.

Upvotes: 1

Related Questions