Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant way to clone a Keycloak realm with all its configurations (clients and roles) for a multitenant application?

Tags:

keycloak

I'm building a multitenant application and I'm using Keycloak for authentication and authorization.

Foreach each tenant, the idea is to have a dedicated Keycloak realm. Each tenant will have exactly the same roles and clients.

I have tried to export one existing realm, use it as template and import it for new tenant. Problem: I'm facing database constraint violation due to internal id.

Question: Is there an elegant way to achieve this, having a template to create a new realm ?

like image 968
Youssouf Maiga Avatar asked Jan 16 '26 21:01

Youssouf Maiga


2 Answers

  • Be sure that the feature for uploading script is enabled. For a deployment with a docker-compose just add this:

      command: -Dkeycloak.profile.feature.upload_scripts=enabled      
    
  • Export your realm (the one to be used as model)

  • Remove all lines containing "id":, "_id": and "containerId":

  • Search and replace template realm name by the new realm name

  • In Keycloak UI admin console, Add new realm, provide the file and that is all.

You can use the cleaned exported file as template.

like image 179
Youssouf Maiga Avatar answered Jan 19 '26 18:01

Youssouf Maiga


Can't comment due to rep, but I'd like to add to @Youssouf Maiga's answer, that you should also modify any fields that contain values under "authenticationFlowBindingOverrides":

Replace any entries that have values assigned under "direct_grant" or "browser" i.e

  "authenticationFlowBindingOverrides": {
    "direct_grant": "f5d1wb45e-27eb-4466-937439-9cc8a615ad65e",
    "browser": "5b23141a1c-7af8d-410e-a9b451f-0eec12039c72e9"
  },

replaced with

"authenticationFlowBindingOverrides": {},
    

I tried cloning my realm based on this and got an error saying:

"Unable to resolve auth flow binding override for: direct_grant" when importing the modified realm export.

Keycloak version 16.1.1

like image 42
The7thNoodle Avatar answered Jan 19 '26 18:01

The7thNoodle