Web Security
Beginner
2 min read
CSRF Tokens and the Synchroniser Token Pattern
Example
{{-- Laravel Blade: synchroniser token pattern --}}
{{-- HTML form: @csrf inserts a hidden _token field --}}
<form method="POST" action="/account/email">
@csrf
{{-- Expands to: <input type="hidden" name="_token" value="...32-byte-random..."> --}}
<input type="email" name="email" required>
<button type="submit">Update Email</button>
</form>
<?php
// Laravel: reading token in JavaScript (for AJAX)
// Place this in your main layout <head>:
// <meta name="csrf-token" content="{{ csrf_token() }}">
// JavaScript: axios — configure globally to send token header
// import axios from 'axios';
// axios.defaults.headers.common['X-CSRF-TOKEN'] =
// document.querySelector('meta[name="csrf-token"]').content;
// ----------------------------------------------------------------
// Double-submit cookie pattern (for token-based / SPA APIs)
// ----------------------------------------------------------------
// Server sets cookie:
// Set-Cookie: XSRF-TOKEN=<random>; SameSite=Strict; Secure; Path=/
//
// JavaScript reads cookie and adds header:
// const token = document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1];
// fetch('/api/transfer', {
// method: 'POST',
// headers: { 'X-XSRF-TOKEN': token, 'Content-Type': 'application/json' },
// body: JSON.stringify({ amount: 100 }),
// credentials: 'include'
// });
//
// Server validates: request header value === cookie value → reject if mismatch
?>
Related Resources
Web Security Reference
Complete tag & property list
Web Security How-To Guides
Step-by-step practical guides
Web Security Exercises
Practice what you've learned
More in Web Security