---
title: Apply CSRF Protection
impact: HIGH
impactDescription: prevents cross-site request forgery attacks
tags: csrf, tokens, forms, security
---

## Apply CSRF Protection

CSRF attacks force authenticated users to perform unintended actions in a web application in which they're currently authenticated.

**Incorrect (no CSRF protection):**

```html
<!-- No CSRF token - vulnerable if using cookie-based auth -->
<form action="/transfer" method="POST">
  <input name="amount" value="1000">
  <button>Transfer</button>
</form>
```

**Correct (CSRF protection using gorilla/csrf):**

```go
import "github.com/gorilla/csrf"

func main() {
    CSRF := csrf.Protect([]byte("32-byte-long-auth-key"))
    http.ListenAndServe(":8000", CSRF(r))
}

func TransferHandler(w http.ResponseWriter, r *http.Request) {
    // Pass the token to the template
    w.Header().Set("X-CSRF-Token", csrf.Token(r))
    // r.FormValue("gorilla.csrf.Token") is also checked automatically
}
```

```html
<form action="/transfer" method="POST">
  <!-- Use a hidden field for the token -->
  <input type="hidden" name="gorilla.csrf.Token" value="{{ .csrfToken }}">
  <input name="amount">
  <button>Transfer</button>
</form>
```

**Defense Depth:**
- Use `SameSite=Strict` or `Lax` for cookies.
- Use `Authorization: Bearer` (not cookies) for APIs.
- Custom headers (e.g., `X-Requested-With`) for AJAX.

**Tools:** `gorilla/csrf`, `nosurf`, SameSite cookies
