Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is auth typically in the Controller in MVC?

I've been doing a lot of tutorials for different MVC frameworks, and it seems very typical for Authorization to take place in the Controller. Why?

My thought is the Controller should only be used to orchestrate Model actions, to handle redirection and to handle error events. These are the things that are dependent on the specific request. Putting Authorization in the Controller seems like you're going to have to duplicate the authorization whenever you're using the same Model action in different Controller actions or different Controllers. If Auth is in the Model, you have consistent requirements for carrying out an action or state change on the data.

I've been googling and looking at other questions such as Should authorization be part of the model or controller? but I don't really see why it's the accepted convention.

Is there a specific reason I'm missing for putting Authorization in the controller over the model?

To sum up points in the comments:

  • Controllers are responsible for altering the state of the model layer and the current view. Nothing else.
  • Authorization belongs where an action is being carried out, if you're following a strict MVC pattern this would most likely be the model, and a Controller is certainly not responsible for authorizing the use of model actions.
  • Cookies should be treated like any other datastore: abstracted and used within the models, not directly by controllers.
  • Authentication and Authorization are separate issues, though they both usually go in the model layer, because they usually involve checks against values in datastores (such as cookies).
like image 384
Charles Avatar asked Oct 18 '13 19:10

Charles


1 Answers

Is there a specific reason I'm missing for putting Authorization in the controller over the model?

Well, the most common reason I can imagine is laziness. I don't mean that morally, it's just far easier to flunge some authorization concept on top into a layer that is more close to the concrete request then to have differentiated access on the model layer. To have authorization with the models is a much higher design.

To add some more practical advice to the answer, I think you should analyse for each program where and for what you would want to introduce authorization. The needs for that can be (extremely) different.

Then only in the next step you should think about which design is most beneficial to introduce authorization and authentication to fulfill these needs.

like image 76
hakre Avatar answered Oct 24 '22 17:10

hakre