Is this even possible? 🤔
Single Sign-On (SSO) sounds simple on paper—"sign in once, access everything"—until your application has to speak OAuth 2.0 to one identity provider, OpenID Connect (OIDC) to three more, SAML 2.0 XML assertions to an enterprise IdP, and maybe legacy credentials to a directory on top of that. Scatter if/else or switch statements across routes, middleware, and templates, and every new provider turns into a maintenance and security hazard.
In this walkthrough, we explore the Universal SSO Sample Implementation—a pluggable authentication architecture built in Go (pkg/sso and cmd/ssod) alongside multi-language client examples (Python, Go, Java, C#, and Rust) that consume the gateway cleanly without coupling application code to vendor quirks.
Introduction: How Single Sign-On Works Across Protocol Families
Enterprise and consumer identity systems rarely converge on a single protocol. Even within one organization, cloud-native apps, legacy enterprise directories, and partner federations often coexist side by side. Understanding how these SSO families differ is the first step toward hiding their complexity behind a uniform contract.
Common SSO & Authentication Families
| SSO / Auth Family | Typical Environments | Interaction & Trust Model | Key Trade-Offs & Pitfalls |
|---|---|---|---|
| OAuth 2.0 & OpenID Connect (OIDC) | Modern web apps, SaaS, Google, Okta, Auth0, Microsoft Entra ID | Browser redirects with authorization codes, PKCE (S256), state & nonce validation, token exchange, and OIDC ID token / userinfo retrieval | Requires strict token/claim verification, HTTPS endpoints, and replay protection |
| SAML 2.0 | Enterprise IdPs (Entra ID / ADFS, Okta SAML, Keycloak, legacy corporate SSO) | SP-initiated redirect or HTTP-POST bindings carrying XML AuthnRequest and signed SAMLResponse assertions | Complex XML signature & canonicalization rules; vulnerable to XXE, signature wrapping, and replay if misconfigured |
| LDAP / Directory Bind | On-premises directories, legacy internal apps | Application collects credentials (or federates via an IdP) and performs directory search & bind | Exposes credentials to the caller unless federated; requires ldaps:///StartTLS, input escaping, and anti-enumeration controls |
| Decentralized / Emerging Identity | Verifiable credentials / emerging identity standards | Cryptographic identity assertions beyond centralized IdP silos | Still evolving in enterprise adoption; outside the core Go gateway scope today |
Why Monolithic Wiring Breaks Down
When applications wire each identity provider directly into HTTP routes and session handlers, a few predictable problems emerge:
Conditional sprawl: Protocol-specific branching leaks into controllers, error handlers, and UI templates.
Inconsistent security enforcement: One route checks
stateor validates claims thoroughly while another skips a check or logs sensitive data.Fragile testing and vendor lock-in: Swapping or adding an IdP requires code surgery across multiple files rather than configuration and adapter registration.
A pluggable SSO architecture inverts those dependencies: applications depend on a core orchestrator and a standard provider interface, while each protocol or vendor lives behind an isolated adapter.
Implementation: Go Core, Gateway (ssod), and Multi-Language Clients
The Universal SSO codebase (link provided) splits cleanly into a reusable Go library (pkg/sso), an HTTP gateway daemon (cmd/ssod), and client examples across multiple languages (examples/).
High-Level Architecture & Login Sequence
At the heart of pkg/sso is the Manager, which coordinates a StateSigner (HMAC-SHA256 signed, expiring state), a Cache (MemoryCache by default) for pending login state, PKCE verifiers, and nonces, and concrete Provider adapters (mock, google, oidc base with okta, auth0, and entra wrappers, oauth2, and saml).
When a sign-in starts, BeginLogin generates a signed state, a nonce, and a PKCE code_verifier, stores the pending login record in Cache under a TTL, and asks the selected Provider for the authorization URL (including the S256 code_challenge). When the IdP redirects back to /auth/{provider}/callback, CompleteLogin verifies the signature and expiry, looks up and deletes the cached entry for one-time consumption, confirms the providerID matches, and delegates token/assertion verification to the adapter.
Core Go Contracts, State/PKCE, and Gateway Wiring
- The
sso.ProviderContract: rather than relying on runtime "must override" exceptions alone, Go's interface system enforces that every adapter implements the contract at compile time. Where a protocol does not support an operation (such as token refresh or revocation in SAML), the adapter explicitly returnsUNSUPPORTED_METHOD.
type Provider interface { ID() string Name() string Protocol() ProtocolType GetAuthURL(ctx context.Context, req AuthURLRequest) (*AuthURLResponse, error) HandleCallback(ctx context.Context, req CallbackRequest) (*IdentityResult, error) ValidateToken(ctx context.Context, tokenString string) (*Claims, error) RefreshToken(ctx context.Context, refreshToken string) (*TokenResponse, error) RevokeToken(ctx context.Context, tokenString string) error GetLogoutURL(ctx context.Context, req LogoutRequest) (*LogoutURLResponse, error) FetchUserInfo(ctx context.Context, accessToken string) (*UserInfo, error) } - Signed State, One-Time Cache Consumption, and PKCE: replay attacks, CSRF, and authorization code interception are classic SSO pitfalls.
Manager.BeginLoginandManager.CompleteLoginkeep sensitive parameters likeCodeVerifierandNoncein server-side cache rather than exposing them to the browser, whileStateSignerproduces HMAC-SHA256 signed tokens checked with constant-time comparison.
// Inside Manager.BeginLogin: state, err := m.signer.Sign() nonce, err := RandomString(16) verifier, err := NewCodeVerifier() data, err := json.Marshal(pendingLogin{ ProviderID: providerID, Nonce: nonce, CodeVerifier: verifier, }) if err := m.cache.Set(ctx, CacheKey(statePrefix, state), data, m.stateTTL); err != nil { return nil, err } req.State, req.Nonce, req.CodeVerifier = state, nonce, verifier return p.GetAuthURL(ctx, req) - Callback completion: on callback completion,
CompleteLoginvalidates the signature and expiry, consumes the cached state before token exchange, binds the state to the expectedproviderID, and passes the storedCodeVerifierandNonceto the adapter:
if err := m.signer.Verify(cb.State); err != nil { return nil, err } data, found, err := m.cache.Get(ctx, key) if !found { return nil, ErrStateInvalid("unknown or already used state") } if err := m.cache.Delete(ctx, key); err != nil { return nil, err } if pending.ProviderID != providerID { return nil, ErrStateInvalid("state issued for a different provider") } cb.CodeVerifier, cb.Nonce = pending.CodeVerifier, pending.Nonce return p.HandleCallback(ctx, cb) - Gateway HTTP Endpoints (
cmd/ssod): thessodgateway wiresManagerfrom environment variables (requiring a strongSSO_STATE_SECRETof at least 32 bytes and enabling configured providers likegoogle,okta,auth0,azure,oauth2, andsamlalongsidemock). ItsGET /auth/{provider}/loginhandler starts the flow and redirects the client, while/auth/{provider}/callback(GETfor OAuth/OIDC,POSTfor SAML ACS) completes authentication and returns{provider_id, user}as JSON without leaking tokens to the browser.
Consuming the Gateway from Client Applications
One practical advantage of separating ssod from client applications is that callers in Python, Go, Java, C#, or Rust don't need OIDC or SAML SDKs just to initiate a login or verify gateway health and provider availability.
- Python Client (
cli.py&client.py): The Python CLI (python -m sso_client check | login [--follow]) uses a standard-library HTTP opener with_NoRedirectso every redirect hop can be inspected against URL/host safety policies before following.
def start_login(self) -> Login: path = "/auth/" + urllib.parse.quote(self.cfg.provider, safe="") + "/login" status, location, body = self._get(self.cfg.endpoint(path)) if status not in (302, 303): raise self._api_error(status, body) if not location: raise TransportError("gateway redirect has no Location header") target = urllib.parse.urljoin(self.cfg.gateway_url + "/", location) state = check_authorize_url(target, self.cfg.gateway_url, self.cfg.expected_idp_host) log.info("login started provider=%s idp_host=%s", self.cfg.provider, urllib.parse.urlsplit(target).netloc) return Login(target, state) - Go SAML Client (
main.go): thesaml2-goexample client supportscheck,login, andlogin -follow(for local mock flows), using structured logging (log/slog), signal cancellation, and typed gateway error checks (gateway.APIError,gateway.ErrPolicy,gateway.ErrLeavesGateway).
func cmdLogin(ctx context.Context, c *gateway.Client, follow bool, stdout, stderr io.Writer) int { l, err := c.StartLogin(ctx) if err != nil { return reportLoginError(err, stderr) } if !follow { fmt.Fprintln(stdout, "Open this URL in a browser to sign in:") fmt.Fprintln(stdout, l.AuthorizeURL.String()) fmt.Fprintln(stdout, "The identity provider returns the browser to the gateway callback, which completes the login.") return 0 } p, err := c.FollowLocal(ctx, l) if err != nil { if errors.Is(err, gateway.ErrLeavesGateway) { fmt.Fprintln(stderr, err) return 1 } return reportLoginError(err, stderr) } fmt.Fprintf(stdout, "signed in via %s as %s (%s)\n", p.ProviderID, p.User.DisplayName, p.User.Email) return 0 } - Java & C# Configuration and CLI Entry Points (
Config.java/Main.javaandConfig.cs/Program.cs): across the Java and C# clients, configuration parsing enforces consistent guardrails before any network call happens: validatinghttp/httpsschemes, rejecting plainhttpon non-loopback hosts, validating provider IDs (^[a-z0-9_-]{1,64}$), and bounding HTTP timeouts (1..300seconds).
String scheme = uri.getScheme(); if (uri.getHost() == null || scheme == null || !(scheme.equals("http") || scheme.equals("https"))) { throw new ConfigException("SSO_GATEWAY_URL must be an http(s) URL with a host"); } if (scheme.equals("http") && !LOOPBACK.contains(uri.getHost())) { throw new ConfigException("SSO_GATEWAY_URL uses plain http for a non-loopback host: use https"); } - C# client: the C# client mirrors that same configuration contract and command lifecycle (
check,login,login --follow) with cancellation token propagation:
if (uri.Scheme == Uri.UriSchemeHttp && !uri.IsLoopback) { throw new ConfigException("SSO_GATEWAY_URL uses plain http for a non-loopback host: use https"); } var baseUrl = new Uri(uri.GetLeftPart(UriPartial.Authority) + uri.AbsolutePath.TrimEnd('/')); - Rust CLI Client (
main.rs): theoauth2-rustclient follows the exact same CLI semantics (check,login,login --follow), exiting with2on usage or configuration errors,1on gateway/policy/transport failures, and0on success—making it straightforward to run identical smoke checks across all example clients.
fn cmd_login(client: &Client, follow: bool, out: &mut dyn Write, err: &mut dyn Write) -> u8 { let login = match client.start_login() { Ok(l) => l, Err(e) => return report(&e, err), }; if !follow { let _ = writeln!(out, "Open this URL in a browser to sign in:"); let _ = writeln!(out, "{}", login.authorize_url); let _ = writeln!(out, "The identity provider returns the browser to the gateway callback, which completes the login."); return 0; } match client.follow_local(&login) { Ok(p) => { let _ = writeln!( out, "signed in via {} as {} ({})", p.provider_id, p.user.display_name, p.user.email ); 0 } Err(e) => report(&e, err), } } Hardening Lessons: Fixing Illustrative Sample Pitfalls
A big takeaway from comparing the conceptual pluggable SSO design against the hardened Go implementation and client wrappers is how many subtle bugs hide in "toy" SSO samples:
Never stub signature or claim checks: Forged SAML responses or unverified tokens/nonces/issuers/audiences defeat the whole point of SSO. The Go OIDC and SAML adapters enforce RS256/signature checks, issuer/audience/time-window checks (with clock skew bounds), nonce checks, and SAML replay caching.
Always bind
stateto the session/cache and provider: Accepting a provider name blindly from callback parameters or reusing state across providers opens the door to CSRF and confusion attacks.Enforce transport, timeout, and payload limits: Require
https(allowinghttponly on loopback), cap response bodies, set request timeouts, and avoid leaking tokens or secrets in logs or browser responses.
Conclusion: what is demonstrated
The Universal SSO Sample Implementation turns a conceptual pluggable SSO design into a working, testable foundation across both core authentication plumbing and multi-language client integration:
- Core abstraction & lifecycle orchestration (
pkg/sso): A compiler-checkedProviderinterface, driver registry,Manager(BeginLoginandCompleteLogin), HMAC-SHA256StateSigner, PKCE S256 generation,noncetracking, and aCacheabstraction withMemoryCache. - Multiple protocol & vendor adapters: A
mockprovider for offline testing, a standalonegoogleadapter, a sharedoidcbase poweringokta,auth0, andentra(azure), a genericoauth2adapter, and asamladapter with XML signature verification and replay checks. - HTTP gateway (
cmd/ssod) & multi-language clients (examples/): Environment-driven gateway wiring with startup guards and/healthz,/providers,/auth/{provider}/login, and/auth/{provider}/callbackendpoints, paired with Python, Go, Java, C#, and Rust client implementations. - Clear next steps on the roadmap: While single-instance fake-IdP flows and core protocol validation are in place, production multi-replica deployments, persistent/atomic shared caches, gateway session/logout routes, audit decorators, and optional LDAP federation remain tracked as next-stage backlog items.
Thanks for reading🗝️🔑
Links
- Code repository for this post: https://github.com/aairom/universal-sso








![[Kalamos Devlog] After Open-Sourcing: v0.2 to v0.7 Feature Evolution and Using Multi-Agents to Review External PRs](https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvo6aurmkktm5betltn9v.png)
