PHP

Implement CSRF Protection with Synchronizer Tokens (Laravel)

Protect web forms and state-changing requests from Cross-Site Request Forgery (CSRF) attacks by implementing synchronizer tokens, as demonstrated in Laravel.

<?php
// In a Blade template (e.g., resources/views/form.blade.php)
// This generates a hidden input field with the CSRF token.
echo '<form method="POST" action="/profile">
    <input type="hidden" name="_token" value="' . csrf_token() . '">
    <!-- Other form fields -->
    <button type="submit">Update Profile</button>
</form>';

// In a Laravel controller (e.g., app/Http/Controllers/ProfileController.php)
// Laravel's VerifyCsrfToken middleware automatically handles this check.
// It compares the token from the form with the one stored in the session.
// If they don't match, an exception is thrown.

/*
// Simplified conceptual check (DO NOT implement manually in Laravel)
class ProfileController extends Controller
{
    public function update(Request $request)
    {
        // A conceptual manual check, for explanation purposes.
        // In Laravel, this is handled by the VerifyCsrfToken middleware.
        $sessionToken = $request->session()->token();
        $formToken = $request->input('_token');

        if ($sessionToken !== $formToken) {
            abort(419, 'Page Expired - CSRF token mismatch.');
        }

        // ... process valid request ...
    }
}
*/

// To protect AJAX requests, you can include the CSRF token in headers:
// For Axios, after generating the token server-side:
// axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
How it works: This snippet illustrates how Cross-Site Request Forgery (CSRF) protection is typically implemented using synchronizer tokens, specifically leveraging Laravel's built-in features. A unique, unpredictable `_token` is generated and embedded in forms. On submission, the server-side middleware (like Laravel's `VerifyCsrfToken`) compares this token against one stored in the user's session. If they don't match, the request is rejected, preventing attackers from forging requests on behalf of authenticated users. For AJAX calls, the token is often sent via a custom HTTP header.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs