Get a Pentest and security assessment of your IT network.

Cyber Security

CSRF Tokens: A Simple Guide

TL;DR

Cross-Site Request Forgery (CSRF) lets attackers trick users into doing things they didn’t intend on websites. CSRF tokens are a simple way to stop this by adding a secret, unique code to each form submission. This guide shows you how to create and use them.

What is CSRF?

Imagine you’re logged into your online bank. An attacker sends you an email with a link that looks harmless. Clicking it loads a fake website that automatically submits a request to your bank to transfer money – without your knowledge. That’s CSRF in action.

How CSRF Tokens Work

CSRF tokens are unique, secret values generated by the server and included with each form submission. When the server receives a request, it checks if the token is valid. If not, the request is rejected. Because the attacker can’t easily guess or obtain this token, they can’t forge legitimate requests.

Implementing CSRF Tokens

  1. Generate a Unique Token: When a user loads a form, your server creates a random, unique token for that session.
  2. Store the Token: Store this token securely on the server-side (e.g., in the user’s session).
  3. Include the Token in the Form: Add a hidden field to your form containing the token.
  4. Validate the Token on Submission: When the form is submitted, compare the received token with the one stored on the server. If they match, proceed; otherwise, reject the request.

Step-by-Step Guide

Let’s look at a practical example using PHP (but the concept applies to other languages).

1. Generating and Including the Token



<form action="process.php" method="post">
  <input type="hidden" name="csrf_token" value="">
  ...
</form>

This code snippet generates a token if one doesn’t exist and adds it as a hidden field to your form. htmlspecialchars() is important for security – it prevents XSS attacks.

2. Validating the Token

This code checks if a token was submitted and compares it to the one stored in the session. hash_equals() is crucial for secure comparison – standard string comparisons can be vulnerable to timing attacks.

3. Important Considerations

  • Token Regeneration: Regenerate the CSRF token on sensitive actions (e.g., password changes) to prevent replay attacks.
  • Session Security: Ensure your session management is secure (use HTTPS, set appropriate cookies flags).
  • Double Submit Cookie: As an alternative or addition, you can use a double-submit cookie pattern for stateless CSRF protection.
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation