diff --git a/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java b/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java index b1583249a3..82273359fe 100644 --- a/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java +++ b/server-spi-private/src/main/java/org/keycloak/authorization/policy/evaluation/DefaultEvaluation.java @@ -168,20 +168,34 @@ public class DefaultEvaluation implements Evaluation { return user.isMemberOf(group); } + private final String USER_CACHE_SESSION_ATTRIBUTE = DefaultEvaluation.class.getName() + ".userCache"; private UserModel getUser(String id, KeycloakSession session) { - RealmModel realm = session.getContext().getRealm(); - UserModel user = session.users().getUserById(realm, id); + @SuppressWarnings("unchecked") HashMap cache = (HashMap) session.getAttribute(USER_CACHE_SESSION_ATTRIBUTE); + if (cache == null) { + cache = new HashMap<>(); + session.setAttribute(USER_CACHE_SESSION_ATTRIBUTE, cache); + } + UserModel user = cache.get(id); if (Objects.isNull(user)) { - user = session.users().getUserByUsername(realm ,id); - } - if (Objects.isNull(user)) { - user = session.users().getUserByEmail(realm, id); - } - if (Objects.isNull(user)) { - user = session.users().getServiceAccount(realm.getClientById(id)); + if (cache.containsKey(id)) { + return null; + } + RealmModel realm = session.getContext().getRealm(); + user = session.users().getUserById(realm, id); + if (Objects.isNull(user)) { + user = session.users().getUserByUsername(realm, id); + } + if (Objects.isNull(user)) { + user = session.users().getUserByEmail(realm, id); + } + if (Objects.isNull(user)) { + user = session.users().getServiceAccount(realm.getClientById(id)); + } } + cache.put(id, user); + return user; }