What is the csrf_token present in the Laravel layout file for?

Asked

Viewed 4,636 times

9

I am aware that to submit a form in Laravel, you must add a csrf_field, or declare that the route must ignore this protection. However, in the layout file there are the following occurrences:

<meta name="csrf-token" content="{{ csrf_token() }}">

...

<script>
    window.Laravel = {!! json_encode([
        'csrfToken' => csrf_token(),
    ]) !!};
</script>

What are these blocks mentioned above used for?

2 answers

7


This is more specifically aimed at forms of the type AJAX. It’s basically taking the token and include it in the headers for when you submit a request via AJAX.

The Laravel automatically generates a token CSRF for each active user session managed by the application. This token is used to verify if the authenticated user is the one who actually orders for the application.

In addition to checking the token CSRF as a POST parameter, middleware VerifyCsrfToken also checks the request header (X-CSRF-TOKEN). Hence the existence of this metatag.

<meta name="csrf-token" content="{{ csrf_token() }}">

So once you’ve created the metatag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides protection CSRF simple and convenient for your AJAX-based applications:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
  • I have now understood the importance and functioning of this element. Thank you.

-6

To prevent malicious solicitation from other sites, that is to protect your sites from external attacks.

  • This is automatic, or still need to implement some use for this token?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.