Implement multi-tenanted application with Keycloak and springboot

Viewed 3215

When we use 'KeycloakSpringBootConfigResolver' for reading the keycloak configuration from Spring Boot properties file instead of keycloak.json.

Now there are guidelines to implement a multi-tenant application using keycloak by overriding 'KeycloakConfigResolver' as specified in http://www.keycloak.org/docs/2.3/securing_apps_guide/topics/oidc/java/multi-tenancy.html.

The steps defined here can only be used with keycloak.json. How can we adapt this to a Spring Boot application such that keycloak properties are read from the Spring Boot properties file and multi-tenancy is achieved.

3 Answers

You can access the keycloak config you secified in your application.yaml (or application.properties) if you inject org.keycloak.representations.adapters.config.AdapterConfig into your component.

@Component
public class MyKeycloakConfigResolver implements KeycloakConfigResolver {

    private final AdapterConfig keycloakConfig;

    public MyKeycloakConfigResolver(org.keycloak.representations.adapters.config.AdapterConfig keycloakConfig) {
        this.keycloakConfig = keycloakConfig;
    }

    @Override
    public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
        // make a defensive copy before changing the config
        AdapterConfig currentConfig = new AdapterConfig();
        BeanUtils.copyProperties(keycloakConfig, currentConfig);

        // changes stuff here for example compute the realm

        return KeycloakDeploymentBuilder.build(currentConfig);
    }

}

After several trials, the only feasible option for spring boot is to have

  1. Multiple instances of the spring boot application running with different spring 'profiles'.
  2. Each application instance can have its own keycloak properties (as it is under different profiles) including the realm.

The challenge is to have an upgrade path for all instances for version upgrades/bug fixes, but I guess there are multiple strategies already implemented (not part of this discussion)

Related