Blog | G5 Cyber Security

CSRF Protection for Web Services

TL;DR

Cross-Site Request Forgery (CSRF) lets attackers trick users into performing unwanted actions on a web service they’re logged into. This guide shows you how to protect your services using tokens, checking the Origin header, and other methods.

Understanding CSRF

Imagine you’re logged into your online banking. An attacker sends you an email with a link that *looks* harmless. Clicking it might actually send a request to your bank’s server to transfer money – without your knowledge! That’s CSRF in action.

How to Protect Your Web Services

  1. Use Anti-CSRF Tokens

Example (Python/Flask):

from flask import Flask, render_template, request, session
import secrets

app = Flask(__name__)
app.secret_key = 'your_secret_key'

@app.route('/')
def index():
  if 'csrf_token' not in session:
    session['csrf_token'] = secrets.token_hex(16) # Generate a random token
  return render_template('index.html', csrf_token=session['csrf_token'])

@app.route('/submit', methods=['POST'])
def submit():
    if request.form['csrf_token'] == session['csrf_token']:
        # Process the form data safely
        return 'Form submitted successfully!'
    else:
        return 'CSRF token invalid!'
  • Check the Origin Header
  • Example (Node.js/Express):

    const express = require('express');
    const app = express();
    
    app.post('/submit', (req, res) => {
      const allowedOrigins = ['https://yourdomain.com', 'https://www.yourdomain.com'];
      const origin = req.headers.origin;
    
      if (allowedOrigins.includes(origin)) {
        // Process the request safely
        res.send('Request processed successfully!');
      } else {
        res.status(403).send('Forbidden - Invalid Origin');
      }
    });
    
  • Use SameSite Cookies
  • Example (setting in HTTP response header):

    Set-Cookie: sessionid=value; SameSite=Strict
  • Double Submit Cookie Pattern
  • Consider using a Web Application Firewall (WAF)
  • Important Notes

    Exit mobile version