CSRF Token (also called anti-CSRF token, synchronizer token, or nonce) is a unique, unpredictable value associated with a user's session that must be included in state-changing requests. The server validates this token to ensure requests originated from the legitimate application.
The server generates a random token and associates it with the user's session. This token is included in forms as a hidden field or in AJAX requests as a header. On each request, the server compares the submitted token with the stored value.
<!-- Token in form -->
<form action="/transfer" method="POST">
<input type="hidden" name="csrf_token"
value="a8f4e2c1b9d7...">
<input type="text" name="amount">
<button type="submit">Transfer</button>
</form>
<!-- Token in AJAX header -->
fetch('/api/transfer', {
method: 'POST',
headers: {
'X-CSRF-Token': 'a8f4e2c1b9d7...'
},
body: JSON.stringify({amount: 100})
});