Laravel makes it easy to protect your application from cross-site request forgeries. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of the 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.
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
Of course, using the Blade templating engine:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
You do not need to manually verify the CSRF token on POST, PUT, or DELETE requests. The VerifyCsrfToken
HTTP middleware will verify token in the request input matches the token stored in the session.
In addition to looking for the CSRF token as a "POST" parameter, the middleware will also check for the X-CSRF-TOKEN
request header. You could, for example, store the token in a "meta" tag and instruct jQuery to add it to all request headers:
<meta name="csrf-token" content="{{ csrf_token() }}" />
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Now all AJAX requests will automatically include the CSRF token:
$.ajax({
url: "/foo/bar",
})
Laravel also stores the CSRF token in a XSRF-TOKEN
cookie. You can use the cookie value to set the X-XSRF-TOKEN
request header. Some JavaScript frameworks, like Angular, do this automatically for you.