What is the csrf_token in the Laravel layout file?

6

I am aware that to submit a form in Laravel, you need to add a csrf_field, or declare that the route should 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 the abovementioned blocks used for?

    
asked by anonymous 28.02.2017 / 15:44

2 answers

5

This is more specifically intended for forms of type AJAX . It's basically catching token and include it in the headers for when you submit a request via AJAX .

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

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

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

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

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
    
01.03.2017 / 02:09
-5

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

    
28.02.2017 / 16:07