Limit access by Controller or by Model?

南笙酒味 提交于 2019-12-04 15:49:55

Although there could be exceptions to this, access control should be done by the controller.

The models should not be holding any procedural functionality, just business logic. Business logic on itself should not need to be access-controlled.

The controller, which contains actions that 'interact' with this business logic and models, should be the place to have access control in. Some frameworks already provide functionality for access control, that can evaluate the state of an application to decide whether a certain action can be performed.

Example: On a web application, Model "Person" holds "persons", and has a function 'createNew (name)' Controller 'PersonsController' has action 'addNewPerson()', which reads the name from HTTP Post and calls the function mentioned above. It also has an access rule that says that action 'addNewPerson' may not be called if the current state of the application indicates that the user requesting the action is not logged in.

User authorization is a strictly session-based concern, so that is best dealt with in the Controller. Making Models session-aware is possible, but is a violation of concerns and definitely not easy in my experience. You also have to worry about the requests being thread-safe depending on your technology stack.

The way Rails apps typically deal with this is by adding authorization functions to the Controller base class, and letting you define a before_filter to either the entire controller or the specific actions which need to authorize the request.

Typically, I would expect your users to have roles that have access to a a range of functions they can perform on a range of models. This access/no access lookup would be made in the controller.

In the current project I'm working on, we limit access at the controller level via action filters.

The action filters can be defined for a specific action if we want to limit access just to that specifically (ex. a certain page the user shouldn't see) or defined on the controller if that entire area is limited.

The action filter itself is pretty simple, and uses the HttpContext to find the user's identity, but in our case we're using form's authentication so this may differ based on what type of authentication mechanism you're using.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!