Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel protect form hidden fields and url

I have an edit made with blade to edit a resource, like this:

{{Form::model( $post ,['action'=> ['PostController@update', 'id' => $post->id], 'method' => 'post'])}}

Which generates a form with action

http://example.com/posts/edit/123

And my fields, having text and hidden inputs

Seeing this url, it's very easy for a bad-intentioned user to update other posts.

How can I protect the route to make it fail if the id is manipulated with the inspector? Is there any built-in wat to tokenize the id to make sure it matches? Can this also de applied to all the hidden inputs?

Thanks

EDIT:

An example on my hidden fields usage: My posts are generally questions and answers, when an user tries to add an answer to a question, I set question_id as a hidden field, and I want to check it is not manipulated.

like image 612
SkarXa Avatar asked Apr 08 '15 12:04

SkarXa


2 Answers

Limonte's answer is correct to secure the ability to edit other peoples posts - and you should always do that. To answer the second half of your question:

I set question_id as a hidden field, and I want to check it is not manipulated.

The problem is that you can never trust the data supplied by a client to your system. You must always assume it has been tampered with.

One option to help minimize the risk is you can use the encryption service by Laravel to do this:

{{ Form::hidden('question_id', Crypt::encrypt($question_id)) }}

Then in your controller

$question_id = Crypt::decrypt(Input::get('question_id'));

Just make sure you've set a random application encryption key in your app.php config file

like image 172
Laurence Avatar answered Nov 09 '22 12:11

Laurence


To protect route you should check permission in PostController@update.

In the method beginning check if user can edit given post:

public function update($postId)
{
    $post = Post::findOrFail($postId);

    if ($post->user_id !== Auth::id()) {
        abort(403, 'Unauthorized action.');
    }

    // validate, update record, etc.
}
like image 32
Limon Monte Avatar answered Nov 09 '22 10:11

Limon Monte