netbirdio/netbird · error
Failed to exchange code for token
Error message
Failed to exchange code for token
What it means
Fires in handleCallback when the OAuth2 authorization code exchange with the IdP fails — the code is expired, already used, forged, the PKCE code_verifier does not match, or the IdP is unreachable. The handler logs the underlying reason server-side and returns a generic 500 to the client so error details are not leaked.
Solutions
- Read the server log line with log.WithError for the specific oauth2 error (invalid_grant, invalid_code, network failure)
- Have the user restart the login flow — a stale or replayed authorization code cannot be reused
- Verify the OIDC issuer, ClientID, and CallbackURL configuration match the IdP registration
- Check clock skew and IdP availability if exchanges fail systematically
Defensive patterns
Strategy: try-catch
When it happens
Trigger: Thrown at management/server/http/handlers/proxy/auth.go:92 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of netbirdio/netbird@93e97f4bf1 (2026-08-16).
Data as JSON: /api/errors/84f8c3496160b5b2.
Report an issue: GitHub.
Appendix: source
Thrown at management/server/http/handlers/proxy/auth.go:92
}
oidcConfig := h.proxyService.GetOIDCConfig()
provider, err := oidc.NewProvider(r.Context(), oidcConfig.Issuer)
if err != nil {
log.WithError(err).Error("Failed to create OIDC provider")
http.Error(w, "Failed to create OIDC provider", http.StatusInternalServerError)
return
}
token, err := (&oauth2.Config{
ClientID: oidcConfig.ClientID,
Endpoint: provider.Endpoint(),
RedirectURL: oidcConfig.CallbackURL,
}).Exchange(r.Context(), r.URL.Query().Get("code"), oauth2.VerifierOption(codeVerifier))
if err != nil {
log.WithError(err).Error("Failed to exchange code for token")
http.Error(w, "Failed to exchange code for token", http.StatusInternalServerError)
return
}
userID := extractUserIDFromToken(r.Context(), provider, oidcConfig, token)
if userID == "" {
log.Error("Failed to extract user ID from OIDC token")
http.Error(w, "Failed to validate token", http.StatusUnauthorized)
return
}
// Group validation is performed by the proxy via ValidateSession gRPC call.
// This allows the proxy to show 403 pages directly without redirect dance.
sessionToken, err := h.proxyService.GenerateSessionToken(r.Context(), redirectURL.Hostname(), userID, auth.MethodOIDC)
if err != nil {
log.WithError(err).Error("Failed to create session token")
redirectURL.Scheme = "https"
query := redirectURL.Query()View on GitHub (pinned to 93e97f4bf1)