Federated auth
AppRegistrar, MintResourceToken, AdminAuth.
Source: docs/FEDERATED_AUTH.md
Federated Authentication ¶
OneAuth supports a federated authentication model where multiple Apps register with a central auth service, obtain credentials, and mint scoped JWTs that downstream resource servers (e.g., a WebSocket relay like massrelay) validate using a shared KeyStore.
Architecture Overview ¶
Three projects collaborate in a federated deployment:
- oneauth (this repo) — shared auth library + App Registration API
- Resource server (e.g., massrelay) — validates resource-scoped JWTs using KeyStore
- App (e.g., excaliframe) — registers as an App, authenticates users locally, mints resource tokens
flowchart LR
App["App<br/>(excaliframe)"]
AuthSrv["OneAuth Server<br/>(AppRegistrar)"]
EndUser["End User<br/>(browser)"]
ResSrv["Resource Server<br/>(APIMiddleware +<br/>KeyStore)"]
App -->|"1. register"| AuthSrv
AuthSrv -->|"client_id + secret"| App
App -->|"2. authenticate user locally<br/>3. mint resource-scoped JWT"| EndUser
AuthSrv -->|"shared KeyStore<br/>(GORM, FS, GAE)"| ResSrv
EndUser -->|"4. connect with JWT"| ResSrv
End-to-End Flow ¶
Step 1: App Registers with OneAuth Server ¶
The App sends an RFC 7591 Dynamic Client Registration request to the OneAuth server. Admin auth is optional on /apps/dcr — the endpoint can be configured open for self-service or behind X-Admin-Key for gated environments.
curl -X POST https://auth.example.com/apps/dcr \
-H "X-Admin-Key: your-admin-key" \
-H "Content-Type: application/json" \
-d '{
"client_name": "Excaliframe",
"client_uri": "https://excaliframe.com",
"signing_alg": "HS256"
}'
Response (201 Created):
{
"client_id": "app_a1b2c3d4e5f6",
"client_secret": "64-char-hex-string...",
"client_name": "Excaliframe",
"client_uri": "https://excaliframe.com",
"signing_alg": "HS256",
"registration_access_token": "rat_…",
"registration_client_uri": "https://auth.example.com/apps/dcr/app_a1b2c3d4e5f6",
"client_id_issued_at": 1710500000
}
The client_secret is stored in the KeyStorage and shared with the resource server. Application-domain quotas (max_rooms, max_msg_rate, etc.) are not OneAuth-core concerns post-issue 189 — the embedder maintains them in its own store keyed by client_id, subscribing to apiauth.ClientHooks.OnRegistered / OnDeleted to keep the embedder’s quota state in sync with OneAuth’s registrations.
Step 2: App Authenticates Users Locally ¶
The App uses its own authentication system (could be oneauth’s LocalAuth, OAuth, or anything else) to verify the user’s identity.
Step 3: App Mints a Resource Token ¶
After authenticating a user, the App mints a resource-scoped JWT using MintResourceToken:
import oa "github.com/panyam/oneauth"
token, err := oa.MintResourceToken(
"user-42", // userID (goes to JWT "sub" claim)
"app_a1b2c3d4e5f6", // appClientID (goes to "client_id" claim)
[]byte("64-char-hex-string"), // signing key — []byte → HS256
map[string]any{ // customClaims merged into the JWT
"max_rooms": 10,
"max_msg_rate": 30.0,
},
[]string{"relay:connect", "relay:publish"}, // scopes
nil, // RFC 9396 authorization_details
)
The resulting JWT contains:
{
"sub": "user-42",
"client_id": "app_a1b2c3d4e5f6",
"type": "access",
"scopes": ["relay:connect", "relay:publish"],
"max_rooms": 10,
"max_msg_rate": 30.0,
"iat": 1710500000,
"exp": 1710500900
}
Token TTL is 15 minutes, signed with HS256.
Step 4: User Connects to Resource Server ¶
The user presents the JWT when connecting to the resource server:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
Or via query parameter for WebSocket connections:
wss://relay.example.com/ws?token=eyJhbGciOiJIUzI1NiIs...
Step 5: Resource Server Validates the Token ¶
The resource server uses APIMiddleware with a shared KeyStore to validate:
middleware := &oa.APIMiddleware{
KeyStore: keyStore, // shared with OneAuth server
LegacyQueryParamBearer: "token", // legacy 2.0 path; see docs/DEMOS.md for header-clean WebSocket auth
}
mux.Handle("/ws", middleware.ValidateToken(wsHandler))
Validation flow:
- Parse token without verifying signature
- Extract
kidfrom JWT header (or fall back toclient_idfrom unverified payload) - Call
KeyStore.GetKeyByKid(kid)orKeyStore.GetKey(clientID)— returns*KeyRecord - Reject if JWT’s
algheader doesn’t matchrec.Algorithm - Verify JWT signature with
rec.Key - Store userID, scopes, and custom claims in request context
App Registration API ¶
The AppRegistrar provides a complete CRUD API for managing app registrations.
Setup ¶
import oa "github.com/panyam/oneauth"
registrar := &oa.AppRegistrar{
KeyStore: keyStore, // KeyStorage
Auth: oa.NewAPIKeyAuth("admin-secret"), // or oa.NewNoAuth() for dev
}
mux.Handle("/", registrar.Handler())
Endpoints ¶
All endpoints require admin authentication via X-Admin-Key header (when using APIKeyAuth).
Register App ¶
POST /apps/dcr
Content-Type: application/json
X-Admin-Key: admin-secret
{
"client_name": "MyApp",
"client_uri": "https://myapp.example.com",
"signing_alg": "HS256"
}
Returns 201 Created with client_id (format: app_<12-byte-hex>) and client_secret (32-byte hex).
List Apps ¶
GET /apps
X-Admin-Key: admin-secret
Returns JSON with "apps" key containing an array of AppRegistration objects (secrets are not included).
Get App ¶
GET /apps/{client_id}
X-Admin-Key: admin-secret
Returns the app’s metadata (secret not included).
Delete App ¶
DELETE /apps/{client_id}
X-Admin-Key: admin-secret
Removes the app and its key from the KeyStore. Existing tokens signed with the old secret will fail validation.
Rotate Secret ¶
POST /apps/{client_id}/rotate
X-Admin-Key: admin-secret
Generates a new client_secret, updates the KeyStore. Returns the new secret. Old tokens become invalid.
Error Responses ¶
| Status | Condition |
|---|---|
401 Unauthorized |
Missing X-Admin-Key header |
403 Forbidden |
Wrong admin key |
404 Not Found |
App not found |
405 Method Not Allowed |
Wrong HTTP method |
AdminAuth Interface ¶
Pluggable authentication for the App Registration API.
type AdminAuth interface {
Authenticate(r *http.Request) error
}
APIKeyAuth (Production) ¶
Reads X-Admin-Key header and compares using crypto/subtle.ConstantTimeCompare to prevent timing attacks.
auth := oa.NewAPIKeyAuth("your-secret-admin-key")
registrar := &oa.AppRegistrar{
KeyStore: keyStore,
Auth: auth,
}
NoAuth (Development Only) ¶
Allows all requests without authentication. Never use in production.
auth := oa.NewNoAuth()
MintResourceToken ¶
Helper function for Apps to mint resource-scoped JWTs after authenticating their users. One entry point covers HS256 / RS256 / ES256 — the signing alg is auto-selected from the Go type of signingKey:
| Go type | Alg |
|---|---|
[]byte |
HS256 |
*rsa.PrivateKey |
RS256 |
*ecdsa.PrivateKey |
ES256 |
func MintResourceToken(
userID string,
appClientID string,
signingKey any,
customClaims map[string]any,
scopes []string,
authzDetails []core.AuthorizationDetail,
) (string, error)
customClaims ride alongside the standard JWT claims (sub, iss, aud, exp, iat, type, scopes, jti, client_id, authorization_details). Any collision with that standard set is logged and dropped — the minter owns those keys.
Example: App-Side Token Minting ¶
func mintTokenForUser(w http.ResponseWriter, r *http.Request) {
// 1. Get the authenticated user from your session
userID := getLoggedInUserID(r)
// 2. Mint a resource token (HS256 — pass []byte)
token, err := oa.MintResourceToken(
userID,
os.Getenv("APP_CLIENT_ID"),
[]byte(os.Getenv("APP_CLIENT_SECRET")),
map[string]any{"max_rooms": 10, "max_msg_rate": 30.0},
[]string{"relay:connect"},
nil,
)
if err != nil {
http.Error(w, "failed to mint token", http.StatusInternalServerError)
return
}
// 3. Return the token to the client
json.NewEncoder(w).Encode(map[string]string{
"resource_token": token,
})
}
Multi-Tenant JWT Validation ¶
The resource server validates tokens from multiple apps using a shared KeyStore. See API_AUTH.md for the full KeyStore interface and validation details.
Key security feature: algorithm confusion prevention. The KeyRecord.Algorithm field ensures an app registered with HS256 can’t send a token with alg: none or alg: RS256.
KeyStore Implementations ¶
All persistent implementations satisfy KeyStorage (which embeds KeyLookup). Each stores KeyRecord values containing the client ID, key material, and algorithm. A shared test suite in keystoretest/ ensures consistent behavior.
| Implementation | Location | Use Case |
|---|---|---|
InMemoryKeyStore |
keystore.go |
Testing, simple deployments |
FSKeyStore |
stores/fs/ |
Single-node deployments |
GORMKeyStore |
stores/gorm/ |
Production (PostgreSQL, MySQL) |
GAEKeyStore |
stores/gae/ |
Google Cloud / serverless |
All minted JWTs include a kid header (RFC 7638 thumbprint), enabling GetKeyByKid() lookups without parsing unverified claims.
For store setup details, see STORES.md.
Reference Server ¶
The cmd/oneauth-server/ directory contains a config-driven reference server that bundles AppRegistrar, AdminAuth, and KeyStore wiring.
YAML Configuration ¶
server:
port: "8080"
host: "0.0.0.0"
keystore:
type: "gorm" # memory, fs, gorm, gae
gorm:
driver: "postgres"
dsn: "${DATABASE_URL:-postgres://localhost/oneauth}"
admin_auth:
type: "api-key" # none, api-key
api_key:
key: "${ADMIN_API_KEY}"
Environment variable substitution: ${VAR_NAME} or ${VAR_NAME:-default_value}.
Deployment Options ¶
| Platform | Details |
|---|---|
| GAE | go124 runtime, Secret Manager for admin key, /_ah/health endpoint |
| Docker | See cmd/oneauth-server/deploy-examples/ |
| Kubernetes | See cmd/oneauth-server/deploy-examples/ |
On GAE without a config file, the server falls back to configFromEnv() which reads all configuration from environment variables.
Complete Example: Three-Service Setup ¶
1. OneAuth Server (Central Auth) ¶
// cmd/oneauth-server wired with:
keyStore := gormstore.NewKeyStore(db)
adminAuth := oa.NewAPIKeyAuth(os.Getenv("ADMIN_API_KEY"))
registrar := &oa.AppRegistrar{KeyStore: keyStore, Auth: adminAuth}
mux.Handle("/", registrar.Handler())
2. App (e.g., Document Editor) ¶
// On startup: register with OneAuth server (or use pre-registered credentials)
clientID := os.Getenv("APP_CLIENT_ID")
clientSecret := os.Getenv("APP_CLIENT_SECRET")
// After authenticating a user locally:
func handleConnect(w http.ResponseWriter, r *http.Request) {
userID := getLoggedInUserID(r)
token, _ := oa.MintResourceToken(userID, clientID, []byte(clientSecret),
map[string]any{"max_rooms": 10},
[]string{"relay:connect", "relay:publish"},
nil)
json.NewEncoder(w).Encode(map[string]string{"resource_token": token})
}
3. Resource Server (e.g., WebSocket Relay) ¶
// Shares the same KeyStore as OneAuth server (or a read replica)
keyStore := gormstore.NewKeyStore(db)
middleware := &oa.APIMiddleware{
KeyStore: keyStore,
LegacyQueryParamBearer: "token", // legacy 2.0 path; see docs/DEMOS.md for header-clean WebSocket auth
}
mux.Handle("/ws", middleware.ValidateToken(func(w http.ResponseWriter, r *http.Request) {
userID := oa.GetUserIDFromAPIContext(r.Context())
scopes := oa.GetScopesFromAPIContext(r.Context())
custom := oa.GetCustomClaimsFromContext(r.Context())
maxRooms := int(custom["max_rooms"].(float64))
// ... proceed with scoped access
}))
Security Considerations ¶
- Admin key protection: Store the admin API key in a secrets manager (e.g., GCP Secret Manager). Use
APIKeyAuthin production, neverNoAuth. - Secret rotation: Use
POST /apps/{client_id}/rotateto rotate compromised secrets. Old tokens become invalid immediately. - Token lifetime: Resource tokens expire after 15 minutes. Apps should mint fresh tokens for each connection.
- Algorithm confusion:
KeyRecord.Algorithmprevents attacks where a token’salgheader is manipulated. - Constant-time comparison:
APIKeyAuthusescrypto/subtle.ConstantTimeCompareto prevent timing attacks on the admin key. - Encryption at rest: HS256 client secrets can be encrypted at rest using
EncryptedKeyStoragewith AES-256-GCM. SetONEAUTH_MASTER_KEY(64 hex chars) on all services sharing the same KeyStore DB. See JWT_SIGNING.md for details.
Asymmetric Signing (RS256/ES256) ¶
OneAuth supports asymmetric JWT signing alongside HS256. With asymmetric keys, apps keep their private key secret and register only the public key. Resource servers verify tokens using the public key without ever knowing the signing secret.
Quick example — register with RS256:
curl -X POST https://auth.example.com/apps/dcr \
-H "X-Admin-Key: your-admin-key" \
-H "Content-Type: application/json" \
-d '{
"client_name": "Excaliframe",
"client_uri": "https://excaliframe.com",
"token_endpoint_auth_method": "private_key_jwt",
"jwks": {
"keys": [{"kty": "RSA", "alg": "RS256", "n": "...", "e": "AQAB"}]
}
}'
Quick example — mint with asymmetric key:
privKey, _ := utils.ParsePrivateKeyPEM(privPEM)
token, err := oa.MintResourceToken("user-42", "app_abc", privKey, customClaims, scopes, nil)
For the full guide on key generation, algorithm selection, APIAuth configuration, key rotation, DecodeVerifyKey, and algorithm confusion prevention, see JWT_SIGNING.md.
JWKS Public Key Discovery ¶
Resource servers can auto-discover asymmetric public keys via a standard JWKS endpoint instead of sharing database access with the auth server.
Auth Server: Serving JWKS ¶
The oneauth-server exposes GET /.well-known/jwks.json — a public endpoint (no auth required) that returns all registered asymmetric keys (RS256/ES256) in JWK format. HS256 secrets are never included.
curl https://auth.example.com/.well-known/jwks.json
Response:
{
"keys": [
{
"kty": "RSA",
"kid": "app_a1b2c3d4e5f6",
"alg": "RS256",
"use": "sig",
"n": "0vx7agoebG...",
"e": "AQAB"
},
{
"kty": "EC",
"kid": "app_x9y8z7w6v5u4",
"alg": "ES256",
"use": "sig",
"crv": "P-256",
"x": "f83OJ3D2xF...",
"y": "x_FEzRu9m3..."
}
]
}
The response includes Cache-Control: public, max-age=3600 for efficient caching.
Resource Server: Fetching Keys via JWKS ¶
Instead of connecting to the auth server’s database, resource servers can use JWKSKeyStore:
keyStore := oa.NewJWKSKeyStore("https://auth.example.com/.well-known/jwks.json")
if err := keyStore.Start(); err != nil {
log.Fatal(err)
}
defer keyStore.Stop()
middleware := &oa.APIMiddleware{
KeyStore: keyStore,
}
JWKSKeyStore implements KeyLookup (read-only) with:
- Background refresh: Keys are re-fetched every hour (configurable via
WithRefreshInterval) - Cache-miss refresh: Unknown
client_idtriggers an immediate refresh attempt - Resilience: If the JWKS endpoint is down, cached keys continue to work
- Stampede protection:
MinRefreshGap(default 5s) prevents thundering herd on cache misses
Demo Resource Server with JWKS ¶
The demo resource server supports JWKS_URL as an alternative to DATABASE_URL:
# Before (shared database):
DATABASE_URL=postgres://... ./demo-resource-server
# After (JWKS — no database needed):
JWKS_URL=http://localhost:9999/.well-known/jwks.json ./demo-resource-server
Limitations ¶
- HS256 apps are not discoverable via JWKS — symmetric secrets cannot be safely exposed over HTTP. HS256 apps still require shared database access.
- JWKS is read-only —
JWKSKeyStoreimplementsKeyLookuponly, notKeyStorage. It cannot register or delete keys. - Propagation delay — newly registered asymmetric apps may take up to the refresh interval to appear in resource servers. Cache-miss refresh reduces this for initial lookups.
Protected Resource Metadata (RFC 9728) ¶
Resource servers can advertise their capabilities at GET /.well-known/oauth-protected-resource, enabling clients to auto-discover which authorization servers are trusted, what scopes are supported, and what token formats are accepted — without hardcoding.
meta := &apiauth.ProtectedResourceMetadata{
Resource: "https://relay.example.com",
AuthorizationServers: []string{"https://auth.example.com"},
ScopesSupported: []string{"relay:connect", "relay:publish"},
TokenFormatsSupported: []string{"jwt"},
SigningAlgsSupported: []string{"RS256", "ES256", "HS256"},
}
mux.Handle("GET /.well-known/oauth-protected-resource",
apiauth.NewProtectedResourceHandler(meta))
This completes the standards-based discovery chain: clients discover the resource server’s requirements via PRM, then discover the authorization server’s endpoints via OIDC Discovery or AS Metadata (RFC 8414), then obtain tokens and present them to the resource server.
See API_AUTH.md for the full API reference.