Keycloak exception "Cannot access delegate without a transaction"
<p>Context: <strong>Keycloak 1.9.1.Final and newer versions</strong></p>

<p>Hi,</p>

<p>I have created a custom user federation provider which is a simple variation of the Keycloak's classpath property federation provider example. Instead of reading the usernames in a property file, I fetch then from an external web service.</p>

<p>My trouble is that sometimes I get the following exception when trying to authenticate with a test user:</p>

<pre><code>Failed authentication: java.lang.IllegalStateException: Cannot access delegate without a transaction
  at org.keycloak.models.cache.infinispan.UserCacheSession.getDelegate(UserCacheSession.java:78)
  at org.keycloak.models.cache.infinispan.UserCacheSession.addUser(UserCacheSession.java:442)
  at com.example.keycloak.MyFederationProvider.getUserModel(MyFederationProvider.java:324)
  at com.example.keycloak.MyFederationProvider.getUserByUsername(MyFederationProvider.java:206)
  at org.keycloak.models.UserFederationManager.getUserByUsername(UserFederationManager.java:237)
  at org.keycloak.models.utils.KeycloakModelUtils.findUserByNameOrEmail(KeycloakModelUtils.java:273)
  at org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator.validateUserAndPassword(AbstractUsernameFormAuthenticator.java:127)
  at org.keycloak.authentication.authenticators.browser.UsernamePasswordForm.validateForm(UsernamePasswordForm.java:56)
  at org.keycloak.authentication.authenticators.browser.UsernamePasswordForm.action(UsernamePasswordForm.java:49)
  at org.keycloak.authentication.DefaultAuthenticationFlow.processAction(DefaultAuthenticationFlow.java:84)
  at org.keycloak.authentication.AuthenticationProcessor.authenticationAction(AuthenticationProcessor.java:759)
  at org.keycloak.services.resources.LoginActionsService.processFlow(LoginActionsService.java:359)
  at org.keycloak.services.resources.LoginActionsService.processAuthentication(LoginActionsService.java:341)
  at org.keycloak.services.resources.LoginActionsService.authenticateForm(LoginActionsService.java:386)
  ...
</code></pre>

<p>I can't figure out why this exception occures. I looked at the <code>org.keycloak.models.cache.infinispan.UserCacheSession</code> class and I could see that the exception is thrown when <code>transactionActive</code> variable is false, but I don't understand under what conditions it is set to false.</p>

<p>I tried forcing a transaction with <code>KeycloakModelUtils.runJobInTransaction()</code> method or by adding <code>begin()</code> and <code>commit()</code> arround the <code>addUser()</code> call, but it didn't solved the issue (I got a new error which informs that transaction is already active).</p>

<p>Did you already experienced this exception and know how to avoid it ?</p>

<p>Thanks a lot</p>