Best practice for security? - Controller vs Model based?

Hi there,

I’m looking for feedback on an efficient way of implementing security for a web based app. The most common method I’ve seen is to implement security on each controller and/or action; there are lots of modules in GitHub that make this really easy.

The issue I see with this is that it ignores a lot of business rules that may apply to data, and the alternative I’ve seen is to use model based security (canRead() and canWrite() methods on each model) which will evaluate conditions to determine whether you can create/read/update/delete a model. This works particularly well when you have a REST API and a web interface as the security/business rules are applied consistently irrespective of how you access the model.

Looking at the Yii2 security docs I notice you could use permissions. A ‘hybrid’ approach be to check for permissions on controllers (ie. a ‘create-post’ on both a web interface and REST API), as well as rule on the create post that checks the model to determine whether that action is allowed?

I’m looking for feedback as to how other people have built a scale-able and low maintenance security model?



The model depends very much on the application. For role-based security use RBAC. For simpler checks use other filters. Ownership checks — add a user ID to the query selecting a record.