Skip to content

CSRF Protection

The Basics

CSRF Protection

Introduction

Cross-site request forgery (CSRF) is an attack in which another website makes a signed-in user's browser send a request to your application. For example, imagine your application has a /user/email route that accepts a POST request to change the user's email address. Without protection, a malicious site could include a form that posts the attacker's own email address to that route, and submit it as soon as the page loads:

1<form action="https://your-application.com/user/email" method="POST">
2 <input type="email" name="email" value="[email protected]">
3</form>
4 
5<script>
6 document.forms[0].submit();
7</script>
1<form action="https://your-application.com/user/email" method="POST">
2 <input type="email" name="email" value="[email protected]">
3</form>
4 
5<script>
6 document.forms[0].submit();
7</script>

The user's browser sends their session cookie along with the request. So if the attacker lures one of your users to that page, your application changes the user's email address to the attacker's.

Laravel protects your application from these requests by default. The web middleware group includes a middleware that checks every request except GET, HEAD, and OPTIONS requests. Since those three methods are never checked, make sure your routes that respond to them don't change any data.

How Laravel protects your application

The ValidateCSRFToken middleware in the web group checks each request in two steps:

  1. If the browser's Sec-Fetch-Site header says the request comes from your application's own origin, the middleware lets the request through. Modern browsers send this header over HTTPS, so this step covers nearly every request from your own pages.
  2. Otherwise, the request must carry the CSRF token stored in the user's session. If the token is missing or doesn't match, the middleware rejects the request with a 419 response.

Another site can't read your user's token, so it can't forge a request that carries it. Laravel also changes the token each time the user signs in or out.

If your application uses Inertia, you may send users back to their form with a message instead of showing them the 419 page. To learn more, check out the Inertia guide's section on expired pages.

Sending the token

Most requests from your own pages pass the Sec-Fetch-Site check, so ValidateCSRFToken never needs to look at their CSRF token. However, older browsers don't send the Sec-Fetch-Site header, and no browser sends it over plain HTTP, so those requests must carry the token instead. To make sure every request works, send the CSRF token from all of your forms and JavaScript requests.

Forms

An HTML form sends the token in a hidden _token field. You don't need to write the field yourself. In a view, call csrfField inside the form, and Laravel renders the hidden field with the current token:

1<form method="POST" action="/profile">
2 {{csrfField}}
3 
4 <!-- Renders <input type="hidden" name="_token" value="..."> -->
5</form>
1<form method="POST" action="/profile">
2 {{csrfField}}
3 
4 <!-- Renders <input type="hidden" name="_token" value="..."> -->
5</form>

JavaScript and Inertia

JavaScript requests usually need no extra work. On every response from a route in the web group, the ValidateCSRFToken middleware puts the CSRF token in an XSRF-TOKEN cookie. HTTP clients such as Axios, and the Inertia client, read that cookie and automatically send its value back in an X-XSRF-TOKEN header.

Some clients, such as the browser's built-in fetch, don't read the cookie. For those, send the token in an X-CSRF-TOKEN header instead. First, render the token in a <meta> tag in your layout view with csrfToken:

1<meta name="csrf-token" content="{{csrfToken}}">
1<meta name="csrf-token" content="{{csrfToken}}">

Then read the tag each time you send a request, rather than once when the page loads, because the token changes when the user signs in:

1fetch("/messages", {
2 method: "POST",
3 headers: {
4 "Content-Type": "application/json",
5 "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
6 },
7 body: JSON.stringify({ body: "Hello!" }),
8});
1fetch("/messages", {
2 method: "POST",
3 headers: {
4 "Content-Type": "application/json",
5 "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
6 },
7 body: JSON.stringify({ body: "Hello!" }),
8});

Excluding URIs from protection

Sometimes you may need to exclude a few URIs from CSRF protection. For example, if you process payments with Stripe and use its webhooks, Stripe's servers post to your application directly, and Stripe has no way of knowing your user's CSRF token. When applicable, verify those requests with the signature the provider sends instead.

A webhook rarely needs the session, so the best place for it is usually routes/api.go, which CSRF protection doesn't cover. If you'd like to keep a webhook in routes/web.go, you may exclude it from ValidateCSRFToken instead.

To exclude several URIs at once, such as every webhook route, replace the ValidateCSRFToken middleware in bootstrap/app.go with one that lists the URIs to skip. A * matches any part of a URI, so stripe/* excludes /stripe/webhook, /stripe/refunds, and every other URI under /stripe:

1import (
2 laravel "go.laravel.com"
3 "go.laravel.com/config"
4 "go.laravel.com/middleware"
5)
6 
7Middleware: func(m *laravel.Middleware, cfg *config.Config) {
8 m.Replace(middleware.ValidateCSRFToken{Except: []string{"stripe/*", "webhooks/*"}})
9},
1import (
2 laravel "go.laravel.com"
3 "go.laravel.com/config"
4 "go.laravel.com/middleware"
5)
6 
7Middleware: func(m *laravel.Middleware, cfg *config.Config) {
8 m.Replace(middleware.ValidateCSRFToken{Except: []string{"stripe/*", "webhooks/*"}})
9},

To exclude a single route, you may instead chain Without onto the route's definition in your route file. This keeps the exclusion next to the route it applies to:

1import "go.laravel.com/middleware"
2 
3route.Post("/stripe/webhook", webhooks.Stripe).Without(middleware.ValidateCSRFToken{})
1import "go.laravel.com/middleware"
2 
3route.Post("/stripe/webhook", webhooks.Stripe).Without(middleware.ValidateCSRFToken{})

Accepting requests from subdomains

Some applications span several subdomains that post to each other. For example, a page on dashboard.example.com might post a form to example.com. The browser marks that request as coming from the same site rather than the same origin, so ValidateCSRFToken checks it for a CSRF token. To let requests from your other subdomains through without a token, replace the middleware in bootstrap/app.go with one that sets AllowSameSite:

1import (
2 laravel "go.laravel.com"
3 "go.laravel.com/config"
4 "go.laravel.com/middleware"
5)
6 
7Middleware: func(m *laravel.Middleware, cfg *config.Config) {
8 m.Replace(middleware.ValidateCSRFToken{AllowSameSite: true})
9},
1import (
2 laravel "go.laravel.com"
3 "go.laravel.com/config"
4 "go.laravel.com/middleware"
5)
6 
7Middleware: func(m *laravel.Middleware, cfg *config.Config) {
8 m.Replace(middleware.ValidateCSRFToken{AllowSameSite: true})
9},