---
title: Apply CSRF Protection
impact: HIGH
impactDescription: prevents Cross-Site Request Forgery (CSRF) attacks by ensuring requests originate from the intended application
tags: csrf, tokens, forms, security, kotlin
---

## Apply CSRF Protection

CSRF attacks force an authenticated user to execute unwanted actions on a web application in which they're currently authenticated (like changing passwords or transferring funds). Modern web frameworks provide built-in protection that must be enabled and properly configured.

**Incorrect (no CSRF protection):**

```kotlin
// Spring Security - disabling CSRF without a valid reason
override fun configure(http: HttpSecurity) {
    http.csrf().disable() // VULNERABLE if using Cookie-based auth
}

// Raw HTML form without token
// <form action="/api/transfer" method="POST"> ... </form>
```

**Correct (CSRF protection enabled):**

```kotlin
// Spring Security (enabled by default)
@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http
            .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
    }
}

// In Template (Thymeleaf example)
// <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />

// Ktor CSRF Protection
install(Sessions) {
    cookie<UserSession>("user_session")
}
install(CSRF) {
    // Validate that a specific header is present
    checkHeader("X-CSRF-TOKEN")
}
```

**CSRF Defense Strategies:**
1.  **Anti-CSRF Tokens:** Include a unique, secret, and unpredictable token in all state-changing requests (POST, PUT, DELETE).
2.  **SameSite Cookies:** Set `SameSite=Strict` or `Lax` on all session cookies.
3.  **Custom Request Headers:** For APIs, requiring a custom header (like `X-Requested-With`) can block requests from standard `<form>` submissions.
4.  **Verification of Origin:** Validate `Origin` and `Referer` headers on the server.

**Tools:** Spring Security CSRF, OWASP ZAP, Burp Suite, Browser DevTools
