How do I work with SSO on Keycloak and Spring Security?

Recently, we conducted a Proof of Concept (POC) to assess the feasibility of implementing a centralized authentication model in our company. The main idea was to employ a single ‘REALM’ to authenticate various applications, adopting a dedicated client approach for each of them, and using Spring Security as the security framework. In case of need, each user would be associated with a specific client, providing efficient centralization for the entire business ecosystem.
However, we encountered an additional challenge: we already had a ‘REALM’ operating under the federation concept, connecting to the user base of our legacy system. It was then that the second objective of our POC arose: to explore the concept of ‘multi tenancy’, integrating Keycloak with Spring Security. During our internet research, we came across a repository that had apparently addressed this challenge before, offering a potential solution (GitHub - czetsuya/spring-keycloak-multi-tenant: This project demonstrates multi-tenancy in Keycloak by overriding the class KeycloakConfigResolver to load the keycloak json configuration file depending on the realm specified in the path in each request. The realm is information is cache, so it's only loaded once per login.). However, upon further examination, we identified that the version of Keycloak used was quite outdated.
Thus, the question arises: how can we implement this Single Sign-On (SSO) across multiple ‘REALMs’ using Java applications effectively and compatible with the latest versions of Keycloak?

The question subject says something, but the question explanation says something else. Therefore, I will answer some of them.

  • SSO basically uses the IdP cookie :cookie:. Regardless of the OIDC SDK, the idea behind the scenes is the same, based on the OpenID Connect standard.
  • Multi-tenancy: First, you have to be clear about how many kinds of identities you are handling. If both IdPs are handling the same identity, perhaps it will help to have one IdP for many reasons (that I will not detail here)