Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to validate a forms referrer and token in a MVC application?

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.

like image 967
ibanore Avatar asked Jun 04 '13 17:06

ibanore


2 Answers

(..) 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.

like image 124
tereško Avatar answered Nov 15 '22 03:11

tereško


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.

like image 26
Zsolt Szilagyi Avatar answered Nov 15 '22 04:11

Zsolt Szilagyi