Blog | G5 Cyber Security

CSRF Token Security: Preventing POST/PUT Attacks

TL;DR

Knowing a CSRF token doesn’t automatically let an attacker make valid POST or PUT requests. Proper implementation, including checking the Origin header and SameSite cookies, is crucial to prevent attacks.

Understanding the Problem

Cross-Site Request Forgery (CSRF) tokens are designed to protect against attackers making unwanted actions on your website on behalf of a logged-in user. However, simply possessing the token isn’t enough for an attack to succeed. Modern browsers and server-side checks provide additional layers of security.

Steps to Prevent POST/PUT Attacks Even With Token Knowledge

  1. Verify the Origin Header
from flask import Flask, request
app = Flask(__name__)
@app.route('/update', methods=['POST'])
if request.origin != 'https://yourdomain.com':
    return "Unauthorized", 403
  • Example (Node.js/Express):
  • const express = require('express');
    const app = express();
    app.post('/update', (req, res) => {
      if (req.headers.origin !== 'https://yourdomain.com') {
        return res.status(403).send('Unauthorized');
      }
    });
    
  • Use SameSite Cookies
  • setcookie('csrf_token', $token, ['samesite' => 'Strict']);
    
  • Double Submit Cookie Pattern
  • Token Rotation
  • Input Validation and Output Encoding
  • Consider using a well-vetted cybersecurity framework
  • Why Knowing the Token Isn’t Enough

    Even with a valid token, an attacker needs to bypass browser security features (like SameSite cookies) and server-side checks (Origin header verification). Modern browsers are designed to prevent cross-site requests from sending sensitive cookies automatically.

    Testing Your CSRF Protection

    Exit mobile version