Laravel CSRF
What is CSRF?
CSRF (Cross-Site Request Forgery) is a type of attack that forces an end user to execute unwanted actions on a web application where they are authenticated. CSRF attacks can compromise the integrity of data by tricking users into performing actions they did not intend to perform, such as submitting a form or changing user settings.
How does Laravel protect against CSRF?
Laravel automatically protects your application from CSRF attacks by requiring a CSRF token on every POST, PUT, PATCH, or DELETE request. This token is included in the form and verified by Laravel to ensure the request originates from the application and not from a malicious third party.
What is a CSRF token?
A CSRF token is a unique, random string that Laravel generates for each active user session. It ensures that requests made to the server come from the authenticated user and not from an attacker. Laravel verifies the CSRF token during form submissions or AJAX requests to prevent CSRF attacks.
How do you include a CSRF token in a Laravel form?
In Blade templates, you can include a CSRF token in forms using the @csrf directive. This directive generates a hidden input field with the token, which Laravel checks when processing the form submission.
Example of including a CSRF token in a form:
<form method="POST" action="/submit-form">
@csrf
<input type="text" name="name" placeholder="Enter your name" />
<button type="submit">Submit</button>
</form>
In this example, the @csrf directive generates the CSRF token that protects the form from CSRF attacks.
How do you verify CSRF tokens in Laravel?
Laravel automatically verifies CSRF tokens for incoming requests when using methods like POST, PUT, DELETE, and PATCH. The CSRF token is automatically added to each request by including it in your forms using the @csrf directive. Laravel's middleware then checks if the token sent with the request matches the token stored in the user's session.
Example of Laravel's automatic CSRF protection:
Route::post('/submit-form', function (Request $request) {
// CSRF token is automatically verified
});
How do you exclude routes from CSRF protection in Laravel?
You can exclude specific routes from CSRF protection by adding them to the $except property of the VerifyCsrfToken middleware, located in the app/Http/Middleware/VerifyCsrfToken.php file.
Example of excluding a route from CSRF protection:
class VerifyCsrfToken extends Middleware
{
protected $except = [
'webhook/*', // Exclude webhook routes
];
}
In this example, all routes matching the pattern webhook/* are excluded from CSRF protection, which is useful for external services like webhooks that don't require CSRF tokens.
How do you use CSRF tokens in AJAX requests?
When making AJAX requests in Laravel, you must include the CSRF token in your request headers. You can retrieve the CSRF token from the page's meta tags or directly from Blade's @csrf directive and include it in the AJAX request.
Example of setting up CSRF tokens in AJAX requests:
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post('/submit-form', {name: 'John'}, function(response) {
console.log(response);
});
</script>
In this example, the CSRF token is included in the AJAX request headers, ensuring that Laravel can verify the request's authenticity.
What happens if a CSRF token is missing or invalid?
If a CSRF token is missing or invalid, Laravel will reject the request and throw a TokenMismatchException. This typically results in a 419 HTTP status code (Page Expired) response, indicating that the CSRF verification failed.
Example of CSRF failure:
Route::post('/submit-form', function (Request $request) {
// If the CSRF token is invalid, Laravel will throw a TokenMismatchException
});
How do you manually generate a CSRF token?
You can manually generate a CSRF token using the csrf_token() helper function in Laravel. This can be useful when you need to include the CSRF token in custom forms or AJAX requests.
Example of generating a CSRF token:
{{ csrf_token() }}This will output the CSRF token for the current user session, which can then be included in forms or requests.
How do you refresh the CSRF token in Laravel?
In some cases, you may need to refresh the CSRF token, especially in single-page applications (SPAs). You can refresh the CSRF token by making a request to an endpoint and retrieving a new token.
Example of refreshing the CSRF token in a JavaScript application:
$.get('/refresh-csrf').done(function(data) {
$('meta[name="csrf-token"]').attr('content', data.token);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': data.token
}
});
});
In this example, a new CSRF token is retrieved from the /refresh-csrf endpoint and updated in the application's AJAX setup.
What is the X-CSRF-TOKEN header in Laravel?
The X-CSRF-TOKEN header is used to send the CSRF token along with an AJAX request. Laravel checks this header to validate the token for POST, PUT, PATCH, or DELETE requests made via JavaScript.
Example of including the X-CSRF-TOKEN header:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
In this example, the CSRF token is added to the request headers using the X-CSRF-TOKEN header, ensuring that Laravel can validate the AJAX request.
Can you disable CSRF protection in Laravel?
While it's possible to disable CSRF protection by removing the VerifyCsrfToken middleware, it is not recommended for security reasons. You should only exclude specific routes from CSRF protection when necessary and avoid disabling it globally.
To disable CSRF protection for specific routes:
class VerifyCsrfToken extends Middleware
{
protected $except = [
'api/*',
];
}
This disables CSRF protection for all routes under the api/* path.