csrf-protection
БесплатноБез исполняемых скриптовНе проверенImplement Cross-Site Request Forgery (CSRF) protection for API routes. Use this skill when you need to protect POST/PUT/DELETE endpoints, implement token…
Об этом скилле
CSRF Protection - Preventing Cross-Site Request Forgery
What CSRF Attacks Are
The Attack Scenario
Imagine you're logged into your banking app. In another tab, you visit a malicious website. That website contains hidden code that submits a form to your bank: "Transfer $10,000 to attacker's account." Because you're logged in, your browser automatically sends your session cookie, and the bank processes the transfer.
This is Cross-Site Request Forgery—tricking your browser into making requests you didn't intend.
Real-World CSRF Attacks
Router DNS Hijacking (2008): A CSRF vulnerability in several home routers allowed attackers to change router DNS settings by tricking users into visiting a malicious website. Victims lost no money but were redirected to phishing sites for months. Millions of routers were affected.
YouTube Actions (2012): YouTube had a CSRF vulnerability that allowed attackers to perform actions as other users (like, subscribe, etc.) by tricking them into visiting a crafted URL.
Why CSRF Is Still Common
According to OWASP, CSRF vulnerabilities appear in 35% of web applications tested. Why?
- It's invisible when it works (users don't know they made a request)
- Easy to forget to implement (no obvious broken functionality)
- Developers often rely solely on authentication without checking request origin
Our CSRF Architecture
Implementation Features
HMAC-SHA256 Cryptographic Signing (industry standard)
- Provides cryptographic proof token was generated by our server
- Even if intercepted, attackers can't forge tokens without secret key
Session-Bound Tokens
- Tokens can't be used across different user sessions
- Each user gets unique tokens
Single-Use Tokens
- Token cleared after validation
- Window of opportunity is seconds, not hours
- If captured, useless after one request
HTTP-Only Cookies
- JavaScript cannot access tokens
- Prevents XSS-based token theft
SameSite=Strict
- Browser won't send cookie on cross-origin requests
- Additional layer of protection
Implementation Files
lib/csrf.ts- Cryptographic token generationlib/withCsrf.ts- Middleware enforcing verificationapp/api/csrf/route.ts- Token endpoint for clients
How to Use CSRF Protection
Step 1: Wrap Your Handler
For any POST/PUT/DELETE endpoint:
import { NextRequest, NextResponse } from 'next/server';
import { withCsrf } from '@/lib/withCsrf';
async function handler(request: NextRequest) {
// Your business logic here
// Token automatically verified by withCsrf
return NextResponse.json({ success: true });
}
// Apply CSRF protection
export const POST = withCsrf(handler);
export const config = {
runtime: 'nodejs', // Required for crypto operations
};
Step 2: Client-Side Token Fetching
Before making a protected request, fetch the CSRF token:
// Fetch CSRF token
const response = await fetch('/api/csrf', {
credentials: 'include'
});
const { csrfToken } = await response.json();
// Use token in POST request
await fetch('/api/your-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken // Include token in header
},
credentials: 'include', // Important: send cookies
body: JSON.stringify(data)
});
Step 3: What Happens Automatically
When withCsrf() wraps your handler:
- Extracts CSRF token from
X-CSRF-Tokenheader - Extracts CSRF cookie from request
- Verifies token matches cookie using HMAC
- Clears token after validation (single-use)
- If valid → calls your handler
- If invalid → returns HTTP 403 Forbidden
Complete Example: Protected Contact Form
// app/api/contact/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { withCsrf } from '@/lib/withCsrf';
import { withRateLimit } from '@/lib/withRateLimit';
import { validateRequest } from '@/lib/validateRequest';
import { contactFormSchema } from '@/lib/validation';
import { handleApiError } from '@/lib/errorHandler';
async function contactHandler(request: NextRequest) {
try {
const body = await request.json();
// Validate input
const validation = validateRequest(contactFormSchema, body);
if (!validation.success) {
return validation.response;
}
const { name, email, subject, message } = validation.data;
// Process contact form
await sendEmail({
to: '[email protected]',
from: email,
subject,
message
});
return NextResponse.json({ success: true });
} catch (error) {
return handleApiError(error, 'contact-form');
}
}
// Apply both rate limiting AND CSRF protection
export const POST = withRateLimit(withCsrf(contactHandler));
export const config = {
runtime: 'nodejs',
};
Frontend Integration Example
// components/ContactForm.tsx
'use client';
import { useState } from 'rea
Установить csrf-protection в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл csrf-protection?
Implement Cross-Site Request Forgery (CSRF) protection for API routes. Use this skill when you need to protect POST/PUT/DELETE endpoints, implement token validation, prevent cross-site attacks, or secure form submissions. Triggers include "CSRF", "cross-site request forgery", "protect form", "token validation", "withCsrf", "CSRF token", "session fixation".
Как установить скилл csrf-protection?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл csrf-protection запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic