What is CSRF Protection in Laravel

Laravel makes it easy to protect your website from fraudulent application (CSRF) attacks. Cross-site request forgeries are a form of malicious exploitation where unauthorized orders are made on behalf of a certified user.

The CSRF token is used to verify a verified user that you are actually making requests to the website. Whenever you define an HTML form on your website, you must enter a field of hidden CSRF tokens in the form for CSRF middleware protection to verify the request. You can use @csrf Blade directions to create a token field.

<form method="POST" action="/profile">
    @csrf
    ...
</form>

Excluding URIs From CSRF Protection

Sometimes you may wish to remove a set of URIs for CSRF protection. If you are using Stripe to process payments and using their webhook system you will need to uninstall your web Stroke management method from CSRF security as Stripe is not the CSRF token you are sending to your routes.

X-CSRF-TOKEN

In addition to viewing the CSRF token as a POST parameter the VerifyCsrfToken middleware will also test the X-CSRF-TOKEN. You can save the token in an HTML meta tag.

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

Then you have created the meta tag you can instruct a library like jQuery to automatically add the token to all request headers. Laravel provides convenient CSRF protection for your AJAX based applications:

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

X-XSRF-TOKEN

Laravel stores the current CSRF token in encrypted XSRF-TOKEN cookie that is included with each response generated by the framework. You can use the cookie value to set X-XSRF-TOKEN request header.

This cookie is primarily sent as a convenience since some JavaScript frameworks and libraries, like Angular and Axios, automatically place its value in the X-XSRF-TOKEN header on same-origin requests.