JWT Audience Separation¶
SystemForge supports audience-aware JWT tokens to distinguish between BFF (web browser) and API (programmatic) clients. This enables strict path separation and prevents token misuse.
Why Audience Separation?¶
Without audience validation, a token obtained for the web UI could be used against the API directly, bypassing CSRF protection. Audience claims solve this:
| Client Type | Audience | Transport | CSRF Protected |
|---|---|---|---|
| Web Browser | bff |
HTTP-only cookie | Yes |
| API Client | api |
Bearer header | No (uses scopes) |
Web App API Client
│ │
│ POST /bff/login │ POST /api/tokens
│ │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ JWT │ │ JWT │
│ aud: "bff" │ │ aud: "api" │
│ no scopes │ │ scopes: [...]│
└──────────────┘ └──────────────┘
│ │
│ Cookie only accepted │ Bearer only accepted
│ on /bff/* routes │ on /api/* routes
▼ ▼
┌──────────────┐ ┌──────────────┐
│ BFF Handler │ │ API Handler │
│ /bff/* │ │ /api/* │
└──────────────┘ └──────────────┘
Application Audience¶
Config.Audience names the application a jwt.Service issues tokens for and
is required: NewService returns ErrMissingAudience without it. Every token
the service mints carries it, and ValidateAccessToken and
ValidateRefreshToken refuse tokens that do not, so applications that share a
signing key do not accept each other's tokens.
cfg := jwt.DefaultConfig()
cfg.Secret = secret // at least 32 bytes for HS256 (48 for HS384, 64 for HS512)
cfg.Issuer = "https://auth.my-app.example" // required
cfg.Audience = []string{"my-app"}
jwtService, err := jwt.NewService(cfg)
NewService also requires Issuer (ErrMissingIssuer) and an HMAC secret
at least as long as the hash output (ErrWeakSecret).
Key rotation¶
Set KeyID to put a kid header on every token. A token's kid selects the
verification key: KeyID selects the signing key, an entry in
VerificationKeys selects that key, and any other kid is rejected. Tokens
without a kid are verified with the signing key, so give the current key a
KeyID first and wait until tokens issued without one have expired (the
refresh token lifetime) before the first rotation.
Rotation keeps two keys valid: the signing key N and the previous key N-1 in
VerificationKeys. Only N-2 is removed. Each step is its own deploy, so
rolling back any deploy returns to a configuration that verifies every token
issued so far:
-
Steady state.
k1signs. -
Pre-stage
k2. Deployk2for verification only whilek1still signs, and wait until every instance runs it. -
Promote
k2.k2signs andk1(now N-1) stays for verification. Rolling this deploy back returns to step 2, which still verifies the tokensk2signed in the meantime. -
Next rotation. Pre-stage
k3withk1still listed ({"k1": k1, "k3": k3}), then promotek3with{"k2": k2}.k1is N-2 at that point and is the only key removed.
Never introduce a new signing key and drop the previous one in the same deploy: a rollback would then reject every token the new key signed.
The client-kind audiences below (bff, api) are added in front of the
application audience rather than replacing it, so a BFF token for my-app
carries aud: ["bff", "my-app"].
Constants¶
import "github.com/plexusone/systemforge/session/jwt"
// Audience constants
const (
jwt.AudienceBFF = "bff" // Web browser clients
jwt.AudienceAPI = "api" // Programmatic clients
)
Generating Tokens with Audience¶
BFF Tokens (Web Clients)¶
import (
"github.com/plexusone/systemforge/session/jwt"
)
jwtService, _ := jwt.NewService(cfg)
// Generate BFF token pair (no scopes)
tokenPair, err := jwtService.GenerateBFFTokenPair(
userID,
email,
name,
)
// tokenPair.AccessToken has aud: ["bff", "my-app"]
API Tokens (Programmatic Clients)¶
// Generate API token (requires scopes)
apiToken, err := jwtService.GenerateAPIToken(
userID,
email,
name,
[]string{"read:users", "write:projects"},
90 * 24 * time.Hour, // 90 days
)
// apiToken has aud: ["api", "my-app"] and scopes
Custom Audience¶
// For custom audiences (e.g., mobile apps, service-to-service)
accessToken, err := jwtService.GenerateAccessTokenWithAudience(
userID,
email,
name,
"mobile",
[]string{"read:*"},
)
Validating Tokens with Audience¶
Standard Validation (Application Audience)¶
// Accepts any kind of token addressed to this application (Config.Audience)
claims, err := jwtService.ValidateAccessToken(tokenString)
Audience-Aware Validation¶
// Strict - requires matching audience
claims, err := jwtService.ValidateAccessTokenWithAudience(
tokenString,
jwt.AudienceBFF, // Expected audience
)
if errors.Is(err, jwt.ErrAudienceMismatch) {
// Token has wrong audience
return http.StatusForbidden
}
Claims Helper Methods¶
The Claims struct provides helper methods for audience handling:
// Get first audience value
aud := claims.Audience() // "bff" or "api"
// Check for specific audience
if claims.HasAudience("bff") {
// Token is for BFF client
}
// Set audience (builder pattern)
claims.WithAudience("bff")
claims.WithAudience("api", "mobile") // Multiple audiences
Middleware Integration¶
BFF Middleware¶
func BFFAuthMiddleware(jwtService *jwt.Service) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get token from cookie
cookie, err := r.Cookie(bff.DefaultCookieName)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
// Validate with BFF audience
claims, err := jwtService.ValidateAccessTokenWithAudience(
cookie.Value,
jwt.AudienceBFF,
)
if err != nil {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
ctx := WithClaims(r.Context(), claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
API Middleware¶
func APIAuthMiddleware(jwtService *jwt.Service) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get token from Authorization header
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
token := strings.TrimPrefix(auth, "Bearer ")
// Validate with API audience
claims, err := jwtService.ValidateAccessTokenWithAudience(
token,
jwt.AudienceAPI,
)
if err != nil {
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
ctx := WithClaims(r.Context(), claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
Errors¶
var (
// ErrAudienceMismatch is returned when token audience doesn't match expected
jwt.ErrAudienceMismatch = errors.New("audience mismatch")
// ErrScopesRequired is returned when API tokens are created without scopes
jwt.ErrScopesRequired = errors.New("at least one scope is required for API tokens")
)
Migration Guide¶
From Non-Audience Tokens¶
-
Update token generation to include audience:
-
Update validation (optional, for strict enforcement):
-
Existing tokens without audience will:
- Pass
ValidateAccessToken()(backward compatible) - Fail
ValidateAccessTokenWithAudience()(strict mode)
Rollout Strategy¶
- Deploy with audience in new tokens, but don't validate audience yet
- Monitor for any issues with new tokens
- After token rotation period (refresh token lifetime), enable strict audience validation
- Remove backward compatibility code
Security Considerations¶
- Always validate audience on security-sensitive endpoints
- Use short-lived access tokens with refresh for BFF clients
- Require scopes for all API tokens
- Log audience mismatches for security monitoring
- Don't accept BFF tokens via Bearer header - they should only come from cookies