Friday, April 14, 2017

Laravel nested resource security

On a project I'm currently working on, I have nested resources like this

route()->resources('user', 'UserController');
route()->resources('user.place', 'PostController');
route()->resources('user.place.picture', 'PictureController');

Everything is working fine, I pass along each time the id of the user, etc...

The trick is when you come to a place, if this is yours I show buttons to edit and make some actions. So I check if the $place.user_id == $user.id to show the buttons.

After playing a little, since to access for example a place of mine I have the following URL : /user/1/place/2 for the Place.show.

I'm the owner so the buttons show and I can modify but if another user (user_id 2 for example) use the same URL to see my place he can't modify anything but can see the place.

What I found is that if this user use the same URL but change the user_id to mine then he can have full access to the place and modify it.

So to protect against this I added another condition : Auth::user()->id == $user->id

What I'm wondering is if there was a solution to prevent this behavior, because if I have to protect every method of a nested resources it's becoming long and ugly to implement. Also when I come to the next level user.place.picture. I think I need to add another layer of security each time I go down. $picture->place_id == $place->id and so on.

So, when I print a link so the user can click on it with the right user, place, picture ID then nothing prevent or check if one id has been modified. If the last one is modified, there's no problem since it'll retrieve another element. But if we modify the parent's id it can be dangerous, especially when I grant some access along the way.

Hope there's a simple solution that I missed !



via dib258

Advertisement