Import Keycloak realm for use in Integration Test
We saw how to export a keycloak realm in a previous post. We also saw how to resolve the script upload is disabled error when importing the previously exported realm. In this post, we consider how to import a realm and use it in integration test
1. Why is this even necessary?
You may have a keycloak integration and need to verify that clients and users have the necessary authorizations. The easiest way to do this is to export your development realm and import this into the keycloak container during integration test.
By default, keycloak export produces separate files: a project-realm.json and project-users-0..n.json. Again see post for how to export realm.
2. What to do
Copy users property from the project-users-n.json file into the project-realm.json file. This is because, the service client roles which you may have added while making changes to your realm during development will be present in the users property.
For instance, say you have a client: account-api-resource-server, if you proceed to only import the realm file, it would normally only include the client definition. Let's say you added the realm-role manage-users to the client, which allows your client to create a user via the Keycloak Rest API. Only importing the project-realm.json file would give an HttpStatus of 401 when we attempt to create a user using the keycloak REST API. The reason is that the client is not authorized to perform this operation, as it does not have the required role.
3. Client Roles defintion
Notice that the exported realm users json file contains a users property which is a listing of users and clients. Clients have authorization details here as well. Client account-api-resource-server has clientRoles: view-realm, manage-users, ...
4. Realm export for Integration Test
To ensure that the keycloak clients have the correct setup, including service-account-roles, you can prepare a single realm-export.json file for import. Copy the users property from the realm-users.json file into the realm.json export file. I also like to remove regular users from the list, and only keep the client defintions. Resulting in an export file like so:
Happy coding.