In a Single Page Application (SPA), CSRF tokens can be managed as follows:
Token Generation : The server generates a CSRF token for each user session and sends it to the client.
Token Storage : The client stores the CSRF token, typically in a cookie or local storage.
Token Inclusion : The client includes the CSRF token in the headers of subsequent HTTP requests.
Token Validation : The server validates the CSRF token for each incoming request to ensure its authenticity.
Example :
# Server-side (Flask example)
from flask import Flask, session, request, jsonify
import os
app = Flask(__name__)
app.secret_key = os.urandom(24)
@app.before_request
def generate_csrf_token():
if 'csrf_token' not in session:
session['csrf_token'] = os.urandom(24).hex()
@app.route('/api/data', methods=['POST'])
def handle_data():
token = request.headers.get('X-CSRF-Token')
if not token or token != session['csrf_token']:
return jsonify({'error': 'Invalid CSRF token'}), 403
# Process the request
return jsonify({'success': 'Data processed'})
# Client-side (JavaScript example)
function sendData(data) {
const csrfToken = getCookie('csrf_token'); // Assume a function to get the CSRF token from cookies
fetch('/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken
},
body: JSON.stringify(data)
}).then(response => response.json())
.then(data => console.log(data));
}?