1

I want to achieve transaction functionality in keycloak. I am creating a user then a role and associating that role with the user. I want all of these operations in a single transaction. Here is my code snippet:

Keycloak keyClk = getKeyCloakInstance();
    UserRepresentation userRepresentation = new UserRepresentation();
    userRepresentation.setEnabled(user.getStatus());
    userRepresentation.setUsername(user.getUserId() != null ? user.getUserId() : "");
    userRepresentation.setEmail(user.getEmail());

    RealmResource realmResource = keyClk.realm(KeyCloakUtil.realmName);
    UsersResource usersRessource = realmResource.users();
    Response response = usersRessource.create(userRepresentation);
    List<Role> roleList = user.getRoles();
    if (!roleList.isEmpty() || roleList != null) {
        createUserRoleList(user.getUserId(), roleList, KeyCloakUtil.clientId, KeyCloakConstant.ACTION_ADD);
    }
ouflak
  • 2,458
  • 10
  • 44
  • 49
sandeep
  • 41
  • 7

2 Answers2

0

I am not sure if keycloak is able to handle that task transactionally. What i did is after creating a user in keycloak, i would save the reference of the created user in a database. This approach is risky if something went wrong with your workflow and maybe you end up having some users in keycloak but not in your local database.

Harun Sevinc
  • 33
  • 2
  • 6
  • What if, the database insert fails you just delete the user from Keycloak? i.e. start the transaction over again – Connie DeCinko Jan 27 '23 at 22:28
  • Well, since Keycloak is the place where users are stored in, it is not that much of a pain. When the user should be deleted it is enough to remove him from keycloak. The reference could easily be deleted by comparing ids that do not exist anymore. Also, you could make your database insert transactional to avoid things like that i guess. – Harun Sevinc Feb 03 '23 at 20:45
0

I know you can enhance keycloak and create a new rest API. When you do that, you will have access to keycloak transaction classes and can do everything under s transaction, at least this is what I understand when I searched for it.

I would have liked them to expose this feature without needing to enhance the code.

Another approach is to simulate a transaction your self. Before you start handling the request create a job Id and store it with the information you need to complete the job. Update the job as you go. If the code fails you can revert the changes you made. Even if the application stops when it starts again, you can go over the jobs and find the in-progress jobs and decide if you should try to complete them or revert the changes.

ouflak
  • 2,458
  • 10
  • 44
  • 49
mirit sadon
  • 31
  • 1
  • 4