Using Keycloak and Angular with multi-tenant configurations

Following up on my initial article on Keycloak & AngularJS implementation using RouterUI, in this article we are taking it to the next level with the support of a truly multi-tenant application.


Keycloak logically splits multi-tenant apps into realms; meaning a separate configuration, users, authentication, everything, for each realm. We can use the realm configuration to separate each clients access and limit requests to the authentication service based on the client.

As a result, each client will have its own login page. Typical of most enterprise login gateways, if a user doesn’t know the realm in which they want to login they wont be granted access to the application.

This raises a problem with AngularJS dynamic routing and controller inspired approach to handling certain states. In this case we need to solve for a pre-controller phase initiation of the authentication configuration.

Route Test

This brings us to the first major consideration: the route tester. This is how we determine which configuration to tell keycloak to load.

The route tester is required to run before the application is loaded. Using the $urlService we test to see if the URL matches one of our preconfigured realm paths. If it string tests true we load the keycloak realm using the found key.

Dynamic Configuration

This is convenient because it allows an unlimited number of login pages to be configured on the remote keycloak server, and only a few lines of setup here in AngularJS.


I used local-storage to persist the realm as the likelihood someone is changing realms is extremely slim. This also allows someone to change realms by simple changing the url.

The nice thing about this setup we can also test for the existing session in a specified realm.

If the login fails we resort to the realm specific keycloak login page.

Unauthorized Redirect

If the user doesn't have a realm in local storage and did not pass the regex test for logging into our application we redirect to a generic page.

Server Side Dynamic JWKS

This series will continue with the server side code that explains how to evaluate requests that can be coming from multiple keycloak domains. All the while preserving the JWKS specification