为什么如果我不在表单末尾放置 {{csrf_field()}}(在 Laravel 5 视图中)我会得到 TokenMismatchException?

Why if I don't put a {{csrf_field()}} at the end of a form (in a Laravel 5 view) I obtain a TokenMismatchException?

我是 PHPLaravel 的新手,我对 {{csrf_field()}} 中插入的符号有以下疑问 <form>.

进入视图我有以下形式:

<form method="post" action="/registration">

  <div class="form-group">
    <label>Nome</label>
    <div class="input-group">
      <div class="input-group-addon"><i class="fa fa-user"></i></div>
      <input type="text" name="name" class="form-control" placeholder="Inserisci il tuo nome">
    </div>
  </div>

  <div class="form-group">
    <label>Cognome</label>
    <div class="input-group">
      <div class="input-group-addon"><i class="fa fa-user"></i></div>
      <input type="text" name="surname" class="form-control" placeholder="Inserisci il tuo cognome">
    </div>
  </div>

  <!-- Some other fields -->

  {{csrf_field()}}

  <button type="submit" class="btn btn-default">Submit</button>

</form>

这是由这种简约的控制器方法处理的:

public function store(Request $request)
{
    return $request->all();
}

因此,如果我将 {{csrf_field()}} "statment" 放在提交按钮之前,它可以正常工作并且控制器方法可以正确处理请求,但是如果我删除这行它不起作用,我得到一个 TokenMismatchException.

为什么会这样,这个 {{csrf_field()}} 到底代表了什么,为什么我要在表格中使用它?

Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user. Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application. Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request.

更多信息请参考CSRF Protection documentation

CSRF 代表 Cross-Site 请求伪造

在这种情况下,Laravel 要求将此字段与请求一起发送,以便它可以在回发时验证请求不是伪造的。

可以在这里找到很好的解释:

简答是防止cross-site请求伪造

Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the website trusts.[2] Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user's browser.

更多关于https://laravel.com/docs/5.4/csrf

用简单的英语来说,它用于确保提交的表单是从服务器生成的,并且是从用户的浏览器应用的,而不是机器人或任何类型的程序代理。

无论您是否使用 Laravel 这样的框架,处理 CSRF 都是非常重要的。