Published on

CSRF Tokens

Authors

Cross-Site Request Forgery (CSRF) is a common web security vulnerability that allows attackers to perform unauthorized actions on behalf of authenticated users. CSRF tokens are an essential defense mechanism to protect against CSRF attacks. In this guide, we'll explore what CSRF tokens are, why they are important, and how to implement them in your web applications.

Table of Contents

Introduction to CSRF Tokens

CSRF tokens are random, unique values generated by the server and included in the web application's forms. These tokens act as a second layer of defense against CSRF attacks. When a user visits a web page, the server generates a CSRF token and associates it with the user's session. The token is then included in all forms that require user actions, such as submitting data or changing account settings.

How CSRF Tokens Work

When a user submits a form, the browser includes the CSRF token as part of the form data. This token is not accessible to attackers as it is stored in the user's session, and cross-origin requests cannot read it due to the Same-Origin Policy. When the server receives the form submission, it verifies the CSRF token's validity before processing the request. If the token is valid, the request is considered legitimate, and the action is allowed.

Implementing CSRF Tokens

Let's look at how to implement CSRF tokens in your web application to prevent CSRF attacks.

Generating CSRF Tokens

In your server-side code, you need to generate a CSRF token for each user session. The token should be a random and unique value.

// Example of generating a CSRF token in Node.js
const crypto = require('crypto')

function generateCSRFToken() {
  return crypto.randomBytes(32).toString('hex')
}

Including CSRF Tokens in Forms

Once the CSRF token is generated, you need to include it in the web application's forms. Add a hidden input field to each form and set its value to the CSRF token.

<!-- Example of including a CSRF token in an HTML form -->
<form action="/update-profile" method="POST">
  <input type="hidden" name="csrfToken" value="{csrfToken}" />
  <!-- other form fields -->
  <button type="submit">Update Profile</button>
</form>

Verifying CSRF Tokens

On the server side, when a form is submitted, you need to verify the CSRF token's validity before processing the request.

// Example of verifying the CSRF token in Node.js
function verifyCSRFToken(req, res, next) {
  const { csrfToken } = req.body

  // Retrieve the CSRF token associated with the user's session
  const sessionCSRFToken = req.session.csrfToken

  if (csrfToken === sessionCSRFToken) {
    // CSRF token is valid, continue processing the request
    next()
  } else {
    // CSRF token is invalid, reject the request
    res.status(403).json({ error: 'Invalid CSRF token' })
  }
}

By implementing CSRF tokens in your web application, you can significantly reduce the risk of CSRF attacks and enhance the overall security of your system.

Conclusion

CSRF tokens are a critical security mechanism for protecting web applications against CSRF attacks. By including CSRF tokens in your forms and verifying their validity on the server side, you can prevent attackers from exploiting this vulnerability and ensure the integrity of user actions.

Resources

  1. OWASP Cross-Site Request Forgery (CSRF) Cheat Sheet
  2. Mozilla Developer Network - SameSite attribute