🔒 Security

CSRF

Cross-Site Request Forgery

A cross-site request forgery attack. A web security vulnerability that abuses a user's authenticated session to send unintended requests to a server.

📖 Detailed Explanation

CSRF (Cross-Site Request Forgery) is a web attack that causes a user, while authenticated, to unintentionally execute a malicious request. The attacker hides a request to a site the victim is logged in to inside a malicious page, and when the victim visits that page, the browser automatically sends the request with cookies included. Important operations such as bank transfers, password changes, and email address changes can be executed without the victim's knowledge.

Three conditions are required for a CSRF attack to succeed. First, the victim must be logged in to the target site. Second, the session cookie must be automatically included in the request. Third, the parameters of the target action must be predictable. For example, if the current password is not verified when changing a password, it is vulnerable to CSRF. If XSS is "executing malicious code on a trusted site," CSRF is "sending a trusted request from a malicious site."

The core of CSRF defense is the CSRF token (Anti-CSRF Token). The server generates a unique token for each session and requires that this token be included in every state-changing request. Since an attacker cannot know the victim's token value, they cannot craft a valid request. Major frameworks such as Django, Rails, and Spring Security have built-in support for CSRF tokens. In a SPA (Single Page Application), the token is sent via an HTTP header.

The SameSite cookie attribute in modern browsers is the new standard for CSRF defense. SameSite=Strict does not send cookies at all on cross-site requests, and SameSite=Lax sends cookies only on top-level navigations using safe methods (GET). Since SameSite=Lax became the default in Chrome 80, many CSRF attacks are automatically blocked. However, SameSite alone is not complete, so it should be used together with CSRF tokens.

💻 Code Example

// CSRF 방어 - Node.js Express 예제
const express = require('express');
const csrf = require('csurf');
const cookieParser = require('cookie-parser');

const app = express();

// 쿠키 파서 설정
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));

// CSRF 미들웨어 설정
const csrfProtection = csrf({
    cookie: {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'strict'  // SameSite 쿠키 설정
    }
});

// CSRF 토큰을 쿠키로 전달 (SPA용)
app.get('/api/csrf-token', csrfProtection, (req, res) => {
    res.json({ csrfToken: req.csrfToken() });
});

// 로그인 폼 (서버 사이드 렌더링)
app.get('/login', csrfProtection, (req, res) => {
    res.send(`
        
`); }); // 로그인 처리 - CSRF 토큰 검증 자동 수행 app.post('/login', csrfProtection, (req, res) => { // CSRF 토큰이 유효하지 않으면 403 에러 발생 const { email, password } = req.body; // 인증 로직... res.send('로그인 성공'); }); // 비밀번호 변경 - 민감한 작업에 CSRF 필수 app.post('/api/change-password', csrfProtection, (req, res) => { const { currentPassword, newPassword } = req.body; // 현재 비밀번호 확인 (CSRF와 별개로 추가 보안) if (!verifyCurrentPassword(req.user, currentPassword)) { return res.status(401).json({ error: '현재 비밀번호가 일치하지 않습니다' }); } // 비밀번호 변경 처리... res.json({ message: '비밀번호가 변경되었습니다' }); }); // CSRF 에러 핸들러 app.use((err, req, res, next) => { if (err.code === 'EBADCSRFTOKEN') { res.status(403).json({ error: 'CSRF 토큰이 유효하지 않습니다', message: '세션이 만료되었거나 요청이 위조되었습니다' }); } else { next(err); } }); // 쿠키 설정 예시 - SameSite 포함 app.post('/api/session', (req, res) => { res.cookie('sessionId', 'abc123', { httpOnly: true, secure: true, sameSite: 'lax', // 크로스 사이트 요청 제한 maxAge: 24 * 60 * 60 * 1000 // 24시간 }); res.json({ success: true }); });
# CSRF 방어 - Django 예제
# Django는 CSRF 보호가 기본 활성화

# settings.py
CSRF_COOKIE_SECURE = True  # HTTPS에서만 쿠키 전송
CSRF_COOKIE_HTTPONLY = True  # JavaScript에서 쿠키 접근 불가
CSRF_COOKIE_SAMESITE = 'Lax'  # SameSite 설정
CSRF_TRUSTED_ORIGINS = ['https://example.com']  # 신뢰 도메인

# views.py
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
from django.middleware.csrf import get_token
from django.http import JsonResponse

# 템플릿에서 CSRF 토큰 사용
# {% csrf_token %} - 폼에 hidden 필드로 토큰 삽입

@ensure_csrf_cookie  # 쿠키에 CSRF 토큰 설정
def get_csrf_token(request):
    """SPA를 위한 CSRF 토큰 엔드포인트"""
    return JsonResponse({'csrfToken': get_token(request)})

@csrf_protect  # CSRF 검증 강제
def change_password(request):
    """비밀번호 변경 - CSRF 보호 필수"""
    if request.method == 'POST':
        current_password = request.POST.get('current_password')
        new_password = request.POST.get('new_password')

        # 현재 비밀번호 확인 (추가 보안)
        if not request.user.check_password(current_password):
            return JsonResponse({'error': '현재 비밀번호 불일치'}, status=401)

        request.user.set_password(new_password)
        request.user.save()
        return JsonResponse({'message': '비밀번호 변경됨'})

# AJAX 요청에서 CSRF 토큰 전송 (JavaScript)
"""
// 쿠키에서 CSRF 토큰 읽기
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

// fetch 요청에 CSRF 토큰 포함
fetch('/api/change-password', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'X-CSRFToken': getCookie('csrftoken')  // 헤더로 전송
    },
    credentials: 'include',  // 쿠키 포함
    body: JSON.stringify({ new_password: 'newPass123' })
});
"""

# REST Framework에서 CSRF
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['POST'])
def api_transfer_money(request):
    """
    DRF는 SessionAuthentication 사용 시 CSRF 검증 수행
    TokenAuthentication 사용 시 CSRF 불필요 (토큰 자체가 인증)
    """
    amount = request.data.get('amount')
    to_account = request.data.get('to_account')
    # 송금 처리...
    return Response({'success': True})
// CSRF 방어 - React SPA 예제
import axios from 'axios';
import { useEffect, useState } from 'react';

// Axios 인스턴스 설정 - CSRF 토큰 자동 포함
const api = axios.create({
    baseURL: '/api',
    withCredentials: true,  // 쿠키 포함
});

// 응답에서 CSRF 토큰 쿠키 추출
function getCsrfToken() {
    const name = 'csrftoken';
    const cookies = document.cookie.split(';');
    for (let cookie of cookies) {
        const [cookieName, cookieValue] = cookie.trim().split('=');
        if (cookieName === name) {
            return decodeURIComponent(cookieValue);
        }
    }
    return null;
}

// 요청 인터셉터 - 모든 요청에 CSRF 토큰 추가
api.interceptors.request.use(config => {
    const csrfToken = getCsrfToken();
    if (csrfToken) {
        config.headers['X-CSRFToken'] = csrfToken;
    }
    return config;
});

// CSRF 토큰 초기화 훅
function useCsrfToken() {
    const [isReady, setIsReady] = useState(false);

    useEffect(() => {
        // 앱 시작 시 CSRF 토큰 쿠키 획득
        api.get('/csrf-token')
            .then(() => setIsReady(true))
            .catch(err => console.error('CSRF 토큰 초기화 실패:', err));
    }, []);

    return isReady;
}

// 비밀번호 변경 폼 컴포넌트
function ChangePasswordForm() {
    const csrfReady = useCsrfToken();
    const [formData, setFormData] = useState({
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
    });
    const [error, setError] = useState('');
    const [success, setSuccess] = useState(false);

    const handleSubmit = async (e) => {
        e.preventDefault();
        setError('');

        if (formData.newPassword !== formData.confirmPassword) {
            setError('새 비밀번호가 일치하지 않습니다');
            return;
        }

        try {
            // CSRF 토큰이 헤더에 자동 포함됨
            await api.post('/change-password', {
                current_password: formData.currentPassword,
                new_password: formData.newPassword
            });
            setSuccess(true);
        } catch (err) {
            if (err.response?.status === 403) {
                setError('세션이 만료되었습니다. 다시 로그인해주세요.');
            } else {
                setError(err.response?.data?.error || '오류가 발생했습니다');
            }
        }
    };

    if (!csrfReady) {
        return 
로딩 중...
; } return (
{error &&
{error}
} {success &&
비밀번호가 변경되었습니다
} setFormData({...formData, currentPassword: e.target.value})} required /> setFormData({...formData, newPassword: e.target.value})} required /> setFormData({...formData, confirmPassword: e.target.value})} required />
); }

🗣️ Say It Like This in Practice

💬 In a security audit feedback
"The password change API has no CSRF protection. An attacker could change the victim's password from a malicious page. If it's Django, please add the @csrf_protect decorator and update the frontend to send the X-CSRFToken header."
💬 When designing an SPA architecture
"If a React app uses session cookie authentication, a CSRF token is required. Call /api/csrf-token at app initialization to get the cookie, and put the X-CSRFToken header on every POST/PUT/DELETE request. If it's JWT token authentication, CSRF is not needed."
💬 In a cookie configuration discussion
"Set SameSite=Lax on the session cookie. It's the default since Chrome 80, but it's better to set it explicitly. For sensitive operations like payments, use SameSite=Strict together with a CSRF token."

⚠️ Cautions & Best Practices

❌
State change via GET request

GET requests often skip CSRF token verification. State changes such as account deletion, money transfers, and settings changes must always use POST/PUT/DELETE, and the CSRF token must be verified.

❌
Exposing the CSRF token in the URL

If the CSRF token is sent as a query parameter, it is exposed in the Referer header and browser history. Always send it in the POST body or a custom header (X-CSRFToken).

❌
Omitting the CSRF token by relying only on SameSite

SameSite cookies are not supported in older browsers and can be vulnerable to subdomain attacks. Use them together with CSRF tokens for defense in depth.

✅
CSRF Defense Best Practices

Use the framework's built-in CSRF protection, and require re-authentication (verifying the current password) for sensitive operations. Add Origin/Referer header verification, and set SameSite=Lax or stricter on session cookies.

🔗 Related Terms

📚 Learn More