CSRF Protection

Protecting against Cross-Site Request Forgery

Category: Security

CSRF Protection

Cross-Site Request Forgery (CSRF) is a malicious exploit whereby unauthorized commands are transmitted from a user that the web application trusts.

VelvetCMS 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.

How It Works #

The VerifyCsrfToken middleware, which is included in the web middleware group by default, automatically verifies that the token in the request input matches the token stored in the session.

Using the Token #

In Forms #

Anytime you define a HTML form in your application that points to a POST, PUT, PATCH, or DELETE route, you should include a hidden CSRF _token field in the form so that the CSRF protection middleware can validate the request.

You can use the csrf_field() helper to generate the token field:

<form method="POST" action="/profile">
    {!! csrf_field() !!}
    
    <!-- Equivalent to: -->
    <input type="hidden" name="_token" value="xyz...">
</form>

In JavaScript (AJAX) #

When building JavaScript driven applications, you can access the token from a meta tag:

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

Then, configure your AJAX library (like Axios or jQuery) to automatically add the X-CSRF-TOKEN header to every request:

const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

fetch('/api/user', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': token
    },
    body: JSON.stringify({ name: 'John' })
});

Excluding Routes #

Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.

You can exclude routes by adding them to the $except property in the VerifyCsrfToken middleware class.