---
title: Protect OAuth Code Flow Vs CSRF
impact: HIGH
impactDescription: prevents OAuth authorization code theft
tags: oauth, csrf, state, authorization, security
---

## Protect OAuth Code Flow Vs CSRF

Without state parameter validation, attackers can use their own authorization codes to link their accounts to a victim's session.

**Incorrect (no state parameter):**

```go
func OAuthInitHandler(w http.ResponseWriter, r *http.Request) {
    url := fmt.Sprintf("https://accounts.google.com/o/oauth2/auth?client_id=%s&redirect_uri=%s&response_type=code", clientID, redirectURI)
    // No state parameter!
    http.Redirect(w, r, url, http.StatusFound)
}
```

**Correct (state parameter validation):**

```go
func OAuthInitHandler(w http.ResponseWriter, r *http.Request) {
    state := generateRandomState() // CSPRNG
    
    // Store in session (cookie or DB)
    session := getSession(r)
    session.Values["oauth_state"] = state
    session.Save(r, w)
    
    url := googleConfig.AuthCodeURL(state)
    http.Redirect(w, r, url, http.StatusFound)
}

func OAuthCallbackHandler(w http.ResponseWriter, r *http.Request) {
    queryState := r.URL.Query().Get("state")
    session := getSession(r)
    
    // Validate state
    if queryState == "" || queryState != session.Values["oauth_state"] {
        http.Error(w, "Invalid state", 403)
        return
    }
    
    // Exchange code for token
}
```

**Tools:** `golang.org/x/oauth2`, Security Audit
