Custom SPI to add or remove policy and local cache issue in cluster mode

Hi everyone,
we are built a custom SPI to dynamically add and remove user based policy to existing permission.
We are experiencing issue in Keycloak authorization cache in our 3 machines keycloak cluster.
Sometimes the cache is not invalidated in every node resulting in authorization failures.
Here below the piece of code we use for adding a policy to an existing one:

ClientModel clientModel = Optional.ofNullable(realm.getClientByClientId(cliendId))
.orElseThrow( ()->new InternalServerErrorException("CliendId “+cliendId+” in realm “+realm.getName()+” is not present ") ) ;

        StoreFactory storeFactory =  this.authorization.getStoreFactory();
        ResourceServer resourceServer = storeFactory.getResourceServerStore().findById(clientModel.getId());


        Optional.ofNullable(storeFactory.getResourceStore().findByName(resourceName, resourceServer.getId()))
                .orElseThrow( ()->new InternalServerErrorException("Resource Temple "+resourceName+" forn CliendId "+cliendId+" in realm "+realm.getName()+" is not present ") ) ;


        PolicyStore policyStore = storeFactory.getPolicyStore();

        Policy permission =  Optional.ofNullable(policyStore.findByName(permissionName, resourceServer.getId()))
                .orElseThrow( ()->new InternalServerErrorException("Permission "+permissionName+" in client "+cliendId+" is not present ") ) ;

        String policyName = "share_"+resourceName+"_"+toUser;

        if(policyStore.findByName(policyName, resourceServer.getId())!=null)
               throw new ConflictException("Policy "+policyName+" in client" + cliendId + "' already exists.");

// add a policy to give access to the user
Policy sharePolicy = policyStore.create(getSharePolicy(policyName,user.getId()), resourceServer);
permission.addAssociatedPolicy(sharePolicy);

Any idea?

+1 for this. We’re encountering this problem with Keycloak 6.0.1 version. Could you please provide help to us? @pedroigor