The CSRF Token in Laravel may ONLY work IF the user is Authenticated
Content Index
There's something you should know, and one that most people probably overlook, about the blessed CSRF token we use. In this case, I'm focusing on Laravel, but it's obviously used in other frameworks. It's precisely the token we configure when we send any request from a form.
Look at what the official documentation tells us. The token in question is a feature that prevents malicious exploits, through which unauthorized commands from other sites could send requests to our application.
So far, so good. The important detail is that this token only works if the user is authenticated. That is, if the user is not authenticated, validation will always fail.
In production, submitting a form via JavaScript with the token configured in the header returns a 419 error (if you're a Laravel developer, you'll be familiar with this error: it occurs when the token isn't passed). Locally, this error does NOT occur.
The reason for this is unclear, but it seems to me that local Laravel knows from the URL or environment variables that the form is NOT in production and relaxes the checks.
How to fix it?
Even if we pass the token, if the user isn't authenticated, it will fail. The solution is simple:
Go to the bootstrap/app.php file
Exclude the form's specific route from validation:
bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
$middleware->statefulApi();
$middleware->validateCsrfTokens(except: [
'/social/subscribe',
]);
})
This way, the endpoint no longer requires authentication to validate the token. I tested it in production, and it now returns a 200 OK instead of a 419 error.
In summary:
- If the user isn't authenticated and you use the CSRF token, you'll get an error.
- You should thoroughly test your forms in production, especially if the user doesn't need to log in.
- Depending on how you pass the token, it may work in some views and not in others.
- So keep this in mind before uploading your app.
I agree to receive announcements of interest about this Blog.
Protect Your Laravel: How CSRF Tokens and Authentication Work