I validate all my forms data in the model layer but I also check where my form was submitted from (HTTP Referrer) and I also send a token with the form to help prevent Cross Site Request Forgeries and my question is where should these checks be done? In the controller or in the model layer?
I was thinking up a few different ways to accomplish this and one was to have some sort of protected method in my AbstractController
for validating the forms source and posted token but then that might break the SRP.
(..) where should these checks be done? In the controller or in the model layer?
Neither.
In my humble opinion, CSRF protection should be handled at the same level as other forms of access control: outside the MVC triad.
If application fails to verify the token, it means that data in Request
instance (or your alternative of it) cannot be trusted, thus it need to be scrapped. I would perform such check before initialization of Controller
and/of View
instance.
Basicly it is wise check your data multiple times with different intentions. I suggest these levels:
1) A pre-front-controller checks the data recieved for integrity. If you miss some token, or got some timeout from the browser etc, you exit immediately. You will not let these requests reach your MVC. Here is where you might want suoshin. The reason is, that the deeper levels might communicate secured data with the browser, even on an error. Imagine someone missed a security token (attack?), and your view returns an error message and sets some cookies. Using these, the attacker might be logged in after any invalid form request.
2) The front controller verifies if the entered may be entered in that form from that user etc. (e.g. if a US-User might enter a Canada Phonenumber) It is ment to give direct feedback in form of "please enter a correct phone number" and so on.
3) The model validates if the data is in a state to be safely saved and returned, e.g. if it has been escaped, has the right length etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With