August 2, 2024 · 4 min read · 93 views
We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.
CSRF (Cross-Site Request Forgery) protection is a security measure implemented in web applications to prevent unauthorized actions from being performed on behalf of an authenticated user. In Laravel, CSRF protection is a built-in feature that helps safeguard your application against such attacks by ensuring that every form submission and sensitive request includes a unique token that verifies the request's legitimacy.
CSRF attacks can be detrimental as they exploit the trust a web application has in the authenticated user. If not protected, malicious actors can trick users into performing unwanted actions such as changing account details, making unauthorized transactions, or even deleting important data. By implementing CSRF protection, Laravel ensures that only legitimate requests, initiated by the user, are processed by the application.
In Laravel, CSRF protection is automatically enabled for all routes that use the web middleware group. This middleware group is applied to most of the routes in a typical Laravel application, ensuring strong protection.
Laravel generates a unique CSRF token for each active user session. This token is embedded in all forms generated by the @csrf
Blade directive and is also included in the meta tags of your web pages. Here's an example of how to include a CSRF token in a form if you are using Blade for the frontend:
<form method="POST" action="/example">
@csrf
<!-- Form fields go here -->
<button type="submit">Submit</button>
</form>
The @csrf
directive generates a hidden input field with the CSRF token, ensuring that the token is submitted along with the form data.
When a form is submitted, Laravel verifies the CSRF token to ensure it matches the token stored in the user's session. If the token is missing or invalid, the request is rejected. This verification helps prevent unauthorized requests from being processed.
For AJAX requests, you need to include the CSRF token in the request headers. You can achieve this by setting the X-CSRF-TOKEN header with the token value. Here's an example using Axios, but before that you could store the token in an HTML meta tag:<meta name="csrf-token" content="{{ csrf_token() }}">
import axios from 'axios';
// Set the CSRF token as a common header
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
// Example of making an AJAX request with Axios
axios.post('/example-endpoint', {
name: 'John Doe'
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
This setup ensures that all Axios requests include the CSRF token, allowing Laravel to verify the request's legitimacy.
In some cases, you might want to exclude certain routes from CSRF protection. This can be done by adding the route URIs to the validateCsrfTokens
method in your application's bootstrap/app.php
file:
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->validateCsrfTokens(except: [
'stripe/*',
'http://example.com/foo/bar',
'http://example.com/foo/*',
]);
})
->withExceptions(function (Exceptions $exceptions) {
})
->create();
Use this feature sparingly and only for routes where CSRF protection is genuinely unnecessary, as it reduces your application's security.
CSRF protection is a crucial aspect of web application security, and Laravel simplifies its implementation by providing built-in mechanisms to safeguard your application. By understanding and leveraging Laravel's CSRF protection features, you can protect your application from unauthorized actions and ensure a secure user experience.
Laravel 11 for Beginners: Using Custom and Built-in Commands
Laravel 11 for Beginners: Using Policies for Authorization
This article is part of our series Laravel 11 for Beginners: A Step-by-Step Guide to Learn the Concepts.
If you need help with a Laravel project let's get in touch.
Lucky Media is proud to be recognized as a Top Laravel Development Agency
Technologies:
Related Posts
Stay up to date
Be updated with all news, products and tips we share!