From aa91f6027801d198e68409bc8b907761fe08c776 Mon Sep 17 00:00:00 2001 From: Alexander Schwartz Date: Thu, 1 Aug 2024 10:38:46 +0200 Subject: [PATCH] Caches the id-to-user mapping for the evaluation in the current session (#31794) Closes #31519 Signed-off-by: Alexander Schwartz --- .../policy/evaluation/DefaultEvaluation.java | 32 +++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) 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; }