Question:
I am aware that to submit a form in Laravel, you need to add a csrf_field, or declare that the route should bypass 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?
Answer:
This is more specifically intended for forms of the AJAX
type. It's basically taking the token
and including it in the headers for when you send a request via AJAX
.
Laravel
automatically generates a 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 makes requests to the application.
In addition to verifying the token CSRF
as a POST parameter, the VerifyCsrfToken
middleware also verifies the request header ( X-CSRF-TOKEN
). Hence the existence of this metatag
.
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you've created the meta tag, you can instruct a library like jQuery
to automatically add the 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')
}
});