
Keycloak Identity Provider Federation: Bridging Multiple IdPs
An examination of Keycloak identity provider federation and how to bridge multiple SAML and OIDC brokers for unified access.
When an application requires authentication from disparate sources—such as a corporate Active Directory via SAML and a public Google account via OIDC—the naive approach of hardcoding provider logic in the application layer creates a fragile architecture. Every new identity provider necessitates code changes and maintenance. Keycloak resolves this by acting as a protocol bridge. It does not merely pass tokens; it normalizes them. The core mechanism is the "Broker" provider, which allows Keycloak to act as a Service Provider (SP) for an upstream IdP while simultaneously serving as an Identity Provider (IdP) for downstream applications. This Part 9 of the Keycloak Masterclass Series explores how to leverage this pattern to unify access across systems.
The Broker Mechanism: Normalization Over Translation
In a federated setup, Keycloak sits logically between the user and the application. When a user attempts to log in, the application redirects the browser to Keycloak. Keycloak then intercepts the request and checks if the user has selected an external identity provider. If they have, Keycloak initiates a secondary authentication flow with that specific provider.
The critical distinction here is that Keycloak does not simply forward the authentication result. It performs a "mapping" operation. Upon successful authentication with the upstream provider (e.g., Google), Keycloak receives a response containing user attributes. It then queries its own user database to see if a user exists with a matching identifier. If no match exists, Keycloak can automatically provision a new user in its local realm. If a match exists, it links the external identity to the local user record. This process happens transparently, allowing the application to authenticate against a single set of credentials regardless of the source.
This mechanism relies on the concept of a "linking strategy." By default, Keycloak uses the email address as the unique identifier to link accounts. However, this is configurable. If you configure the SAML broker to use the NameID format and the OIDC broker to use the sub claim, Keycloak must have a strategy to reconcile these if they refer to the same human. Without this bridging logic, the system treats the SAML user and the OIDC user as two distinct entities, even if they are the same person.
SAML as a Broker: The Assertion Bridge
Configuring a SAML Identity Provider in Keycloak involves transforming Keycloak into a SAML Service Provider. This is a distinct architectural role from the standard SAML Identity Provider mode. In this mode, Keycloak holds a private key and certificate, and it expects to receive a signed SAML Assertion from the upstream IdP.
When a user authenticates via a SAML broker, the following mechanism occurs:
- Redirect: Keycloak redirects the browser to the upstream IdP's SSO endpoint.
- Assertion: The upstream IdP returns a SAML Response containing a signed Assertion. This assertion includes attributes like
email,name, andgroups. - Validation: Keycloak validates the digital signature using the configured public certificate.
- Mapping: Keycloak extracts the attributes from the XML Assertion and maps them to its internal user model.
The configuration in the Keycloak console requires specifying the SAML metadata URL or manually entering the Single Sign-On Service URL and Entity ID of the upstream provider. A common pitfall in this mechanism is the handling of the NameID. If the upstream SAML provider sends a transient NameID that changes on every login, Keycloak cannot link the user to an existing record. The upstream provider must send a persistent NameID (usually the email or a stable GUID) for the linking mechanism to work reliably.
<!-- Example of a SAML Assertion attribute that Keycloak maps -->
<saml:Attribute Name="email" FriendlyName="email">
<saml:AttributeValue>user@example.com</saml:AttributeValue>
</saml:Attribute>Keycloak then uses a SAML User Attribute Mapper to define how these XML attributes map to the internal user fields. If the upstream provider does not send the email, and the linking strategy relies on email, the user creation will fail or create a duplicate account.
OIDC as a Broker: The Token Bridge
The OIDC broker operates on a different mechanism than SAML, relying on JSON Web Tokens (JWT) rather than XML Assertions. When Keycloak acts as an OIDC client for an upstream provider, it initiates an OAuth 2.0 Authorization Code Grant flow.
The flow proceeds as follows:
- Initiation: Keycloak redirects the user to the upstream OIDC provider's authorization endpoint with a
client_idandredirect_uri. - Token Exchange: After the user authenticates with the upstream provider, they are redirected back to Keycloak with an authorization code. Keycloak exchanges this code for an Access Token and an ID Token.
- Discovery: Keycloak parses the ID Token. This token contains claims (attributes) about the user.
- Mapping: Keycloak uses a
User Attribute Mapperto extract specific claims (e.g.,email,given_name,family_name) from the JWT and populate the local user record.
The primary difference in mechanism is the state management. While the SAML Assertion payload itself is self-contained and stateless, the protocol flow relies heavily on stateful mechanisms like RelayState parameters, SAML artifacts, or browser session binding to link specific requests to their responses. In contrast, OIDC explicitly mandates the state parameter during the initial redirect to prevent CSRF attacks, providing a more standardized approach to state correlation between the browser and the provider. Furthermore, OIDC allows for dynamic attribute discovery via the UserInfo endpoint if the ID Token does not contain all necessary claims.
A critical tradeoff in the OIDC broker mechanism is the reliance on the upstream provider's claim stability. Unlike SAML, where the schema is rigid, OIDC claims are flexible. If a provider changes the claim name for email from email to user_email, the Keycloak configuration must be updated immediately, or the mapping breaks. This flexibility is a double-edged sword: it allows for rich data integration but increases the risk of configuration drift.
Bridging and User Linking: The Merge Logic
The most complex part of federation is the "Bridging" phase—connecting a user who has previously logged in via SAML to a new login via OIDC. Keycloak handles this through the "First Broker Login Flow."
When a user logs in via a new broker, Keycloak checks if a local user exists with the identifier provided by the broker.
- Scenario A: The user enters
alice@example.comvia Google OIDC. Keycloak looks for a user withemail = alice@example.com. - Scenario B: If found, Keycloak links the
google.comidentity to the existing user record. The user now has two linked identities. - Scenario C: If not found, Keycloak prompts the user to link the new identity to an existing account. This usually involves asking the user to enter their username and password to prove ownership of the local account before linking.
This mechanism prevents account fragmentation. However, it introduces a dependency on the uniqueness of the attribute used for linking. If you use email, and a user has two emails (one for work, one for personal), the system might merge accounts incorrectly. Conversely, if you use a sub (subject) claim from OIDC, it is unique to that provider but useless for linking to a SAML user unless there is a cross-provider registry.
In practice, the most robust strategy is to enforce a "primary" identifier. For example, configure both the SAML and OIDC brokers to map their respective attributes to the email field in Keycloak. This ensures that regardless of the protocol, the lookup key remains consistent. Regarding synchronization frequency, Keycloak's default behavior updates the local user record on every successful login if the attribute is marked as "Update on every login." This ensures data freshness but requires strict consistency checks on upstream data to avoid "toggling" issues where conflicting attribute values overwrite each other on successive logins.
Configuration and Tradeoffs
Configuring multiple brokers requires careful management of the "Trust" relationship. Every broker adds a round-trip to the authentication flow. A SAML login involves a redirect, an XML handshake, and a validation step. An OIDC login involves a redirect, a token exchange, and a claim parsing step. This adds latency, typically 200–500ms per broker interaction.
From a security perspective, the broker model shifts the trust boundary. Keycloak trusts the upstream provider to accurately report the user's identity. If the upstream SAML provider is compromised, the attacker can impersonate any user whose identity they can forge. Therefore, the configuration of the SAML broker must strictly enforce signature validation and clock skew tolerance settings. Similarly, for OIDC, the Client Secret must be rotated regularly, and the redirect_uri must be whitelisted to prevent open redirect vulnerabilities.
There is also a data consistency tradeoff. If an attribute is updated in the upstream provider (e.g., a user changes their name), Keycloak must decide whether to update the local user record. Keycloak's default behavior is to update the local record on every login if the attribute is marked as "Update on every login." This ensures data freshness but can lead to "toggling" issues if the upstream provider sends inconsistent data.
Finally, consider the operational overhead. Managing a SAML broker requires maintaining certificates and metadata URLs. Managing an OIDC broker requires managing client secrets and scopes. As you add more brokers, the complexity of the "First Broker Login Flow" increases. You must ensure that the user experience remains smooth; otherwise, users may abandon the login process if they are asked to link accounts unexpectedly.
Common Pitfalls
- NameID Persistence Failures: Relying on transient
NameIDformats in SAML brokers often leads to broken user linking. If the upstream IdP generates a new anonymous identifier on every session, Keycloak cannot associate the login with an existing local user, resulting in duplicate accounts. Always configure upstream providers to issue persistentNameIDvalues (e.g.,urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress). - Claim Mapping Drift: OIDC providers frequently update their claim schemas. A change in the upstream provider from
emailtouser_emailorpreferred_usernamebreaks the Keycloak mapping without warning. Implement monitoring for attribute changes and maintain a strict version control policy for your broker configurations to detect these drifts early. - Latency Accumulation: While a single broker adds ~200ms, chaining multiple brokers or adding complex attribute mappers can push total authentication time beyond user tolerance thresholds. In high-traffic environments, this latency compounds, leading to perceived slowness. Profile your flows and consider caching strategies or reducing the number of attributes requested during the initial handshake.
Practical Takeaways
- Consistency is Key: Define a canonical "linking key" (usually email) at the design phase and enforce it across all broker configurations. Do not rely on provider-specific IDs like
suborNameIDfor cross-broker linking unless you have a pre-existing mapping table. - Validate Before Linking: Always test the "First Broker Login Flow" with a user account that exists in one provider but not the other. Verify that the linking prompt appears correctly and that the final user profile merges attributes as expected.
- Monitor Upstream Health: Treat upstream IdPs as external dependencies. If an IdP changes its certificate, metadata, or claim structure, your federation breaks immediately. Set up alerts for certificate expiration and monitor upstream availability.
FAQ
Q: Can I link a SAML user and an OIDC user if they use different email addresses?
A: Not automatically. Keycloak relies on matching identifiers defined in the mapping configuration. If a user has alice@corp.com in SAML and alice@gmail.com in OIDC, Keycloak will create two separate accounts. You must manually merge them in the Admin Console or configure a custom mapper to normalize these addresses to a single canonical value before linking.
Q: How does Keycloak handle session timeouts between the upstream IdP and the broker? A: The upstream IdP may expire the user's session before they complete the redirect back to Keycloak. Keycloak's broker flow will typically fail with an authentication error in this scenario. It is best practice to align the session timeout of the upstream IdP with the expected duration of the Keycloak redirect flow, or to configure the IdP to allow longer session durations for federated users.
Q: Is it possible to disable the "First Broker Login Flow" prompt? A: Yes, but it requires careful planning. You can configure the broker to automatically create a new user if no match is found, or to reject the login entirely. However, disabling the prompt removes the ability for users to merge accounts they inadvertently split, often leading to fragmented identity data. It is generally recommended to keep the prompt active unless you have a strict provisioning workflow.
Conclusion
Keycloak's broker mechanism transforms a fragmented identity landscape into a unified access layer. By normalizing SAML assertions and OIDC tokens into a common user model, it allows applications to authenticate users without knowing the underlying protocols. The tradeoff is increased configuration complexity and reliance on stable upstream attributes, but the benefit of a single pane of glass for identity management is significant.
Related posts
Social Login with OIDC: Google, GitHub & Microsoft
An examination of implementing social login using OpenID Connect with Google, GitHub, and Microsoft via Keycloak for federated identity management.
Spring Security SAML Extension: Enterprise SSO Integration
This guide covers enterprise SSO integration using Spring Security SAML, SAML service provider setup, and Spring SAML migration strategies.
Keycloak Production: TLS, DB Tuning & K8s
A step-by-step guide to deploying Keycloak in production environments using Docker and Kubernetes with SSL and monitoring.