CSRF (Cross-Site Request Forgery) protection setup for website

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

CSRF Protection Setup for Websites

CSRF — attack where attacker forces authorized user to unintentionally execute action on target site. Classic example: user logged into bank, opens malicious page — it sends POST request to transfer money on their behalf.

Attack Mechanism

Browser automatically attaches cookies to any request to domain, regardless of request origin. If site uses session authentication via cookies, attacker can create form or XHR executing action on behalf of victim.

CSRF Token Protection

Classic and most reliable approach: unique token per session is generated, embedded in forms and verified on each POST/PUT/DELETE request.

Laravel (built-in protection):

// Middleware VerifyCsrfToken connected globally in app/Http/Kernel.php
// In Blade templates:
<form method="POST" action="/profile">
    @csrf
    {{-- Generates: <input type="hidden" name="_token" value="..."> --}}
</form>

For AJAX requests token passed via meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">
// Axios — setup once globally
axios.defaults.headers.common['X-CSRF-TOKEN'] =
    document.querySelector('meta[name="csrf-token"]').content;

// Fetch
const response = await fetch('/api/data', {
    method: 'POST',
    headers: {
        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
});

SameSite Cookie

Modern and elegant protection method — SameSite flag in cookies:

// Laravel config/session.php
'same_site' => 'lax', // or 'strict'
Value Behavior
Strict Cookie not sent in any cross-site requests
Lax Cookie not sent on cross-site POST, but sent on link navigation
None Cookie sent everywhere (requires Secure)

Lax — good balance for most sites. Strict breaks external link navigation (user clicks link from email and ends up unauthorized).

Double Submit Cookie

For sessionless APIs (SPA + JWT): token stored in cookie and duplicated in header. Server compares them.

// Client reads cookie (accessible via JS, not HttpOnly)
const csrfToken = document.cookie
    .split('; ')
    .find(row => row.startsWith('XSRF-TOKEN='))
    ?.split('=')[1];

axios.defaults.headers.common['X-XSRF-TOKEN'] = csrfToken;

Laravel Sanctum uses exactly this pattern for SPA authentication.

CSRF Protection Exceptions

Some routes intentionally exclude from CSRF verification (payment system webhooks, Stripe events etc):

// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'stripe/*',
    'webhooks/github',
];

For excluded routes authentication verification done via HMAC signature or Bearer token.

Origin/Referer Verification

Additional layer: verify Origin or Referer header on mutating requests. If Origin doesn't match server domain — request rejected.

// Example middleware
public function handle($request, Closure $next)
{
    $origin = $request->header('Origin');
    $allowed = ['https://example.com', 'https://app.example.com'];

    if ($request->isMethod('POST') && !in_array($origin, $allowed)) {
        abort(403, 'Forbidden origin');
    }

    return $next($request);
}

CSRF Protection Testing

  1. Create HTML page on different domain with form posting to protected URL
  2. Authorize on target site
  3. Navigate to malicious page and try to submit form
  4. Server must return 419 (Laravel) or 403

Implementation Timeline

  • Basic CSRF protection in Laravel/Django/Rails: 1 day
  • SPA integration (Sanctum/XSRF cookie): 1–2 days
  • Audit and fix vulnerable forms in legacy project: 2–5 days