CSRF Protection in Laravel
Certainly! CSRF (Cross-Site Request Forgery) protection is an important security measure in Laravel to prevent unauthorized commands from being executed on behalf of an authenticated user. Below is a detailed step-by-step guide to implementing and managing CSRF protection for POST requests in Laravel.
Step 1: CSRF Protection in Laravel
Laravel automatically generates and verifies CSRF tokens to protect against CSRF attacks. Any form that performs a POST
, PUT
, PATCH
, or the DELETE
request must include a CSRF token.
Step 2: Enabling CSRF Protection
By default, Laravel includes CSRF protection through middleware. You can find it in:
Look for the VerifyCsrfToken
middleware in the $middlewareGroups
array:
This ensures that all routes in the web
middleware groups are protected.
Step 3: Adding CSRF Token to Forms
Whenever you create a form in Laravel that submits a POST
, PUT
, PATCH
, or DELETE
request, you must include a CSRF token.
Using Blade Syntax
Add the @csrf
directive inside your form:
The @csrf
directive generates a hidden input field like this:
Step 4: Manually Retrieving CSRF Token
If you're making an AJAX request or using JavaScript frameworks like Vue.js or React, you must manually pass the CSRF token.
1. Adding CSRF Token to AJAX Requests (jQuery)
If you are using jQuery for an AJAX POST
request, include the token in the headers:
You can set the token in your Blade template:
2. Adding CSRF Token in JavaScript Fetch API
If you're using fetch()
, include the CSRF token in the headers:
Step 5: Handling CSRF Token Verification Errors
If a request is rejected due to a missing or invalid CSRF token, Laravel will return a 419 Page Expired error.
To debug:
- Ensure your form includes
@csrf
if using Blade. - Verify the token is correctly passed in AJAX requests.
- If testing API routes, consider disabling CSRF for API endpoints (see Step 6).
Step 6: Disabling CSRF Protection for Specific Routes
If you have an API or webhook that does not require CSRF protection, you can exclude it in VerifyCsrfToken.php
:
Path: app/Http/Middleware/VerifyCsrfToken.php
Use this cautiously, as disabling CSRF can expose your application to security risks.
Step 7: Regenerating CSRF Token After User Logout
Laravel automatically regenerates the CSRF token after logout for security reasons. If you face issues with token mismatches, ensure your session is correctly refreshed after logging in or out.
Conclusion
- CSRF protection is enabled by default in Laravel.
- Use
@csrf
in forms. - Include CSRF tokens in AJAX requests.
- Handle
419
errors by ensuring tokens are included. - Exclude API routes from CSRF protection only when necessary.
Would you like an example with Laravel controllers and routes? 🚀