CSRF Token

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.

How It Works

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.

Implementation Example

<!-- 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})
});

Token Properties

  • Unique per session: Each user has their own token
  • Unpredictable: Cryptographically random value
  • Validated server-side: Token checked before processing
  • Often rotated: New token per form or request

Common Weaknesses

  • Token not validated on server
  • Token tied to session but not user
  • Predictable token generation
  • Token leaked via Referer header

See Also