Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5/ Form security (require clarification)

Not entirely confident I have understood security in Laravel forms enough. For example, if a form contains <input type="hidden" name="user_id"> then obviously a hacker could change the value before submitting an update. While I have looked here at CSRF, I've not fully understood if this is enough protection?

E.g. Taking the above, if I go to a site and open a form to edit a record I'm permitted to view but not change, and maliciously alter the "user_id", is it enough that the form is protected with {{ csrf_field() }} or must I employ some further security such as Crypt::encrypt($id) to hide the user_id (held in a database) and Crypt::decrypt($id)?

Is it considered a bad practice to expose a row id (like a user id) in a client browser (even though everything is sent over https)?

Many Thanks

like image 431
KevinY Avatar asked Dec 27 '17 18:12

KevinY


3 Answers

No, it's not enough to use just CSRF token in this case. You also need to use policies, guards, middleware to protect your app.

In this case, someone can alter the user_id if you read it from the form and use after that, so you need to use a policy like this one to protect data (this example is from the docs):

public function update(User $user, Post $post)
{
    return $user->id === $post->user_id;
}

Also, when you need to use user ID, always use auth()->id() or auth()->user() if you need whole object. Never read user ID from the form.

like image 159
Alexey Mezenin Avatar answered Nov 15 '22 04:11

Alexey Mezenin


The Laravel framework stores the value of this CSRF field like a session variable and matches it when you submit it.

When you submit the form Laravel checks that value from the session value stored. if there is a mismatch an error is thrown ! :)

like image 21
Ayush Maheshwari Avatar answered Nov 15 '22 04:11

Ayush Maheshwari


CSRF token protect the site from cross-site requests, means an external user can't duplicate the form and send a post request. Laravel create a random session token which we place in the hidden field using csrf_field() or Session::token() function. Laravel checks the session with hidden field value from the form before processing the form.

like image 26
Rahul Reghunath Avatar answered Nov 15 '22 04:11

Rahul Reghunath