Backend & Cloud Engineer Guide: RFC 8693 OAuth2 Token Exchange Gateway in Go
Forwarding a raw external user access token across five internal microservices is a major security anti-pattern: if a downstream analytics service is compromised, the attacker can replay that broad-scoped user token against your core billing or account APIs. Conversely, using a static service-to-service API key loses the calling user's identity and audit trail. As a backend engineer and cloud engineer, I implement RFC 8693 OAuth 2.0 Token Exchange in Go to swap external tokens for short-lived, audience-restricted internal JWTs with explicit act (actor) delegation claims.
1. RFC 8693 Token Exchange with Audience & Scope Downscoping in Go
When the API gateway or an orchestrator service calls an upstream microservice, it exchanges the subject token for a narrow 60-second internal JWT bound strictly to the target upstream service's aud claim:
// auth/token_exchange.go
package auth
import (
"crypto/ed25519"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
type ActorClaim struct {
Subject string `json:"sub"`
}
type InternalExchangeClaims struct {
jwt.RegisteredClaims
TenantID string `json:"tenant_id"`
Scope string `json:"scope"`
Actor ActorClaim `json:"act"`
}
func ExchangeForInternalToken(
signingKey ed25519.PrivateKey,
subjectUserID, tenantID, callerServiceID, targetAudience, narrowedScope string,
) (string, error) {
now := time.Now().UTC()
claims := InternalExchangeClaims{
RegisteredClaims: jwt.RegisteredClaims{
Issuer: "https://sts.internal.aldianfazrihady.com",
Subject: subjectUserID,
Audience: jwt.ClaimStrings{targetAudience},
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now.Add(-5 * time.Second)),
ExpiresAt: jwt.NewNumericDate(now.Add(60 * time.Second)),
},
TenantID: tenantID,
Scope: narrowedScope,
Actor: ActorClaim{Subject: fmt.Sprintf("spiffe://prod/ns/core/sa/%s", callerServiceID)},
}
token := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims)
token.Header["kid"] = "sts-ed25519-2026-11"
return token.SignedString(signingKey)
}
2. Preventing Confused Deputy Attacks Across Microservices
Because the exchanged token embeds both sub (the human end-user), act.sub (the immediate calling microservice identity), and a single-service aud (e.g., https://ledger.internal), the ledger service rejects any token originally minted for the notification service.