Avoid using methods on UserCredentialStoreManager

This commit is contained in:
Alexander Schwartz 2022-05-05 10:35:51 +02:00 committed by Hynek Mlnařík
parent bc8fd21dc6
commit 6f287e7ded
63 changed files with 258 additions and 274 deletions

View file

@ -44,11 +44,6 @@ public class SecretQuestionCredentialProvider implements CredentialProvider<Secr
this.session = session; this.session = session;
} }
private UserCredentialStore getCredentialStore() {
return session.userCredentialManager();
}
@Override @Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
if (!(input instanceof UserCredentialModel)) { if (!(input instanceof UserCredentialModel)) {
@ -62,7 +57,7 @@ public class SecretQuestionCredentialProvider implements CredentialProvider<Secr
if (challengeResponse == null) { if (challengeResponse == null) {
return false; return false;
} }
CredentialModel credentialModel = getCredentialStore().getStoredCredentialById(realm, user, input.getCredentialId()); CredentialModel credentialModel = user.getUserCredentialManager().getStoredCredentialById(input.getCredentialId());
SecretQuestionCredentialModel sqcm = getCredentialFromModel(credentialModel); SecretQuestionCredentialModel sqcm = getCredentialFromModel(credentialModel);
return sqcm.getSecretQuestionSecretData().getAnswer().equals(challengeResponse); return sqcm.getSecretQuestionSecretData().getAnswer().equals(challengeResponse);
} }
@ -75,7 +70,7 @@ public class SecretQuestionCredentialProvider implements CredentialProvider<Secr
@Override @Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
if (!supportsCredentialType(credentialType)) return false; if (!supportsCredentialType(credentialType)) return false;
return getCredentialStore().getStoredCredentialsByTypeStream(realm, user, credentialType).count() > 0; return user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType).findAny().isPresent();
} }
@Override @Override
@ -83,12 +78,12 @@ public class SecretQuestionCredentialProvider implements CredentialProvider<Secr
if (credentialModel.getCreatedDate() == null) { if (credentialModel.getCreatedDate() == null) {
credentialModel.setCreatedDate(Time.currentTimeMillis()); credentialModel.setCreatedDate(Time.currentTimeMillis());
} }
return getCredentialStore().createCredential(realm, user, credentialModel); return user.getUserCredentialManager().createStoredCredential(credentialModel);
} }
@Override @Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) { public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
return getCredentialStore().removeStoredCredential(realm, user, credentialId); return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
} }
@Override @Override

View file

@ -3,7 +3,6 @@ package org.keycloak.models.cache.infinispan;
import org.keycloak.credential.CredentialInput; import org.keycloak.credential.CredentialInput;
import org.keycloak.credential.CredentialModel; import org.keycloak.credential.CredentialModel;
import org.keycloak.models.SingleUserCredentialManager; import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.UserModel;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -107,8 +106,8 @@ public abstract class SingleUserCredentialManagerCacheAdapter implements SingleU
} }
@Override @Override
public Stream<String> getConfiguredUserStorageCredentialTypesStream(UserModel user) { public Stream<String> getConfiguredUserStorageCredentialTypesStream() {
return singleUserCredentialManager.getConfiguredUserStorageCredentialTypesStream(user); return singleUserCredentialManager.getConfiguredUserStorageCredentialTypesStream();
} }
@Override @Override

View file

@ -34,15 +34,9 @@ import java.util.Objects;
import java.util.stream.Stream; import java.util.stream.Stream;
/** /**
* Handling credentials for a given user. * Handling credentials for a given user for the legacy store.
* *
* This serves as a wrapper to specific strategies. The wrapping code implements the logic for {@link CredentialInputUpdater}s * Its companion is the MapSingleUserCredentialManagerStrategy that doesn't contain storage related elements.
* and {@link CredentialInputValidator}s. Storage specific strategies can be added like for example in
* org.keycloak.models.map.credential.MapSingleUserCredentialManagerStrategy.
*
* I tried to extract the federation specific parts to the {@link LegacySingleUserCredentialManagerStrategy} but the control
* flow in the existing logic: if <code>model == null || !model.isEnabled()</code>, the code will directly return, while
* the behavior of the strategy is to continue if it returns false and it will then try other providers.
* *
* @author Alexander Schwartz * @author Alexander Schwartz
*/ */
@ -218,7 +212,7 @@ public class LegacySingleUserCredentialManager extends AbstractStorageManager<Us
} }
@Override @Override
public Stream<String> getConfiguredUserStorageCredentialTypesStream(UserModel user) { public Stream<String> getConfiguredUserStorageCredentialTypesStream() {
return getCredentialProviders(session, CredentialProvider.class).map(CredentialProvider::getType) return getCredentialProviders(session, CredentialProvider.class).map(CredentialProvider::getType)
.filter(credentialType -> UserStorageCredentialConfigured.CONFIGURED == isConfiguredThroughUserStorage(realm, user, credentialType)); .filter(credentialType -> UserStorageCredentialConfigured.CONFIGURED == isConfiguredThroughUserStorage(realm, user, credentialType));
} }

View file

@ -40,8 +40,8 @@ import java.util.stream.Stream;
* Handling credentials for a given user. * Handling credentials for a given user.
* *
* This serves as a wrapper to specific strategies. The wrapping code implements the logic for {@link CredentialInputUpdater}s * This serves as a wrapper to specific strategies. The wrapping code implements the logic for {@link CredentialInputUpdater}s
* and {@link CredentialInputValidator}s. Storage specific strategies can be added like for example in * and {@link CredentialInputValidator}s. Storage specific strategies can be added, like for example, in
* org.keycloak.models.map.credential.MapSingleUserCredentialManagerStrategy. * {@link MapSingleUserCredentialManagerStrategy}.
* *
* @author Alexander Schwartz * @author Alexander Schwartz
*/ */
@ -162,7 +162,7 @@ public class MapSingleUserCredentialManager implements SingleUserCredentialManag
} }
@Override @Override
public Stream<String> getConfiguredUserStorageCredentialTypesStream(UserModel user) { public Stream<String> getConfiguredUserStorageCredentialTypesStream() {
// TODO ask the store // TODO ask the store
return getCredentialProviders(session, CredentialProvider.class).map(CredentialProvider::getType) return getCredentialProviders(session, CredentialProvider.class).map(CredentialProvider::getType)
.filter(credentialType -> UserStorageCredentialConfigured.CONFIGURED == isConfiguredThroughUserStorage(realm, user, credentialType)); .filter(credentialType -> UserStorageCredentialConfigured.CONFIGURED == isConfiguredThroughUserStorage(realm, user, credentialType));

View file

@ -12,7 +12,7 @@ import java.util.stream.Collectors;
public interface CredentialValidator<T extends CredentialProvider> { public interface CredentialValidator<T extends CredentialProvider> {
T getCredentialProvider(KeycloakSession session); T getCredentialProvider(KeycloakSession session);
default List<CredentialModel> getCredentials(KeycloakSession session, RealmModel realm, UserModel user) { default List<CredentialModel> getCredentials(KeycloakSession session, RealmModel realm, UserModel user) {
return session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, getCredentialProvider(session).getType()) return user.getUserCredentialManager().getStoredCredentialsByTypeStream(getCredentialProvider(session).getType())
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
default String getType(KeycloakSession session) { default String getType(KeycloakSession session) {

View file

@ -220,9 +220,9 @@ public class ModelToRepresentation {
rep.setEmail(user.getEmail()); rep.setEmail(user.getEmail());
rep.setEnabled(user.isEnabled()); rep.setEnabled(user.isEnabled());
rep.setEmailVerified(user.isEmailVerified()); rep.setEmailVerified(user.isEmailVerified());
rep.setTotp(session.userCredentialManager().isConfiguredFor(realm, user, OTPCredentialModel.TYPE)); rep.setTotp(user.getUserCredentialManager().isConfiguredFor(OTPCredentialModel.TYPE));
rep.setDisableableCredentialTypes(session.userCredentialManager() rep.setDisableableCredentialTypes(user.getUserCredentialManager()
.getDisableableCredentialTypesStream(realm, user).collect(Collectors.toSet())); .getDisableableCredentialTypesStream().collect(Collectors.toSet()));
rep.setFederationLink(user.getFederationLink()); rep.setFederationLink(user.getFederationLink());
rep.setNotBefore(session.users().getNotBeforeOfUser(realm, user)); rep.setNotBefore(session.users().getNotBeforeOfUser(realm, user));
rep.setRequiredActions(user.getRequiredActionsStream().collect(Collectors.toList())); rep.setRequiredActions(user.getRequiredActionsStream().collect(Collectors.toList()));

View file

@ -779,21 +779,21 @@ public class RepresentationToModel {
convertDeprecatedCredentialsFormat(userRep); convertDeprecatedCredentialsFormat(userRep);
if (userRep.getCredentials() != null) { if (userRep.getCredentials() != null) {
for (CredentialRepresentation cred : userRep.getCredentials()) { for (CredentialRepresentation cred : userRep.getCredentials()) {
if (cred.getId() != null && session.userCredentialManager().getStoredCredentialById(realm, user, cred.getId()) != null) { if (cred.getId() != null && user.getUserCredentialManager().getStoredCredentialById(cred.getId()) != null) {
continue; continue;
} }
if (cred.getValue() != null && !cred.getValue().isEmpty()) { if (cred.getValue() != null && !cred.getValue().isEmpty()) {
RealmModel origRealm = session.getContext().getRealm(); RealmModel origRealm = session.getContext().getRealm();
try { try {
session.getContext().setRealm(realm); session.getContext().setRealm(realm);
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(cred.getValue(), false)); user.getUserCredentialManager().updateCredential(UserCredentialModel.password(cred.getValue(), false));
} catch (ModelException ex) { } catch (ModelException ex) {
throw new PasswordPolicyNotMetException(ex.getMessage(), user.getUsername(), ex); throw new PasswordPolicyNotMetException(ex.getMessage(), user.getUsername(), ex);
} finally { } finally {
session.getContext().setRealm(origRealm); session.getContext().setRealm(origRealm);
} }
} else { } else {
session.userCredentialManager().createCredentialThroughProvider(realm, user, toModel(cred)); user.getUserCredentialManager().createCredentialThroughProvider(toModel(cred));
} }
} }
} }

View file

@ -52,7 +52,7 @@ public class HistoryPasswordPolicyProvider implements PasswordPolicyProvider {
PasswordPolicy policy = session.getContext().getRealm().getPasswordPolicy(); PasswordPolicy policy = session.getContext().getRealm().getPasswordPolicy();
int passwordHistoryPolicyValue = policy.getPolicyConfig(PasswordPolicy.PASSWORD_HISTORY_ID); int passwordHistoryPolicyValue = policy.getPolicyConfig(PasswordPolicy.PASSWORD_HISTORY_ID);
if (passwordHistoryPolicyValue != -1) { if (passwordHistoryPolicyValue != -1) {
if (session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, PasswordCredentialModel.TYPE) if (user.getUserCredentialManager().getStoredCredentialsByTypeStream(PasswordCredentialModel.TYPE)
.map(PasswordCredentialModel::createFromCredentialModel) .map(PasswordCredentialModel::createFromCredentialModel)
.anyMatch(passwordCredential -> { .anyMatch(passwordCredential -> {
PasswordHashProvider hash = session.getProvider(PasswordHashProvider.class, PasswordHashProvider hash = session.getProvider(PasswordHashProvider.class,
@ -63,7 +63,7 @@ public class HistoryPasswordPolicyProvider implements PasswordPolicyProvider {
} }
if (passwordHistoryPolicyValue > 0) { if (passwordHistoryPolicyValue > 0) {
if (this.getRecent(session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, PasswordCredentialModel.PASSWORD_HISTORY), if (this.getRecent(user.getUserCredentialManager().getStoredCredentialsByTypeStream(PasswordCredentialModel.PASSWORD_HISTORY),
passwordHistoryPolicyValue - 1) passwordHistoryPolicyValue - 1)
.map(PasswordCredentialModel::createFromCredentialModel) .map(PasswordCredentialModel::createFromCredentialModel)
.anyMatch(passwordCredential -> { .anyMatch(passwordCredential -> {

View file

@ -100,7 +100,7 @@ public class CredentialHelper {
String totpSecret = credentialModel.getOTPSecretData().getValue(); String totpSecret = credentialModel.getOTPSecretData().getValue();
UserCredentialModel otpUserCredential = new UserCredentialModel("", realm.getOTPPolicy().getType(), totpSecret); UserCredentialModel otpUserCredential = new UserCredentialModel("", realm.getOTPPolicy().getType(), totpSecret);
boolean userStorageCreated = session.userCredentialManager().updateCredential(realm, user, otpUserCredential); boolean userStorageCreated = user.getUserCredentialManager().updateCredential(otpUserCredential);
String credentialId = null; String credentialId = null;
if (userStorageCreated) { if (userStorageCreated) {
@ -112,7 +112,7 @@ public class CredentialHelper {
//If the type is HOTP, call verify once to consume the OTP used for registration and increase the counter. //If the type is HOTP, call verify once to consume the OTP used for registration and increase the counter.
UserCredentialModel credential = new UserCredentialModel(credentialId, otpCredentialProvider.getType(), totpCode); UserCredentialModel credential = new UserCredentialModel(credentialId, otpCredentialProvider.getType(), totpCode);
return session.userCredentialManager().isValid(realm, user, credential); return user.getUserCredentialManager().isValid(credential);
} }
public static void deleteOTPCredential(KeycloakSession session, RealmModel realm, UserModel user, String credentialId) { public static void deleteOTPCredential(KeycloakSession session, RealmModel realm, UserModel user, String credentialId) {
@ -122,7 +122,7 @@ public class CredentialHelper {
// This can usually happened when credential is stored in the userStorage. Propagate to "disable" credential in the userStorage // This can usually happened when credential is stored in the userStorage. Propagate to "disable" credential in the userStorage
if (!removed) { if (!removed) {
logger.debug("Removing OTP credential from userStorage"); logger.debug("Removing OTP credential from userStorage");
session.userCredentialManager().disableCredentialType(realm, user, OTPCredentialModel.TYPE); user.getUserCredentialManager().disableCredentialType(OTPCredentialModel.TYPE);
} }
} }

View file

@ -43,7 +43,7 @@ public interface CredentialProvider<T extends CredentialModel> extends Provider
T getCredentialFromModel(CredentialModel model); T getCredentialFromModel(CredentialModel model);
default T getDefaultCredential(KeycloakSession session, RealmModel realm, UserModel user) { default T getDefaultCredential(KeycloakSession session, RealmModel realm, UserModel user) {
CredentialModel model = session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, getType()) CredentialModel model = user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType())
.findFirst().orElse(null); .findFirst().orElse(null);
return model != null ? getCredentialFromModel(model) : null; return model != null ? getCredentialFromModel(model) : null;
} }

View file

@ -46,7 +46,7 @@ public interface UserCredentialStore extends Provider {
CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id); CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id);
/** /**
* @deprecated Use {@link #getStoredCredentialsStream(RealmModel, UserModel) getStoredCredentialsStream} instead. * @deprecated Use {@link org.keycloak.models.SingleUserCredentialManager#getStoredCredentialsStream()} instead.
*/ */
@Deprecated @Deprecated
List<CredentialModel> getStoredCredentials(RealmModel realm, UserModel user); List<CredentialModel> getStoredCredentials(RealmModel realm, UserModel user);
@ -64,7 +64,7 @@ public interface UserCredentialStore extends Provider {
} }
/** /**
* @deprecated Use {@link #getStoredCredentialsByTypeStream(RealmModel, UserModel, String) getStoredCredentialsByTypeStream} * @deprecated Use {@link org.keycloak.models.SingleUserCredentialManager#getStoredCredentialsByTypeStream(String)}
* instead. * instead.
*/ */
@Deprecated @Deprecated
@ -79,7 +79,7 @@ public interface UserCredentialStore extends Provider {
* @return a non-null {@link Stream} of credentials. * @return a non-null {@link Stream} of credentials.
*/ */
default Stream<CredentialModel> getStoredCredentialsByTypeStream(RealmModel realm, UserModel user, String type) { default Stream<CredentialModel> getStoredCredentialsByTypeStream(RealmModel realm, UserModel user, String type) {
List<CredentialModel> result = this.getStoredCredentialsByType(realm, user, type); List<CredentialModel> result = user.getUserCredentialManager().getStoredCredentialsByTypeStream(type).collect(Collectors.toList());
return result != null ? result.stream() : Stream.empty(); return result != null ? result.stream() : Stream.empty();
} }
@ -98,7 +98,7 @@ public interface UserCredentialStore extends Provider {
interface Streams extends UserCredentialStore { interface Streams extends UserCredentialStore {
@Override @Override
default List<CredentialModel> getStoredCredentials(RealmModel realm, UserModel user) { default List<CredentialModel> getStoredCredentials(RealmModel realm, UserModel user) {
return this.getStoredCredentialsStream(realm, user).collect(Collectors.toList()); return user.getUserCredentialManager().getStoredCredentialsStream().collect(Collectors.toList());
} }
@Override @Override
@ -106,7 +106,7 @@ public interface UserCredentialStore extends Provider {
@Override @Override
default List<CredentialModel> getStoredCredentialsByType(RealmModel realm, UserModel user, String type) { default List<CredentialModel> getStoredCredentialsByType(RealmModel realm, UserModel user, String type) {
return this.getStoredCredentialsByTypeStream(realm, user, type).collect(Collectors.toList()); return user.getUserCredentialManager().getStoredCredentialsByTypeStream(type).collect(Collectors.toList());
} }
@Override @Override

View file

@ -248,9 +248,10 @@ public interface KeycloakSession {
/** /**
* Service that allows you to valid and update credentials for a user * Service that allows you to valid and update credentials for a user
* * @deprecated Use {@link UserModel#getUserCredentialManager()} instead.
* @return * @return
*/ */
@Deprecated
UserCredentialManager userCredentialManager(); UserCredentialManager userCredentialManager();
/** /**

View file

@ -20,6 +20,7 @@ package org.keycloak.models;
import org.keycloak.credential.CredentialInput; import org.keycloak.credential.CredentialInput;
import org.keycloak.credential.CredentialModel; import org.keycloak.credential.CredentialModel;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -30,6 +31,10 @@ public interface SingleUserCredentialManager {
*/ */
boolean isValid(List<CredentialInput> inputs); boolean isValid(List<CredentialInput> inputs);
default boolean isValid(CredentialInput... inputs) {
return isValid(Arrays.asList(inputs));
}
/** /**
* Updates a credentials of the user. * Updates a credentials of the user.
*/ */
@ -63,7 +68,7 @@ public interface SingleUserCredentialManager {
@Deprecated @Deprecated
boolean isConfiguredLocally(String type); boolean isConfiguredLocally(String type);
Stream<String> getConfiguredUserStorageCredentialTypesStream(UserModel user); Stream<String> getConfiguredUserStorageCredentialTypesStream();
CredentialModel createCredentialThroughProvider(CredentialModel model); CredentialModel createCredentialThroughProvider(CredentialModel model);
} }

View file

@ -26,9 +26,13 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
/** /**
* Manage the credentials for a user.
*
* @deprecated Instead of this class, use {@link UserModel#getUserCredentialManager()} instead.
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $ * @version $Revision: 1 $
*/ */
@Deprecated
public interface UserCredentialManager extends UserCredentialStore { public interface UserCredentialManager extends UserCredentialStore {
/** /**
@ -97,14 +101,13 @@ public interface UserCredentialManager extends UserCredentialStore {
* @param realm * @param realm
* @param user * @param user
* @return * @return
* @deprecated Use {@link #getDisableableCredentialTypesStream(RealmModel, UserModel) getDisableableCredentialTypesStream} * @deprecated Use {@link UserModel#getUserCredentialManager()} and {@link SingleUserCredentialManager#getDisableableCredentialTypesStream()} instead.
* instead.
*/ */
@Deprecated @Deprecated
Set<String> getDisableableCredentialTypes(RealmModel realm, UserModel user); Set<String> getDisableableCredentialTypes(RealmModel realm, UserModel user);
/** /**
* Obtains the credential types that can be disabled by means of the {@link #disableCredentialType(RealmModel, UserModel, String)} * Obtains the credential types that can be disabled.
* method. * method.
* *
* @param realm a reference to the realm. * @param realm a reference to the realm.
@ -112,8 +115,7 @@ public interface UserCredentialManager extends UserCredentialStore {
* @return a non-null {@link Stream} of credential types. * @return a non-null {@link Stream} of credential types.
*/ */
default Stream<String> getDisableableCredentialTypesStream(RealmModel realm, UserModel user) { default Stream<String> getDisableableCredentialTypesStream(RealmModel realm, UserModel user) {
Set<String> result = this.getDisableableCredentialTypes(realm, user); return user.getUserCredentialManager().getDisableableCredentialTypesStream();
return result != null ? result.stream() : Stream.empty();
} }
/** /**
@ -156,8 +158,7 @@ public interface UserCredentialManager extends UserCredentialStore {
* Return credential types, which are provided by the user storage where user is stored. Returned values can contain for example "password", "otp" etc. * Return credential types, which are provided by the user storage where user is stored. Returned values can contain for example "password", "otp" etc.
* This will always return empty list for "local" users, which are not backed by any user storage * This will always return empty list for "local" users, which are not backed by any user storage
* *
* @return * @deprecated Use {@link UserModel#getUserCredentialManager()} and then call {@link SingleUserCredentialManager#getConfiguredUserStorageCredentialTypesStream()}
* @deprecated Use {@link #getConfiguredUserStorageCredentialTypesStream(RealmModel, UserModel) getConfiguredUserStorageCredentialTypesStream}
* instead. * instead.
*/ */
@Deprecated @Deprecated
@ -174,8 +175,7 @@ public interface UserCredentialManager extends UserCredentialStore {
* @return a non-null {@link Stream} of credential types. * @return a non-null {@link Stream} of credential types.
*/ */
default Stream<String> getConfiguredUserStorageCredentialTypesStream(RealmModel realm, UserModel user) { default Stream<String> getConfiguredUserStorageCredentialTypesStream(RealmModel realm, UserModel user) {
List<String> result = this.getConfiguredUserStorageCredentialTypes(realm, user); return user.getUserCredentialManager().getConfiguredUserStorageCredentialTypesStream();
return result != null ? result.stream() : Stream.empty();
} }
/** /**
@ -188,7 +188,7 @@ public interface UserCredentialManager extends UserCredentialStore {
interface Streams extends UserCredentialManager, UserCredentialStore.Streams { interface Streams extends UserCredentialManager, UserCredentialStore.Streams {
@Override @Override
default Set<String> getDisableableCredentialTypes(RealmModel realm, UserModel user) { default Set<String> getDisableableCredentialTypes(RealmModel realm, UserModel user) {
return this.getDisableableCredentialTypesStream(realm, user).collect(Collectors.toSet()); return user.getUserCredentialManager().getDisableableCredentialTypesStream().collect(Collectors.toSet());
} }
@Override @Override
@ -196,7 +196,7 @@ public interface UserCredentialManager extends UserCredentialStore {
@Override @Override
default List<String> getConfiguredUserStorageCredentialTypes(RealmModel realm, UserModel user) { default List<String> getConfiguredUserStorageCredentialTypes(RealmModel realm, UserModel user) {
return this.getConfiguredUserStorageCredentialTypesStream(realm, user).collect(Collectors.toList()); return user.getUserCredentialManager().getConfiguredUserStorageCredentialTypesStream().collect(Collectors.toList());
} }
@Override @Override

View file

@ -80,13 +80,10 @@ class AuthenticationSelectionResolver {
if (processor.getAuthenticationSession().getAuthenticatedUser() != null) { if (processor.getAuthenticationSession().getAuthenticatedUser() != null) {
authenticationSelectionList = authenticationSelectionList =
Stream.concat( Stream.concat(
processor.getSession().userCredentialManager() processor.getAuthenticationSession().getAuthenticatedUser().getUserCredentialManager().getStoredCredentialsStream()
.getStoredCredentialsStream(processor.getRealm(), processor.getAuthenticationSession().getAuthenticatedUser())
.map(CredentialModel::getType), .map(CredentialModel::getType),
processor.getSession().userCredentialManager() processor.getAuthenticationSession().getAuthenticatedUser().getUserCredentialManager()
.getConfiguredUserStorageCredentialTypesStream( .getConfiguredUserStorageCredentialTypesStream())
processor.getRealm(),
processor.getAuthenticationSession().getAuthenticatedUser()))
.distinct() .distinct()
.filter(typeAuthExecMap::containsKey) .filter(typeAuthExecMap::containsKey)
.map(credentialType -> new AuthenticationSelectionOption(processor.getSession(), typeAuthExecMap.get(credentialType))) .map(credentialType -> new AuthenticationSelectionOption(processor.getSession(), typeAuthExecMap.get(credentialType)))

View file

@ -226,7 +226,7 @@ public abstract class AbstractUsernameFormAuthenticator extends AbstractFormAuth
if (isDisabledByBruteForce(context, user)) return false; if (isDisabledByBruteForce(context, user)) return false;
if (password != null && !password.isEmpty() && context.getSession().userCredentialManager().isValid(context.getRealm(), user, UserCredentialModel.password(password))) { if (password != null && !password.isEmpty() && user.getUserCredentialManager().isValid(UserCredentialModel.password(password))) {
return true; return true;
} else { } else {
return badPasswordHandler(context, user, clearUser,false); return badPasswordHandler(context, user, clearUser,false);

View file

@ -97,8 +97,7 @@ public class OTPFormAuthenticator extends AbstractUsernameFormAuthenticator impl
context.challenge(challengeResponse); context.challenge(challengeResponse);
return; return;
} }
boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(),context.getUser(), boolean valid = context.getUser().getUserCredentialManager().isValid(new UserCredentialModel(credentialId, getCredentialProvider(context.getSession()).getType(), otp));
new UserCredentialModel(credentialId, getCredentialProvider(context.getSession()).getType(), otp));
if (!valid) { if (!valid) {
context.getEvent().user(userModel) context.getEvent().user(userModel)
.error(Errors.INVALID_USER_CREDENTIALS); .error(Errors.INVALID_USER_CREDENTIALS);
@ -131,7 +130,7 @@ public class OTPFormAuthenticator extends AbstractUsernameFormAuthenticator impl
@Override @Override
public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
return session.userCredentialManager().isConfiguredFor(realm, user, getCredentialProvider(session).getType()); return user.getUserCredentialManager().isConfiguredFor(getCredentialProvider(session).getType());
} }
@Override @Override

View file

@ -44,7 +44,7 @@ public class PasswordForm extends UsernamePasswordForm implements CredentialVali
@Override @Override
public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
return session.userCredentialManager().isConfiguredFor(realm, user, getCredentialProvider(session).getType()); return user.getUserCredentialManager().isConfiguredFor(getCredentialProvider(session).getType());
} }
@Override @Override

View file

@ -28,10 +28,7 @@ import static org.keycloak.services.validation.Validation.FIELD_USERNAME;
public class RecoveryAuthnCodesFormAuthenticator implements Authenticator { public class RecoveryAuthnCodesFormAuthenticator implements Authenticator {
private final UserCredentialManager userCredentialManager;
public RecoveryAuthnCodesFormAuthenticator(KeycloakSession keycloakSession) { public RecoveryAuthnCodesFormAuthenticator(KeycloakSession keycloakSession) {
this.userCredentialManager = keycloakSession.userCredentialManager();
} }
@Override @Override
@ -61,7 +58,7 @@ public class RecoveryAuthnCodesFormAuthenticator implements Authenticator {
RealmModel targetRealm = authnFlowContext.getRealm(); RealmModel targetRealm = authnFlowContext.getRealm();
UserModel authenticatedUser = authnFlowContext.getUser(); UserModel authenticatedUser = authnFlowContext.getUser();
if (!isDisabledByBruteForce(authnFlowContext, authenticatedUser)) { if (!isDisabledByBruteForce(authnFlowContext, authenticatedUser)) {
boolean isValid = this.userCredentialManager.isValid(targetRealm, authenticatedUser, boolean isValid = authenticatedUser.getUserCredentialManager().isValid(
UserCredentialModel.buildFromBackupAuthnCode(recoveryAuthnCodeUserInput.replace("-", ""))); UserCredentialModel.buildFromBackupAuthnCode(recoveryAuthnCodeUserInput.replace("-", "")));
if (!isValid) { if (!isValid) {
Response responseChallenge = createLoginForm(authnFlowContext, true, Response responseChallenge = createLoginForm(authnFlowContext, true,
@ -70,14 +67,14 @@ public class RecoveryAuthnCodesFormAuthenticator implements Authenticator {
authnFlowContext.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, responseChallenge); authnFlowContext.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, responseChallenge);
} else { } else {
result = true; result = true;
Optional<CredentialModel> optUserCredentialFound = this.userCredentialManager.getStoredCredentialsByTypeStream(targetRealm, Optional<CredentialModel> optUserCredentialFound = authenticatedUser.getUserCredentialManager().getStoredCredentialsByTypeStream(
authenticatedUser, RecoveryAuthnCodesCredentialModel.TYPE).findFirst(); RecoveryAuthnCodesCredentialModel.TYPE).findFirst();
RecoveryAuthnCodesCredentialModel recoveryCodeCredentialModel = null; RecoveryAuthnCodesCredentialModel recoveryCodeCredentialModel = null;
if (optUserCredentialFound.isPresent()) { if (optUserCredentialFound.isPresent()) {
recoveryCodeCredentialModel = RecoveryAuthnCodesCredentialModel recoveryCodeCredentialModel = RecoveryAuthnCodesCredentialModel
.createFromCredentialModel(optUserCredentialFound.get()); .createFromCredentialModel(optUserCredentialFound.get());
if (recoveryCodeCredentialModel.allCodesUsed()) { if (recoveryCodeCredentialModel.allCodesUsed()) {
this.userCredentialManager.removeStoredCredential(targetRealm, authenticatedUser, authenticatedUser.getUserCredentialManager().removeStoredCredentialById(
recoveryCodeCredentialModel.getId()); recoveryCodeCredentialModel.getId());
} }
} }
@ -137,7 +134,7 @@ public class RecoveryAuthnCodesFormAuthenticator implements Authenticator {
@Override @Override
public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
return session.userCredentialManager().isConfiguredFor(realm, user, RecoveryAuthnCodesCredentialModel.TYPE); return user.getUserCredentialManager().isConfiguredFor(RecoveryAuthnCodesCredentialModel.TYPE);
} }
@Override @Override

View file

@ -215,7 +215,7 @@ public class WebAuthnAuthenticator implements Authenticator, CredentialValidator
boolean result = false; boolean result = false;
try { try {
result = session.userCredentialManager().isValid(context.getRealm(), user, cred); result = user.getUserCredentialManager().isValid(cred);
} catch (WebAuthnException wae) { } catch (WebAuthnException wae) {
setErrorResponse(context, WEBAUTHN_ERROR_AUTH_VERIFICATION, wae.getMessage()); setErrorResponse(context, WEBAUTHN_ERROR_AUTH_VERIFICATION, wae.getMessage());
return; return;
@ -243,7 +243,7 @@ public class WebAuthnAuthenticator implements Authenticator, CredentialValidator
} }
public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
return session.userCredentialManager().isConfiguredFor(realm, user, getCredentialType()); return user.getUserCredentialManager().isConfiguredFor(getCredentialType());
} }
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) { public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {

View file

@ -44,7 +44,7 @@ public class ValidatePassword extends AbstractDirectGrantAuthenticator {
@Override @Override
public void authenticate(AuthenticationFlowContext context) { public void authenticate(AuthenticationFlowContext context) {
String password = retrievePassword(context); String password = retrievePassword(context);
boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), UserCredentialModel.password(password)); boolean valid = context.getUser().getUserCredentialManager().isValid(UserCredentialModel.password(password));
if (!valid) { if (!valid) {
context.getEvent().user(context.getUser()); context.getEvent().user(context.getUser());
context.getEvent().error(Errors.INVALID_USER_CREDENTIALS); context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);

View file

@ -40,7 +40,7 @@ public class ResetPassword extends AbstractSetRequiredActionAuthenticator {
} }
protected boolean configuredFor(AuthenticationFlowContext context) { protected boolean configuredFor(AuthenticationFlowContext context) {
return context.getSession().userCredentialManager().isConfiguredFor(context.getRealm(), context.getUser(), PasswordCredentialModel.TYPE); return context.getUser().getUserCredentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
} }
@Override @Override

View file

@ -93,7 +93,7 @@ public class RegistrationPassword implements FormAction, FormActionFactory {
String password = formData.getFirst(RegistrationPage.FIELD_PASSWORD); String password = formData.getFirst(RegistrationPage.FIELD_PASSWORD);
UserModel user = context.getUser(); UserModel user = context.getUser();
try { try {
context.getSession().userCredentialManager().updateCredential(context.getRealm(), user, UserCredentialModel.password(formData.getFirst("password"), false)); user.getUserCredentialManager().updateCredential(UserCredentialModel.password(formData.getFirst("password"), false));
} catch (Exception me) { } catch (Exception me) {
user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
} }

View file

@ -83,7 +83,7 @@ public class ConsoleUpdatePassword extends UpdatePassword implements RequiredAct
} }
try { try {
context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), UserCredentialModel.password(passwordNew, false)); context.getUser().getUserCredentialManager().updateCredential(UserCredentialModel.password(passwordNew, false));
context.success(); context.success();
} catch (ModelException me) { } catch (ModelException me) {
errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED); errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);

View file

@ -139,7 +139,7 @@ public class UpdatePassword implements RequiredActionProvider, RequiredActionFac
} }
try { try {
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(passwordNew, false)); user.getUserCredentialManager().updateCredential(UserCredentialModel.password(passwordNew, false));
context.success(); context.success();
} catch (ModelException me) { } catch (ModelException me) {
errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED); errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED);

View file

@ -96,7 +96,7 @@ public class UpdateTotp implements RequiredActionProvider, RequiredActionFactory
} }
OTPCredentialProvider otpCredentialProvider = (OTPCredentialProvider) context.getSession().getProvider(CredentialProvider.class, "keycloak-otp"); OTPCredentialProvider otpCredentialProvider = (OTPCredentialProvider) context.getSession().getProvider(CredentialProvider.class, "keycloak-otp");
final Stream<CredentialModel> otpCredentials = (otpCredentialProvider.isConfiguredFor(context.getRealm(), context.getUser())) final Stream<CredentialModel> otpCredentials = (otpCredentialProvider.isConfiguredFor(context.getRealm(), context.getUser()))
? context.getSession().userCredentialManager().getStoredCredentialsByTypeStream(context.getRealm(), context.getUser(), OTPCredentialModel.TYPE) ? context.getUser().getUserCredentialManager().getStoredCredentialsByTypeStream(OTPCredentialModel.TYPE)
: Stream.empty(); : Stream.empty();
if (otpCredentials.count() >= 1 && Validation.isBlank(userLabel)) { if (otpCredentials.count() >= 1 && Validation.isBlank(userLabel)) {
Response challenge = context.form() Response challenge = context.form()

View file

@ -132,7 +132,7 @@ public class WebAuthnRegister implements RequiredActionProvider, CredentialRegis
String excludeCredentialIds = ""; String excludeCredentialIds = "";
if (avoidSameAuthenticatorRegister) { if (avoidSameAuthenticatorRegister) {
excludeCredentialIds = session.userCredentialManager().getStoredCredentialsByTypeStream(context.getRealm(), userModel, getCredentialType()) excludeCredentialIds = userModel.getUserCredentialManager().getStoredCredentialsByTypeStream(getCredentialType())
.map(credentialModel -> { .map(credentialModel -> {
WebAuthnCredentialModel credModel = WebAuthnCredentialModel.createFromCredentialModel(credentialModel); WebAuthnCredentialModel credModel = WebAuthnCredentialModel.createFromCredentialModel(credentialModel);
return Base64Url.encodeBase64ToBase64Url(credModel.getWebAuthnCredentialData().getCredentialId()); return Base64Url.encodeBase64ToBase64Url(credModel.getWebAuthnCredentialData().getCredentialId());

View file

@ -42,26 +42,6 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
protected KeycloakSession session; protected KeycloakSession session;
/*protected List<CredentialModel> getCachedCredentials(UserModel user, String type) {
if (!(user instanceof CachedUserModel)) return null;
CachedUserModel cached = (CachedUserModel)user;
if (cached.isMarkedForEviction()) return null;
List<CredentialModel> rtn = (List<CredentialModel>)cached.getCachedWith().get(getType());
if (rtn == null) return Collections.EMPTY_LIST;
return rtn;
}*/
private UserCredentialStore getCredentialStore() {
return session.userCredentialManager();
}
/*@Override
public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
List<CredentialModel> creds = getCredentialStore().getStoredCredentialsByType(realm, user, getType());
user.getCachedWith().put(getType(), creds);
}*/
public OTPCredentialProvider(KeycloakSession session) { public OTPCredentialProvider(KeycloakSession session) {
this.session = session; this.session = session;
} }
@ -71,12 +51,12 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
if (credentialModel.getCreatedDate() == null) { if (credentialModel.getCreatedDate() == null) {
credentialModel.setCreatedDate(Time.currentTimeMillis()); credentialModel.setCreatedDate(Time.currentTimeMillis());
} }
return getCredentialStore().createCredential(realm, user, credentialModel); return user.getUserCredentialManager().createStoredCredential(credentialModel);
} }
@Override @Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) { public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
return getCredentialStore().removeStoredCredential(realm, user, credentialId); return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
} }
@Override @Override
@ -92,7 +72,7 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
@Override @Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
if (!supportsCredentialType(credentialType)) return false; if (!supportsCredentialType(credentialType)) return false;
return getCredentialStore().getStoredCredentialsByTypeStream(realm, user, credentialType).count() > 0; return user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType).findAny().isPresent();
} }
public boolean isConfiguredFor(RealmModel realm, UserModel user){ public boolean isConfiguredFor(RealmModel realm, UserModel user){
@ -115,7 +95,7 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
return false; return false;
} }
CredentialModel credential = getCredentialStore().getStoredCredentialById(realm, user, credentialInput.getCredentialId()); CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialInput.getCredentialId());
OTPCredentialModel otpCredentialModel = OTPCredentialModel.createFromCredentialModel(credential); OTPCredentialModel otpCredentialModel = OTPCredentialModel.createFromCredentialModel(credential);
OTPSecretData secretData = otpCredentialModel.getOTPSecretData(); OTPSecretData secretData = otpCredentialModel.getOTPSecretData();
OTPCredentialData credentialData = otpCredentialModel.getOTPCredentialData(); OTPCredentialData credentialData = otpCredentialModel.getOTPCredentialData();
@ -127,7 +107,7 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
return false; return false;
} }
otpCredentialModel.updateCounter(counter); otpCredentialModel.updateCounter(counter);
getCredentialStore().updateCredential(realm, user, otpCredentialModel); user.getUserCredentialManager().updateStoredCredential(otpCredentialModel);
return true; return true;
} else if (OTPCredentialModel.TOTP.equals(credentialData.getSubType())) { } else if (OTPCredentialModel.TOTP.equals(credentialData.getSubType())) {
TimeBasedOTP validator = new TimeBasedOTP(credentialData.getAlgorithm(), credentialData.getDigits(), credentialData.getPeriod(), policy.getLookAheadWindow()); TimeBasedOTP validator = new TimeBasedOTP(credentialData.getAlgorithm(), credentialData.getDigits(), credentialData.getPeriod(), policy.getLookAheadWindow());

View file

@ -48,12 +48,8 @@ public class PasswordCredentialProvider implements CredentialProvider<PasswordCr
this.session = session; this.session = session;
} }
protected UserCredentialStore getCredentialStore() {
return session.userCredentialManager();
}
public PasswordCredentialModel getPassword(RealmModel realm, UserModel user) { public PasswordCredentialModel getPassword(RealmModel realm, UserModel user) {
List<CredentialModel> passwords = getCredentialStore().getStoredCredentialsByTypeStream(realm, user, getType()).collect(Collectors.toList()); List<CredentialModel> passwords = user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType()).collect(Collectors.toList());
if (passwords.isEmpty()) return null; if (passwords.isEmpty()) return null;
return PasswordCredentialModel.createFromCredentialModel(passwords.get(0)); return PasswordCredentialModel.createFromCredentialModel(passwords.get(0));
} }
@ -87,34 +83,34 @@ public class PasswordCredentialProvider implements CredentialProvider<PasswordCr
credentialModel.setCreatedDate(Time.currentTimeMillis()); credentialModel.setCreatedDate(Time.currentTimeMillis());
} }
if (oldPassword == null) { // no password exists --> create new if (oldPassword == null) { // no password exists --> create new
createdCredential = getCredentialStore().createCredential(realm, user, credentialModel); createdCredential = user.getUserCredentialManager().createStoredCredential(credentialModel);
} else { // password exists --> update existing } else { // password exists --> update existing
credentialModel.setId(oldPassword.getId()); credentialModel.setId(oldPassword.getId());
getCredentialStore().updateCredential(realm, user, credentialModel); user.getUserCredentialManager().updateStoredCredential(credentialModel);
createdCredential = credentialModel; createdCredential = credentialModel;
// 2) add a password history item based on the old password // 2) add a password history item based on the old password
if (expiredPasswordsPolicyValue > 1) { if (expiredPasswordsPolicyValue > 1) {
oldPassword.setId(null); oldPassword.setId(null);
oldPassword.setType(PasswordCredentialModel.PASSWORD_HISTORY); oldPassword.setType(PasswordCredentialModel.PASSWORD_HISTORY);
getCredentialStore().createCredential(realm, user, oldPassword); user.getUserCredentialManager().createStoredCredential(oldPassword);
} }
} }
// 3) remove old password history items // 3) remove old password history items
final int passwordHistoryListMaxSize = Math.max(0, expiredPasswordsPolicyValue - 1); final int passwordHistoryListMaxSize = Math.max(0, expiredPasswordsPolicyValue - 1);
getCredentialStore().getStoredCredentialsByTypeStream(realm, user, PasswordCredentialModel.PASSWORD_HISTORY) user.getUserCredentialManager().getStoredCredentialsByTypeStream(PasswordCredentialModel.PASSWORD_HISTORY)
.sorted(CredentialModel.comparingByStartDateDesc()) .sorted(CredentialModel.comparingByStartDateDesc())
.skip(passwordHistoryListMaxSize) .skip(passwordHistoryListMaxSize)
.collect(Collectors.toList()) .collect(Collectors.toList())
.forEach(p -> getCredentialStore().removeStoredCredential(realm, user, p.getId())); .forEach(p -> user.getUserCredentialManager().removeStoredCredentialById(p.getId()));
return createdCredential; return createdCredential;
} }
@Override @Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) { public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
return getCredentialStore().removeStoredCredential(realm, user, credentialId); return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
} }
@Override @Override
@ -198,7 +194,7 @@ public class PasswordCredentialProvider implements CredentialProvider<PasswordCr
newPassword.setId(password.getId()); newPassword.setId(password.getId());
newPassword.setCreatedDate(password.getCreatedDate()); newPassword.setCreatedDate(password.getCreatedDate());
newPassword.setUserLabel(password.getUserLabel()); newPassword.setUserLabel(password.getUserLabel());
getCredentialStore().updateCredential(realm, user, newPassword); user.getUserCredentialManager().updateStoredCredential(newPassword);
return true; return true;
} }
@ -219,7 +215,7 @@ public class PasswordCredentialProvider implements CredentialProvider<PasswordCr
// Check if we are creating or updating password // Check if we are creating or updating password
UserModel user = metadataContext.getUser(); UserModel user = metadataContext.getUser();
if (user != null && session.userCredentialManager().isConfiguredFor(session.getContext().getRealm(), user, getType())) { if (user != null && user.getUserCredentialManager().isConfiguredFor(getType())) {
metadataBuilder.updateAction(UserModel.RequiredAction.UPDATE_PASSWORD.toString()); metadataBuilder.updateAction(UserModel.RequiredAction.UPDATE_PASSWORD.toString());
} else { } else {
metadataBuilder.createAction(UserModel.RequiredAction.UPDATE_PASSWORD.toString()); metadataBuilder.createAction(UserModel.RequiredAction.UPDATE_PASSWORD.toString());

View file

@ -39,15 +39,15 @@ public class RecoveryAuthnCodesCredentialProvider
public CredentialModel createCredential(RealmModel realm, UserModel user, public CredentialModel createCredential(RealmModel realm, UserModel user,
RecoveryAuthnCodesCredentialModel credentialModel) { RecoveryAuthnCodesCredentialModel credentialModel) {
session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, getType()).findFirst() user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType()).findFirst()
.ifPresent(model -> deleteCredential(realm, user, model.getId())); .ifPresent(model -> deleteCredential(realm, user, model.getId()));
return session.userCredentialManager().createCredential(realm, user, credentialModel); return user.getUserCredentialManager().createStoredCredential(credentialModel);
} }
@Override @Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) { public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
return session.userCredentialManager().removeStoredCredential(realm, user, credentialId); return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
} }
@Override @Override
@ -95,14 +95,13 @@ public class RecoveryAuthnCodesCredentialProvider
@Override @Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
return session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, credentialType).anyMatch(Objects::nonNull); return user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType).anyMatch(Objects::nonNull);
} }
@Override @Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput credentialInput) { public boolean isValid(RealmModel realm, UserModel user, CredentialInput credentialInput) {
String rawInputRecoveryAuthnCode = credentialInput.getChallengeResponse(); String rawInputRecoveryAuthnCode = credentialInput.getChallengeResponse();
Optional<CredentialModel> credential = session.userCredentialManager() Optional<CredentialModel> credential = user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType()).findFirst();
.getStoredCredentialsByTypeStream(realm, user, getType()).findFirst();
if (credential.isPresent()) { if (credential.isPresent()) {
RecoveryAuthnCodesCredentialModel credentialModel = RecoveryAuthnCodesCredentialModel RecoveryAuthnCodesCredentialModel credentialModel = RecoveryAuthnCodesCredentialModel
.createFromCredentialModel(credential.get()); .createFromCredentialModel(credential.get());
@ -112,7 +111,7 @@ public class RecoveryAuthnCodesCredentialProvider
String nextRecoveryCode = nextRecoveryAuthnCode.get().getEncodedHashedValue(); String nextRecoveryCode = nextRecoveryAuthnCode.get().getEncodedHashedValue();
if (RecoveryAuthnCodesUtils.verifyRecoveryCodeInput(rawInputRecoveryAuthnCode, nextRecoveryCode)) { if (RecoveryAuthnCodesUtils.verifyRecoveryCodeInput(rawInputRecoveryAuthnCode, nextRecoveryCode)) {
credentialModel.removeRecoveryAuthnCode(); credentialModel.removeRecoveryAuthnCode();
session.userCredentialManager().updateCredential(realm, user, credentialModel); user.getUserCredentialManager().updateStoredCredential(credentialModel);
return true; return true;
} }

View file

@ -24,12 +24,9 @@ import org.keycloak.models.UserCredentialManager;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
import org.keycloak.models.cache.CachedUserModel; import org.keycloak.models.cache.CachedUserModel;
import org.keycloak.models.cache.OnUserCache; import org.keycloak.models.cache.OnUserCache;
import org.keycloak.storage.DatastoreProvider;
import org.keycloak.storage.StorageId;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.stream.Stream; import java.util.stream.Stream;
/** /**
@ -48,77 +45,90 @@ public class UserCredentialStoreManager
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public void updateCredential(RealmModel realm, UserModel user, CredentialModel cred) { public void updateCredential(RealmModel realm, UserModel user, CredentialModel cred) {
// TODO: no longer used in non-legacy code, can be removed
user.getUserCredentialManager().updateStoredCredential(cred); user.getUserCredentialManager().updateStoredCredential(cred);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public CredentialModel createCredential(RealmModel realm, UserModel user, CredentialModel cred) { public CredentialModel createCredential(RealmModel realm, UserModel user, CredentialModel cred) {
// TODO: no longer used in non-legacy code, can be removed
return user.getUserCredentialManager().createStoredCredential(cred); return user.getUserCredentialManager().createStoredCredential(cred);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public boolean removeStoredCredential(RealmModel realm, UserModel user, String id) { public boolean removeStoredCredential(RealmModel realm, UserModel user, String id) {
// TODO: no longer used in non-legacy code, can be removed
return user.getUserCredentialManager().removeStoredCredentialById(id); return user.getUserCredentialManager().removeStoredCredentialById(id);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id) { public CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id) {
// TODO: no longer used in non-legacy code, can be removed
return user.getUserCredentialManager().getStoredCredentialById(id); return user.getUserCredentialManager().getStoredCredentialById(id);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public Stream<CredentialModel> getStoredCredentialsStream(RealmModel realm, UserModel user) { public Stream<CredentialModel> getStoredCredentialsStream(RealmModel realm, UserModel user) {
// TODO: no longer used in non-legacy code, can be removed
return user.getUserCredentialManager().getStoredCredentialsStream(); return user.getUserCredentialManager().getStoredCredentialsStream();
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public Stream<CredentialModel> getStoredCredentialsByTypeStream(RealmModel realm, UserModel user, String type) { public Stream<CredentialModel> getStoredCredentialsByTypeStream(RealmModel realm, UserModel user, String type) {
// TODO: no longer used in non-legacy code, can be removed
return user.getUserCredentialManager().getStoredCredentialsByTypeStream(type); return user.getUserCredentialManager().getStoredCredentialsByTypeStream(type);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public CredentialModel getStoredCredentialByNameAndType(RealmModel realm, UserModel user, String name, String type) { public CredentialModel getStoredCredentialByNameAndType(RealmModel realm, UserModel user, String name, String type) {
// TODO: no longer used in non-legacy code, can be removed
return user.getUserCredentialManager().getStoredCredentialByNameAndType(name, type); return user.getUserCredentialManager().getStoredCredentialByNameAndType(name, type);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public boolean moveCredentialTo(RealmModel realm, UserModel user, String id, String newPreviousCredentialId){ public boolean moveCredentialTo(RealmModel realm, UserModel user, String id, String newPreviousCredentialId){
// TODO: no longer used, can be removed
return user.getUserCredentialManager().moveStoredCredentialTo(id, newPreviousCredentialId); return user.getUserCredentialManager().moveStoredCredentialTo(id, newPreviousCredentialId);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public boolean isValid(RealmModel realm, UserModel user, CredentialInput... inputs) { public boolean isValid(RealmModel realm, UserModel user, CredentialInput... inputs) {
// TODO: no longer used, can be removed
return isValid(realm, user, Arrays.asList(inputs)); return isValid(realm, user, Arrays.asList(inputs));
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public CredentialModel createCredentialThroughProvider(RealmModel realm, UserModel user, CredentialModel model){ public CredentialModel createCredentialThroughProvider(RealmModel realm, UserModel user, CredentialModel model){
// TODO: no longer used, can be removed
return user.getUserCredentialManager().createCredentialThroughProvider(model); return user.getUserCredentialManager().createCredentialThroughProvider(model);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public void updateCredentialLabel(RealmModel realm, UserModel user, String credentialId, String userLabel){ public void updateCredentialLabel(RealmModel realm, UserModel user, String credentialId, String userLabel){
// TODO: no longer used, can be removed
user.getUserCredentialManager().updateCredentialLabel(credentialId, userLabel); user.getUserCredentialManager().updateCredentialLabel(credentialId, userLabel);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public boolean isValid(RealmModel realm, UserModel user, List<CredentialInput> inputs) { public boolean isValid(RealmModel realm, UserModel user, List<CredentialInput> inputs) {
// TODO: no longer used, can be removed
return user.getUserCredentialManager().isValid(inputs); return user.getUserCredentialManager().isValid(inputs);
} }
@Deprecated // Keep this up to and including Keycloak 19, then inline @Deprecated // Keep this up to and including Keycloak 19, then inline
public static <T> Stream<T> getCredentialProviders(KeycloakSession session, Class<T> type) { public static <T> Stream<T> getCredentialProviders(KeycloakSession session, Class<T> type) {
// TODO: no longer used, can be removed
return session.getKeycloakSessionFactory().getProviderFactoriesStream(CredentialProvider.class) return session.getKeycloakSessionFactory().getProviderFactoriesStream(CredentialProvider.class)
.filter(f -> Types.supports(type, f, CredentialProviderFactory.class)) .filter(f -> Types.supports(type, f, CredentialProviderFactory.class))
.map(f -> (T) session.getProvider(CredentialProvider.class, f.getId())); .map(f -> (T) session.getProvider(CredentialProvider.class, f.getId()));
@ -127,24 +137,28 @@ public class UserCredentialStoreManager
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) {
// TODO: no longer used, can be removed
return user.getUserCredentialManager().updateCredential(input); return user.getUserCredentialManager().updateCredential(input);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) {
// TODO: no longer used, can be removed
user.getUserCredentialManager().disableCredentialType(credentialType); user.getUserCredentialManager().disableCredentialType(credentialType);
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public Stream<String> getDisableableCredentialTypesStream(RealmModel realm, UserModel user) { public Stream<String> getDisableableCredentialTypesStream(RealmModel realm, UserModel user) {
// TODO: no longer used, can be removed
return user.getUserCredentialManager().getDisableableCredentialTypesStream(); return user.getUserCredentialManager().getDisableableCredentialTypesStream();
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public boolean isConfiguredFor(RealmModel realm, UserModel user, String type) { public boolean isConfiguredFor(RealmModel realm, UserModel user, String type) {
// TODO: no longer used, can be removed
return user.getUserCredentialManager().isConfiguredFor(type); return user.getUserCredentialManager().isConfiguredFor(type);
} }
@ -165,13 +179,15 @@ public class UserCredentialStoreManager
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, then remove it together with the OnUserCache class @Deprecated // Keep this up to and including Keycloak 19, then remove it together with the OnUserCache class
public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) { public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
// TODO: only called from legacy code (infinispan), can be removed
getCredentialProviders(session, OnUserCache.class).forEach(validator -> validator.onCache(realm, user, delegate)); getCredentialProviders(session, OnUserCache.class).forEach(validator -> validator.onCache(realm, user, delegate));
} }
@Override @Override
@Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead @Deprecated // Keep this up to and including Keycloak 19, the use methods on user.getUserCredentialManager() instead
public Stream<String> getConfiguredUserStorageCredentialTypesStream(RealmModel realm, UserModel user) { public Stream<String> getConfiguredUserStorageCredentialTypesStream(RealmModel realm, UserModel user) {
return user.getUserCredentialManager().getConfiguredUserStorageCredentialTypesStream(user); // TODO: no longer used, can be removed
return user.getUserCredentialManager().getConfiguredUserStorageCredentialTypesStream();
} }
@Override @Override

View file

@ -65,23 +65,19 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
attestationStatementConverter = new AttestationStatementConverter(objectConverter); attestationStatementConverter = new AttestationStatementConverter(objectConverter);
} }
private UserCredentialStore getCredentialStore() {
return session.userCredentialManager();
}
@Override @Override
public CredentialModel createCredential(RealmModel realm, UserModel user, WebAuthnCredentialModel credentialModel) { public CredentialModel createCredential(RealmModel realm, UserModel user, WebAuthnCredentialModel credentialModel) {
if (credentialModel.getCreatedDate() == null) { if (credentialModel.getCreatedDate() == null) {
credentialModel.setCreatedDate(Time.currentTimeMillis()); credentialModel.setCreatedDate(Time.currentTimeMillis());
} }
return getCredentialStore().createCredential(realm, user, credentialModel); return user.getUserCredentialManager().createStoredCredential(credentialModel);
} }
@Override @Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) { public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
logger.debugv("Delete WebAuthn credential. username = {0}, credentialId = {1}", user.getUsername(), credentialId); logger.debugv("Delete WebAuthn credential. username = {0}, credentialId = {1}", user.getUsername(), credentialId);
return getCredentialStore().removeStoredCredential(realm, user, credentialId); return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
} }
@Override @Override
@ -174,7 +170,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
@Override @Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
if (!supportsCredentialType(credentialType)) return false; if (!supportsCredentialType(credentialType)) return false;
return session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, credentialType).count() > 0; return user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType).count() > 0;
} }
@ -212,7 +208,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
logger.debugv("response.getAuthenticatorData().getFlags() = {0}", authenticationData.getAuthenticatorData().getFlags()); logger.debugv("response.getAuthenticatorData().getFlags() = {0}", authenticationData.getAuthenticatorData().getFlags());
CredentialModel credModel = getCredentialStore().getStoredCredentialById(realm, user, auth.getCredentialDBId()); CredentialModel credModel = user.getUserCredentialManager().getStoredCredentialById(auth.getCredentialDBId());
WebAuthnCredentialModel webAuthnCredModel = getCredentialFromModel(credModel); WebAuthnCredentialModel webAuthnCredModel = getCredentialFromModel(credModel);
// update authenticator counter // update authenticator counter
@ -221,7 +217,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
long count = auth.getCount(); long count = auth.getCount();
if (count > 0) { if (count > 0) {
webAuthnCredModel.updateCounter(count + 1); webAuthnCredModel.updateCounter(count + 1);
getCredentialStore().updateCredential(realm, user, webAuthnCredModel); user.getUserCredentialManager().updateStoredCredential(webAuthnCredModel);
} }
logger.debugf("Successfully validated WebAuthn credential for user %s", user.getUsername()); logger.debugf("Successfully validated WebAuthn credential for user %s", user.getUsername());
@ -246,7 +242,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
private List<WebAuthnCredentialModelInput> getWebAuthnCredentialModelList(RealmModel realm, UserModel user) { private List<WebAuthnCredentialModelInput> getWebAuthnCredentialModelList(RealmModel realm, UserModel user) {
return session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, getType()) return user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType())
.map(this::getCredentialInputFromCredentialModel) .map(this::getCredentialInputFromCredentialModel)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }

View file

@ -498,7 +498,7 @@ public class ExportUtils {
// Credentials - extra security, do not export credentials if service accounts // Credentials - extra security, do not export credentials if service accounts
if (internal) { if (internal) {
List<CredentialRepresentation> credReps = session.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialRepresentation> credReps = user.getUserCredentialManager().getStoredCredentialsStream()
.map(ExportUtils::exportCredential).collect(Collectors.toList()); .map(ExportUtils::exportCredential).collect(Collectors.toList());
userRep.setCredentials(credReps); userRep.setCredentials(credReps);
} }

View file

@ -51,10 +51,9 @@ public class TotpBean {
public TotpBean(KeycloakSession session, RealmModel realm, UserModel user, UriBuilder uriBuilder) { public TotpBean(KeycloakSession session, RealmModel realm, UserModel user, UriBuilder uriBuilder) {
this.uriBuilder = uriBuilder; this.uriBuilder = uriBuilder;
this.enabled = session.userCredentialManager().isConfiguredFor(realm, user, OTPCredentialModel.TYPE); this.enabled = user.getUserCredentialManager().isConfiguredFor(OTPCredentialModel.TYPE);
if (enabled) { if (enabled) {
List<CredentialModel> otpCredentials = session.userCredentialManager() List<CredentialModel> otpCredentials = user.getUserCredentialManager().getStoredCredentialsByTypeStream(OTPCredentialModel.TYPE).collect(Collectors.toList());
.getStoredCredentialsByTypeStream(realm, user, OTPCredentialModel.TYPE).collect(Collectors.toList());
if (otpCredentials.isEmpty()) { if (otpCredentials.isEmpty()) {
// Credential is configured on userStorage side. Create the "fake" credential similar like we do for the new account console // Credential is configured on userStorage side. Create the "fake" credential similar like we do for the new account console

View file

@ -11,10 +11,7 @@ public class RecoveryAuthnCodeInputLoginBean {
private final int codeNumber; private final int codeNumber;
public RecoveryAuthnCodeInputLoginBean(KeycloakSession session, RealmModel realm, UserModel user) { public RecoveryAuthnCodeInputLoginBean(KeycloakSession session, RealmModel realm, UserModel user) {
CredentialModel credentialModel = session.userCredentialManager() CredentialModel credentialModel = user.getUserCredentialManager().getStoredCredentialsByTypeStream(RecoveryAuthnCodesCredentialModel.TYPE)
.getStoredCredentialsByTypeStream(realm,
user,
RecoveryAuthnCodesCredentialModel.TYPE)
.findFirst().get(); .findFirst().get();
RecoveryAuthnCodesCredentialModel recoveryCodeCredentialModel = RecoveryAuthnCodesCredentialModel.createFromCredentialModel(credentialModel); RecoveryAuthnCodesCredentialModel recoveryCodeCredentialModel = RecoveryAuthnCodesCredentialModel.createFromCredentialModel(credentialModel);

View file

@ -48,9 +48,9 @@ public class TotpBean {
public TotpBean(KeycloakSession session, RealmModel realm, UserModel user, UriBuilder uriBuilder) { public TotpBean(KeycloakSession session, RealmModel realm, UserModel user, UriBuilder uriBuilder) {
this.realm = realm; this.realm = realm;
this.uriBuilder = uriBuilder; this.uriBuilder = uriBuilder;
this.enabled = session.userCredentialManager().isConfiguredFor(realm, user, OTPCredentialModel.TYPE); this.enabled = user.getUserCredentialManager().isConfiguredFor(OTPCredentialModel.TYPE);
if (enabled) { if (enabled) {
otpCredentials = session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, OTPCredentialModel.TYPE) otpCredentials = user.getUserCredentialManager().getStoredCredentialsByTypeStream(OTPCredentialModel.TYPE)
.collect(Collectors.toList()); .collect(Collectors.toList());
} else { } else {
otpCredentials = Collections.EMPTY_LIST; otpCredentials = Collections.EMPTY_LIST;

View file

@ -43,7 +43,7 @@ public class TotpLoginBean {
public TotpLoginBean(KeycloakSession session, RealmModel realm, UserModel user, String selectedCredentialId) { public TotpLoginBean(KeycloakSession session, RealmModel realm, UserModel user, String selectedCredentialId) {
this.userOtpCredentials = session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, OTPCredentialModel.TYPE) this.userOtpCredentials = user.getUserCredentialManager().getStoredCredentialsByTypeStream(OTPCredentialModel.TYPE)
.map(OTPCredential::new) .map(OTPCredential::new)
.collect(Collectors.toList()); .collect(Collectors.toList());

View file

@ -38,7 +38,7 @@ public class WebAuthnAuthenticatorsBean {
public WebAuthnAuthenticatorsBean(KeycloakSession session, RealmModel realm, UserModel user, String credentialType) { public WebAuthnAuthenticatorsBean(KeycloakSession session, RealmModel realm, UserModel user, String credentialType) {
// should consider multiple credentials in the future, but only single credential supported now. // should consider multiple credentials in the future, but only single credential supported now.
this.authenticators = session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, credentialType) this.authenticators = user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType)
.map(WebAuthnCredentialModel::createFromCredentialModel) .map(WebAuthnCredentialModel::createFromCredentialModel)
.map(webAuthnCredential -> { .map(webAuthnCredential -> {
String credentialId = Base64Url.encodeBase64ToBase64Url(webAuthnCredential.getWebAuthnCredentialData().getCredentialId()); String credentialId = Base64Url.encodeBase64ToBase64Url(webAuthnCredential.getWebAuthnCredentialData().getCredentialId());

View file

@ -42,7 +42,7 @@ public class HttpBasicAuthenticator implements Authenticator {
if (user != null) { if (user != null) {
final String password = usernameAndPassword[1]; final String password = usernameAndPassword[1];
final boolean valid = context.getSession().userCredentialManager().isValid(realm, user, UserCredentialModel.password(password)); final boolean valid = user.getUserCredentialManager().isValid(UserCredentialModel.password(password));
if (valid) { if (valid) {
if (isTemporarilyDisabledByBruteForce(context, user)) { if (isTemporarilyDisabledByBruteForce(context, user)) {

View file

@ -104,7 +104,7 @@ public class ApplianceBootstrap {
adminUser.setEnabled(true); adminUser.setEnabled(true);
UserCredentialModel usrCredModel = UserCredentialModel.password(password); UserCredentialModel usrCredModel = UserCredentialModel.password(password);
session.userCredentialManager().updateCredential(realm, adminUser, usrCredModel); adminUser.getUserCredentialManager().updateCredential(usrCredModel);
RoleModel adminRole = realm.getRole(AdminRoles.ADMIN); RoleModel adminRole = realm.getRole(AdminRoles.ADMIN);
adminUser.grantRole(adminRole); adminUser.grantRole(adminRole);

View file

@ -140,7 +140,7 @@ public class AccountConsole {
boolean isTotpConfigured = false; boolean isTotpConfigured = false;
boolean deleteAccountAllowed = false; boolean deleteAccountAllowed = false;
if (user != null) { if (user != null) {
isTotpConfigured = session.userCredentialManager().isConfiguredFor(realm, user, realm.getOTPPolicy().getType()); isTotpConfigured = user.getUserCredentialManager().isConfiguredFor(realm.getOTPPolicy().getType());
RoleModel deleteAccountRole = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.DELETE_ACCOUNT); RoleModel deleteAccountRole = realm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.DELETE_ACCOUNT);
deleteAccountAllowed = deleteAccountRole != null && user.hasRole(deleteAccountRole) && realm.getRequiredActionProviderByAlias(DeleteAccount.PROVIDER_ID).isEnabled(); deleteAccountAllowed = deleteAccountRole != null && user.hasRole(deleteAccountRole) && realm.getRequiredActionProviderByAlias(DeleteAccount.PROVIDER_ID).isEnabled();
} }

View file

@ -5,12 +5,13 @@ import org.jboss.logging.Logger;
import org.jboss.resteasy.annotations.cache.NoCache; import org.jboss.resteasy.annotations.cache.NoCache;
import org.keycloak.authentication.Authenticator; import org.keycloak.authentication.Authenticator;
import org.keycloak.authentication.AuthenticatorFactory; import org.keycloak.authentication.AuthenticatorFactory;
import org.keycloak.common.util.reflections.Types;
import org.keycloak.credential.CredentialMetadata; import org.keycloak.credential.CredentialMetadata;
import org.keycloak.credential.CredentialModel; import org.keycloak.credential.CredentialModel;
import org.keycloak.credential.CredentialProvider; import org.keycloak.credential.CredentialProvider;
import org.keycloak.credential.CredentialProviderFactory;
import org.keycloak.credential.CredentialTypeMetadata; import org.keycloak.credential.CredentialTypeMetadata;
import org.keycloak.credential.CredentialTypeMetadataContext; import org.keycloak.credential.CredentialTypeMetadataContext;
import org.keycloak.credential.UserCredentialStoreManager;
import org.keycloak.models.AccountRoles; import org.keycloak.models.AccountRoles;
import org.keycloak.models.AuthenticationExecutionModel; import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.AuthenticationFlowModel; import org.keycloak.models.AuthenticationFlowModel;
@ -168,11 +169,13 @@ public class AccountCredentialResource {
boolean includeUserCredentials = userCredentials == null || userCredentials; boolean includeUserCredentials = userCredentials == null || userCredentials;
List<CredentialProvider> credentialProviders = UserCredentialStoreManager.getCredentialProviders(session, CredentialProvider.class) List<CredentialProvider> credentialProviders = session.getKeycloakSessionFactory().getProviderFactoriesStream(CredentialProvider.class)
.filter(f -> Types.supports(CredentialProvider.class, f, CredentialProviderFactory.class))
.map(f -> session.getProvider(CredentialProvider.class, f.getId()))
.collect(Collectors.toList()); .collect(Collectors.toList());
Set<String> enabledCredentialTypes = getEnabledCredentialTypes(credentialProviders); Set<String> enabledCredentialTypes = getEnabledCredentialTypes(credentialProviders);
Stream<CredentialModel> modelsStream = includeUserCredentials ? session.userCredentialManager().getStoredCredentialsStream(realm, user) : Stream.empty(); Stream<CredentialModel> modelsStream = includeUserCredentials ? user.getUserCredentialManager().getStoredCredentialsStream() : Stream.empty();
List<CredentialModel> models = modelsStream.collect(Collectors.toList()); List<CredentialModel> models = modelsStream.collect(Collectors.toList());
Function<CredentialProvider, CredentialContainer> toCredentialContainer = (credentialProvider) -> { Function<CredentialProvider, CredentialContainer> toCredentialContainer = (credentialProvider) -> {
@ -201,7 +204,7 @@ public class AccountCredentialResource {
userCredentialMetadataModels = credentialMetadataList.stream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList()); userCredentialMetadataModels = credentialMetadataList.stream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList());
if (userCredentialMetadataModels.isEmpty() && if (userCredentialMetadataModels.isEmpty() &&
session.userCredentialManager().isConfiguredFor(realm, user, credentialProvider.getType())) { user.getUserCredentialManager().isConfiguredFor(credentialProvider.getType())) {
// In case user is federated in the userStorage, he may have credential configured on the userStorage side. We're // In case user is federated in the userStorage, he may have credential configured on the userStorage side. We're
// creating "dummy" credential representing the credential provided by userStorage // creating "dummy" credential representing the credential provided by userStorage
CredentialMetadataRepresentation metadataRepresentation = new CredentialMetadataRepresentation(); CredentialMetadataRepresentation metadataRepresentation = new CredentialMetadataRepresentation();
@ -276,11 +279,11 @@ public class AccountCredentialResource {
@NoCache @NoCache
public void removeCredential(final @PathParam("credentialId") String credentialId) { public void removeCredential(final @PathParam("credentialId") String credentialId) {
auth.require(AccountRoles.MANAGE_ACCOUNT); auth.require(AccountRoles.MANAGE_ACCOUNT);
CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId); CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialId);
if (credential == null) { if (credential == null) {
throw new NotFoundException("Credential not found"); throw new NotFoundException("Credential not found");
} }
session.userCredentialManager().removeStoredCredential(realm, user, credentialId); user.getUserCredentialManager().removeStoredCredentialById(credentialId);
} }
@ -296,14 +299,14 @@ public class AccountCredentialResource {
@NoCache @NoCache
public void setLabel(final @PathParam("credentialId") String credentialId, String userLabel) { public void setLabel(final @PathParam("credentialId") String credentialId, String userLabel) {
auth.require(AccountRoles.MANAGE_ACCOUNT); auth.require(AccountRoles.MANAGE_ACCOUNT);
CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId); CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialId);
if (credential == null) { if (credential == null) {
throw new NotFoundException("Credential not found"); throw new NotFoundException("Credential not found");
} }
try { try {
String label = JsonSerialization.readValue(userLabel, String.class); String label = JsonSerialization.readValue(userLabel, String.class);
session.userCredentialManager().updateCredentialLabel(realm, user, credentialId, label); user.getUserCredentialManager().updateCredentialLabel(credentialId, label);
} catch (IOException ioe) { } catch (IOException ioe) {
throw new ErrorResponseException(ErrorResponse.error(Messages.INVALID_REQUEST, Response.Status.BAD_REQUEST)); throw new ErrorResponseException(ErrorResponse.error(Messages.INVALID_REQUEST, Response.Status.BAD_REQUEST));
} }

View file

@ -600,7 +600,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
} }
UserCredentialModel cred = UserCredentialModel.password(password); UserCredentialModel cred = UserCredentialModel.password(password);
if (!session.userCredentialManager().isValid(realm, user, cred)) { if (!user.getUserCredentialManager().isValid(cred)) {
setReferrerOnPage(); setReferrerOnPage();
errorEvent.error(Errors.INVALID_USER_CREDENTIALS); errorEvent.error(Errors.INVALID_USER_CREDENTIALS);
return account.setError(Status.OK, Messages.INVALID_PASSWORD_EXISTING).createResponse(AccountPages.PASSWORD); return account.setError(Status.OK, Messages.INVALID_PASSWORD_EXISTING).createResponse(AccountPages.PASSWORD);
@ -620,7 +620,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
} }
try { try {
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(passwordNew, false)); user.getUserCredentialManager().updateCredential(UserCredentialModel.password(passwordNew, false));
} catch (ReadOnlyException mre) { } catch (ReadOnlyException mre) {
setReferrerOnPage(); setReferrerOnPage();
errorEvent.error(Errors.NOT_ALLOWED); errorEvent.error(Errors.NOT_ALLOWED);
@ -1028,7 +1028,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
} }
public static boolean isPasswordSet(KeycloakSession session, RealmModel realm, UserModel user) { public static boolean isPasswordSet(KeycloakSession session, RealmModel realm, UserModel user) {
return session.userCredentialManager().isConfiguredFor(realm, user, PasswordCredentialModel.TYPE); return user.getUserCredentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
} }
private String[] getReferrer() { private String[] getReferrer() {

View file

@ -245,7 +245,7 @@ public class LinkedAccountsResource {
} }
private boolean isPasswordSet() { private boolean isPasswordSet() {
return session.userCredentialManager().isConfiguredFor(realm, user, PasswordCredentialModel.TYPE); return user.getUserCredentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
} }
private boolean isValidProvider(String providerId) { private boolean isValidProvider(String providerId) {

View file

@ -7,16 +7,27 @@ import org.keycloak.models.credential.PasswordCredentialModel;
public class PasswordUtil { public class PasswordUtil {
private KeycloakSession session; private final UserModel user;
private UserModel user;
@Deprecated
public PasswordUtil(KeycloakSession session, UserModel user) { public PasswordUtil(KeycloakSession session, UserModel user) {
this.session = session;
this.user = user; this.user = user;
} }
public PasswordUtil(UserModel user) {
this.user = user;
}
/**
* @deprecated Instead, use {@link #isConfigured()}
*/
@Deprecated
public boolean isConfigured(KeycloakSession session, RealmModel realm, UserModel user) { public boolean isConfigured(KeycloakSession session, RealmModel realm, UserModel user) {
return session.userCredentialManager().isConfiguredFor(realm, user, PasswordCredentialModel.TYPE); return user.getUserCredentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
}
public boolean isConfigured() {
return user.getUserCredentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
} }
public void update() { public void update() {

View file

@ -587,7 +587,7 @@ public class UserResource {
auth.users().requireManage(user); auth.users().requireManage(user);
if (credentialTypes == null) return; if (credentialTypes == null) return;
for (String type : credentialTypes) { for (String type : credentialTypes) {
session.userCredentialManager().disableCredentialType(realm, user, type); user.getUserCredentialManager().disableCredentialType(type);
} }
} }
@ -610,7 +610,7 @@ public class UserResource {
} }
try { try {
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(cred.getValue(), false)); user.getUserCredentialManager().updateCredential(UserCredentialModel.password(cred.getValue(), false));
} catch (IllegalStateException ise) { } catch (IllegalStateException ise) {
throw new BadRequestException("Resetting to N old passwords is not allowed."); throw new BadRequestException("Resetting to N old passwords is not allowed.");
} catch (ReadOnlyException mre) { } catch (ReadOnlyException mre) {
@ -638,7 +638,7 @@ public class UserResource {
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public Stream<CredentialRepresentation> credentials(){ public Stream<CredentialRepresentation> credentials(){
auth.users().requireManage(user); auth.users().requireManage(user);
return session.userCredentialManager().getStoredCredentialsStream(realm, user) return user.getUserCredentialManager().getStoredCredentialsStream()
.map(ModelToRepresentation::toRepresentation) .map(ModelToRepresentation::toRepresentation)
.peek(credentialRepresentation -> credentialRepresentation.setSecretData(null)); .peek(credentialRepresentation -> credentialRepresentation.setSecretData(null));
} }
@ -658,7 +658,7 @@ public class UserResource {
// This has "requireManage" due the compatibility with "credentials()" endpoint. Strictly said, it is reading endpoint, not writing, // This has "requireManage" due the compatibility with "credentials()" endpoint. Strictly said, it is reading endpoint, not writing,
// so may be revisited if to rather use "requireView" here in the future. // so may be revisited if to rather use "requireView" here in the future.
auth.users().requireManage(user); auth.users().requireManage(user);
return session.userCredentialManager().getConfiguredUserStorageCredentialTypesStream(realm, user); return user.getUserCredentialManager().getConfiguredUserStorageCredentialTypesStream();
} }
@ -671,13 +671,13 @@ public class UserResource {
@NoCache @NoCache
public void removeCredential(final @PathParam("credentialId") String credentialId) { public void removeCredential(final @PathParam("credentialId") String credentialId) {
auth.users().requireManage(user); auth.users().requireManage(user);
CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId); CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialId);
if (credential == null) { if (credential == null) {
// we do this to make sure somebody can't phish ids // we do this to make sure somebody can't phish ids
if (auth.users().canQuery()) throw new NotFoundException("Credential not found"); if (auth.users().canQuery()) throw new NotFoundException("Credential not found");
else throw new ForbiddenException(); else throw new ForbiddenException();
} }
session.userCredentialManager().removeStoredCredential(realm, user, credentialId); user.getUserCredentialManager().removeStoredCredentialById(credentialId);
adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success(); adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
} }
@ -689,13 +689,13 @@ public class UserResource {
@Path("credentials/{credentialId}/userLabel") @Path("credentials/{credentialId}/userLabel")
public void setCredentialUserLabel(final @PathParam("credentialId") String credentialId, String userLabel) { public void setCredentialUserLabel(final @PathParam("credentialId") String credentialId, String userLabel) {
auth.users().requireManage(user); auth.users().requireManage(user);
CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId); CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialId);
if (credential == null) { if (credential == null) {
// we do this to make sure somebody can't phish ids // we do this to make sure somebody can't phish ids
if (auth.users().canQuery()) throw new NotFoundException("Credential not found"); if (auth.users().canQuery()) throw new NotFoundException("Credential not found");
else throw new ForbiddenException(); else throw new ForbiddenException();
} }
session.userCredentialManager().updateCredentialLabel(realm, user, credentialId, userLabel); user.getUserCredentialManager().updateCredentialLabel(credentialId, userLabel);
} }
/** /**
@ -717,13 +717,13 @@ public class UserResource {
@POST @POST
public void moveCredentialAfter(final @PathParam("credentialId") String credentialId, final @PathParam("newPreviousCredentialId") String newPreviousCredentialId){ public void moveCredentialAfter(final @PathParam("credentialId") String credentialId, final @PathParam("newPreviousCredentialId") String newPreviousCredentialId){
auth.users().requireManage(user); auth.users().requireManage(user);
CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId); CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialId);
if (credential == null) { if (credential == null) {
// we do this to make sure somebody can't phish ids // we do this to make sure somebody can't phish ids
if (auth.users().canQuery()) throw new NotFoundException("Credential not found"); if (auth.users().canQuery()) throw new NotFoundException("Credential not found");
else throw new ForbiddenException(); else throw new ForbiddenException();
} }
session.userCredentialManager().moveCredentialTo(realm, user, credentialId, newPreviousCredentialId); user.getUserCredentialManager().moveStoredCredentialTo(credentialId, newPreviousCredentialId);
} }
/** /**

View file

@ -631,7 +631,7 @@ public class TestingResourceProvider implements RealmResourceProvider {
if (realm == null) return false; if (realm == null) return false;
UserProvider userProvider = session.getProvider(UserProvider.class); UserProvider userProvider = session.getProvider(UserProvider.class);
UserModel user = userProvider.getUserByUsername(realm, userName); UserModel user = userProvider.getUserByUsername(realm, userName);
return session.userCredentialManager().isValid(realm, user, UserCredentialModel.password(password)); return user.getUserCredentialManager().isValid(UserCredentialModel.password(password));
} }
@GET @GET

View file

@ -56,8 +56,7 @@ public class RunHelpers {
return (FetchOnServer) session -> { return (FetchOnServer) session -> {
RealmModel realm = session.getContext().getRealm(); RealmModel realm = session.getContext().getRealm();
UserModel user = session.users().getUserByUsername(realm, username); UserModel user = session.users().getUserByUsername(realm, username);
List<CredentialModel> storedCredentialsByType = session.userCredentialManager() List<CredentialModel> storedCredentialsByType = user.getUserCredentialManager().getStoredCredentialsByTypeStream(CredentialRepresentation.PASSWORD)
.getStoredCredentialsByTypeStream(realm, user, CredentialRepresentation.PASSWORD)
.collect(Collectors.toList()); .collect(Collectors.toList());
System.out.println(storedCredentialsByType.size()); System.out.println(storedCredentialsByType.size());
return storedCredentialsByType.get(0); return storedCredentialsByType.get(0);

View file

@ -70,7 +70,7 @@ public class LDAPTestUtils {
UserCredentialModel creds = UserCredentialModel.password(password); UserCredentialModel creds = UserCredentialModel.password(password);
session.userCredentialManager().updateCredential(realm, user, creds); user.getUserCredentialManager().updateCredential(creds);
return user; return user;
} }
@ -83,7 +83,7 @@ public class LDAPTestUtils {
if (password == null) { if (password == null) {
return; return;
} }
session.userCredentialManager().updateCredential(appRealm, user, (UserCredentialModel) UserCredentialModel.password(username)); user.getUserCredentialManager().updateCredential((UserCredentialModel) UserCredentialModel.password(username));
} }
public static LDAPObject addLDAPUser(LDAPStorageProvider ldapProvider, RealmModel realm, final String username, public static LDAPObject addLDAPUser(LDAPStorageProvider ldapProvider, RealmModel realm, final String username,

View file

@ -487,8 +487,7 @@ public class AccountFormServiceTest extends AbstractTestRealmKeycloakTest {
RealmModel realm = session.getContext().getRealm(); RealmModel realm = session.getContext().getRealm();
UserModel user = session.users().getUserById(realm, uId); UserModel user = session.users().getUserById(realm, uId);
assertThat(user, Matchers.notNullValue()); assertThat(user, Matchers.notNullValue());
List<CredentialModel> storedCredentials = session.userCredentialManager() List<CredentialModel> storedCredentials = user.getUserCredentialManager().getStoredCredentialsStream().collect(Collectors.toList());
.getStoredCredentialsStream(realm, user).collect(Collectors.toList());
assertThat(storedCredentials, Matchers.hasSize(expectedNumberOfStoredCredentials)); assertThat(storedCredentials, Matchers.hasSize(expectedNumberOfStoredCredentials));
}); });
} }

View file

@ -115,11 +115,11 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
UserModel admin = session.users().addUser(realm, "salesManager"); UserModel admin = session.users().addUser(realm, "salesManager");
admin.setEnabled(true); admin.setEnabled(true);
session.userCredentialManager().updateCredential(realm, admin, UserCredentialModel.password("password")); admin.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
admin = session.users().addUser(realm, "sales-admin"); admin = session.users().addUser(realm, "sales-admin");
admin.setEnabled(true); admin.setEnabled(true);
session.userCredentialManager().updateCredential(realm, admin, UserCredentialModel.password("password")); admin.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
UserModel user = session.users().addUser(realm, "salesman"); UserModel user = session.users().addUser(realm, "salesman");
user.setEnabled(true); user.setEnabled(true);
@ -217,32 +217,32 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
UserModel nomapAdmin = session.users().addUser(realm, "nomap-admin"); UserModel nomapAdmin = session.users().addUser(realm, "nomap-admin");
nomapAdmin.setEnabled(true); nomapAdmin.setEnabled(true);
session.userCredentialManager().updateCredential(realm, nomapAdmin, UserCredentialModel.password("password")); nomapAdmin.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
nomapAdmin.grantRole(adminRole); nomapAdmin.grantRole(adminRole);
UserModel anotherAdmin = session.users().addUser(realm, "anotherAdmin"); UserModel anotherAdmin = session.users().addUser(realm, "anotherAdmin");
anotherAdmin.setEnabled(true); anotherAdmin.setEnabled(true);
session.userCredentialManager().updateCredential(realm, anotherAdmin, UserCredentialModel.password("password")); anotherAdmin.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
anotherAdmin.grantRole(adminRole); anotherAdmin.grantRole(adminRole);
UserModel authorizedUser = session.users().addUser(realm, "authorized"); UserModel authorizedUser = session.users().addUser(realm, "authorized");
authorizedUser.setEnabled(true); authorizedUser.setEnabled(true);
session.userCredentialManager().updateCredential(realm, authorizedUser, UserCredentialModel.password("password")); authorizedUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
authorizedUser.grantRole(mapperRole); authorizedUser.grantRole(mapperRole);
authorizedUser.grantRole(managerRole); authorizedUser.grantRole(managerRole);
UserModel authorizedComposite = session.users().addUser(realm, "authorizedComposite"); UserModel authorizedComposite = session.users().addUser(realm, "authorizedComposite");
authorizedComposite.setEnabled(true); authorizedComposite.setEnabled(true);
session.userCredentialManager().updateCredential(realm, authorizedComposite, UserCredentialModel.password("password")); authorizedComposite.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
authorizedComposite.grantRole(compositeRole); authorizedComposite.grantRole(compositeRole);
UserModel unauthorizedUser = session.users().addUser(realm, "unauthorized"); UserModel unauthorizedUser = session.users().addUser(realm, "unauthorized");
unauthorizedUser.setEnabled(true); unauthorizedUser.setEnabled(true);
session.userCredentialManager().updateCredential(realm, unauthorizedUser, UserCredentialModel.password("password")); unauthorizedUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
UserModel unauthorizedMapper = session.users().addUser(realm, "unauthorizedMapper"); UserModel unauthorizedMapper = session.users().addUser(realm, "unauthorizedMapper");
unauthorizedMapper.setEnabled(true); unauthorizedMapper.setEnabled(true);
session.userCredentialManager().updateCredential(realm, unauthorizedMapper, UserCredentialModel.password("password")); unauthorizedMapper.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
unauthorizedMapper.grantRole(managerRole); unauthorizedMapper.grantRole(managerRole);
UserModel user1 = session.users().addUser(realm, "user1"); UserModel user1 = session.users().addUser(realm, "user1");
@ -260,11 +260,11 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
groupManager.grantRole(queryUsersRole); groupManager.grantRole(queryUsersRole);
groupManager.setEnabled(true); groupManager.setEnabled(true);
groupManager.grantRole(mapperRole); groupManager.grantRole(mapperRole);
session.userCredentialManager().updateCredential(realm, groupManager, UserCredentialModel.password("password")); groupManager.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
UserModel groupManagerNoMapper = session.users().addUser(realm, "noMapperGroupManager"); UserModel groupManagerNoMapper = session.users().addUser(realm, "noMapperGroupManager");
groupManagerNoMapper.setEnabled(true); groupManagerNoMapper.setEnabled(true);
session.userCredentialManager().updateCredential(realm, groupManagerNoMapper, UserCredentialModel.password("password")); groupManagerNoMapper.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
groupManagerNoMapper.grantRole(queryGroupsRole); groupManagerNoMapper.grantRole(queryGroupsRole);
groupManagerNoMapper.grantRole(queryUsersRole); groupManagerNoMapper.grantRole(queryUsersRole);
@ -282,7 +282,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
clientMapper.setEnabled(true); clientMapper.setEnabled(true);
clientMapper.grantRole(managerRole); clientMapper.grantRole(managerRole);
clientMapper.grantRole(queryUsersRole); clientMapper.grantRole(queryUsersRole);
session.userCredentialManager().updateCredential(realm, clientMapper, UserCredentialModel.password("password")); clientMapper.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
Policy clientMapperPolicy = permissions.clients().mapRolesPermission(client); Policy clientMapperPolicy = permissions.clients().mapRolesPermission(client);
UserPolicyRepresentation userRep = new UserPolicyRepresentation(); UserPolicyRepresentation userRep = new UserPolicyRepresentation();
userRep.setName("userClientMapper"); userRep.setName("userClientMapper");
@ -293,7 +293,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
UserModel clientManager = session.users().addUser(realm, "clientManager"); UserModel clientManager = session.users().addUser(realm, "clientManager");
clientManager.setEnabled(true); clientManager.setEnabled(true);
clientManager.grantRole(queryClientsRole); clientManager.grantRole(queryClientsRole);
session.userCredentialManager().updateCredential(realm, clientManager, UserCredentialModel.password("password")); clientManager.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
Policy clientManagerPolicy = permissions.clients().managePermission(client); Policy clientManagerPolicy = permissions.clients().managePermission(client);
userRep = new UserPolicyRepresentation(); userRep = new UserPolicyRepresentation();
@ -306,7 +306,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
UserModel clientConfigurer = session.users().addUser(realm, "clientConfigurer"); UserModel clientConfigurer = session.users().addUser(realm, "clientConfigurer");
clientConfigurer.setEnabled(true); clientConfigurer.setEnabled(true);
clientConfigurer.grantRole(queryClientsRole); clientConfigurer.grantRole(queryClientsRole);
session.userCredentialManager().updateCredential(realm, clientConfigurer, UserCredentialModel.password("password")); clientConfigurer.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
Policy clientConfigurePolicy = permissions.clients().configurePermission(client); Policy clientConfigurePolicy = permissions.clients().configurePermission(client);
userRep = new UserPolicyRepresentation(); userRep = new UserPolicyRepresentation();
@ -320,7 +320,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
groupViewer.grantRole(queryGroupsRole); groupViewer.grantRole(queryGroupsRole);
groupViewer.grantRole(queryUsersRole); groupViewer.grantRole(queryUsersRole);
groupViewer.setEnabled(true); groupViewer.setEnabled(true);
session.userCredentialManager().updateCredential(realm, groupViewer, UserCredentialModel.password("password")); groupViewer.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
UserPolicyRepresentation groupViewMembersRep = new UserPolicyRepresentation(); UserPolicyRepresentation groupViewMembersRep = new UserPolicyRepresentation();
groupViewMembersRep.setName("groupMemberViewers"); groupViewMembersRep.setName("groupMemberViewers");
@ -778,7 +778,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
UserModel realmUser = session.users().addUser(realm, "realm-admin"); UserModel realmUser = session.users().addUser(realm, "realm-admin");
realmUser.grantRole(realmAdminRole); realmUser.grantRole(realmAdminRole);
realmUser.setEnabled(true); realmUser.setEnabled(true);
session.userCredentialManager().updateCredential(realm, realmUser, UserCredentialModel.password("password")); realmUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
} }
// KEYCLOAK-5152 // KEYCLOAK-5152
@ -977,12 +977,12 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
GroupModel customerAGroup = session.groups().createGroup(realm, "Customer A"); GroupModel customerAGroup = session.groups().createGroup(realm, "Customer A");
UserModel customerAManager = session.users().addUser(realm, "customer-a-manager"); UserModel customerAManager = session.users().addUser(realm, "customer-a-manager");
session.userCredentialManager().updateCredential(realm, customerAManager, UserCredentialModel.password("password")); customerAManager.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID); ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
customerAManager.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_USERS)); customerAManager.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_USERS));
customerAManager.setEnabled(true); customerAManager.setEnabled(true);
UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user"); UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user");
session.userCredentialManager().updateCredential(realm, regularAdminUser, UserCredentialModel.password("password")); regularAdminUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.VIEW_USERS)); regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.VIEW_USERS));
regularAdminUser.setEnabled(true); regularAdminUser.setEnabled(true);
@ -1073,7 +1073,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID); ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user"); UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user");
session.userCredentialManager().updateCredential(realm, regularAdminUser, UserCredentialModel.password("password")); regularAdminUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_CLIENTS)); regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_CLIENTS));
regularAdminUser.setEnabled(true); regularAdminUser.setEnabled(true);
@ -1253,7 +1253,7 @@ public class FineGrainAdminUnitTest extends AbstractKeycloakTest {
ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID); ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user"); UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user");
session.userCredentialManager().updateCredential(realm, regularAdminUser, UserCredentialModel.password("password")); regularAdminUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_CLIENTS)); regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_CLIENTS));
regularAdminUser.setEnabled(true); regularAdminUser.setEnabled(true);

View file

@ -82,27 +82,27 @@ public class IllegalAdminUpgradeTest extends AbstractKeycloakTest {
UserModel realmUser = session.users().addUser(realm, "userAdmin"); UserModel realmUser = session.users().addUser(realm, "userAdmin");
realmUser.grantRole(realmManageUsers); realmUser.grantRole(realmManageUsers);
realmUser.setEnabled(true); realmUser.setEnabled(true);
session.userCredentialManager().updateCredential(realm, realmUser, UserCredentialModel.password("password")); realmUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
UserModel masterUser = session.users().addUser(master, "userAdmin"); UserModel masterUser = session.users().addUser(master, "userAdmin");
masterUser.grantRole(masterManageUsers); masterUser.grantRole(masterManageUsers);
masterUser.setEnabled(true); masterUser.setEnabled(true);
session.userCredentialManager().updateCredential(master, masterUser, UserCredentialModel.password("password")); masterUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
UserModel masterAdmin = session.users().addUser(master, "masterAdmin"); UserModel masterAdmin = session.users().addUser(master, "masterAdmin");
masterAdmin.grantRole(masterMasterManageUSers); masterAdmin.grantRole(masterMasterManageUSers);
masterAdmin.setEnabled(true); masterAdmin.setEnabled(true);
session.userCredentialManager().updateCredential(master, masterAdmin, UserCredentialModel.password("password")); masterAdmin.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
UserModel user = session.users().addUser(master, "user"); UserModel user = session.users().addUser(master, "user");
user.grantRole(masterManageUsers); user.grantRole(masterManageUsers);
user.setEnabled(true); user.setEnabled(true);
session.userCredentialManager().updateCredential(master, user, UserCredentialModel.password("password")); user.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
user = session.users().addUser(realm, "user"); user = session.users().addUser(realm, "user");
user.grantRole(realmManageUsers); user.grantRole(realmManageUsers);
user.setEnabled(true); user.setEnabled(true);
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password")); user.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
} }
//@Test //@Test

View file

@ -778,7 +778,7 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
} }
try { try {
UserCredentialModel cred = UserCredentialModel.password("PoopyPoop1", true); UserCredentialModel cred = UserCredentialModel.password("PoopyPoop1", true);
session.userCredentialManager().updateCredential(appRealm, user, cred); user.getUserCredentialManager().updateCredential(cred);
Assert.fail("should fail"); Assert.fail("should fail");
} catch (ReadOnlyException e) { } catch (ReadOnlyException e) {
@ -953,13 +953,12 @@ public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId()); Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId());
UserCredentialModel cred = UserCredentialModel.password("Candycand1", true); UserCredentialModel cred = UserCredentialModel.password("Candycand1", true);
session.userCredentialManager().updateCredential(appRealm, user, cred); user.getUserCredentialManager().updateCredential(cred);
CredentialModel userCredentialValueModel = session.userCredentialManager() CredentialModel userCredentialValueModel = user.getUserCredentialManager().getStoredCredentialsByTypeStream(PasswordCredentialModel.TYPE)
.getStoredCredentialsByTypeStream(appRealm, user, PasswordCredentialModel.TYPE)
.findFirst().orElse(null); .findFirst().orElse(null);
Assert.assertNotNull(userCredentialValueModel); Assert.assertNotNull(userCredentialValueModel);
Assert.assertEquals(PasswordCredentialModel.TYPE, userCredentialValueModel.getType()); Assert.assertEquals(PasswordCredentialModel.TYPE, userCredentialValueModel.getType());
Assert.assertTrue(session.userCredentialManager().isValid(appRealm, user, cred)); Assert.assertTrue(user.getUserCredentialManager().isValid(cred));
// LDAP password is still unchanged // LDAP password is still unchanged
try { try {

View file

@ -96,7 +96,7 @@ public class LDAPUserMultipleCredentialTest extends AbstractLDAPTest {
LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), user2, "some-other-password"); LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), user2, "some-other-password");
UserModel userWithOtp = session.users().getUserByUsername(appRealm, "test-user-with-otp"); UserModel userWithOtp = session.users().getUserByUsername(appRealm, "test-user-with-otp");
OTPCredentialModel otpCredential = OTPCredentialModel.createHOTP("DJmQfC73VGFhw7D4QJ8A", 6, 0, "HmacSHA1"); OTPCredentialModel otpCredential = OTPCredentialModel.createHOTP("DJmQfC73VGFhw7D4QJ8A", 6, 0, "HmacSHA1");
session.userCredentialManager().createCredential(appRealm, userWithOtp, otpCredential); userWithOtp.getUserCredentialManager().createStoredCredential(otpCredential);
}); });
} }

View file

@ -292,8 +292,7 @@ public class BackwardsCompatibilityUserStorageTest extends AbstractAuthTest {
testingClient.server().run(session -> { testingClient.server().run(session -> {
RealmModel realm1 = session.realms().getRealmByName("test"); RealmModel realm1 = session.realms().getRealmByName("test");
UserModel user1 = session.users().getUserByUsername(realm1, "otp1"); UserModel user1 = session.users().getUserByUsername(realm1, "otp1");
Assert.assertEquals(0, session.userCredentialManager() Assert.assertEquals(0, user1.getUserCredentialManager().getStoredCredentialsStream().count());
.getStoredCredentialsStream(realm1, user1).count());
}); });
} }

View file

@ -14,9 +14,11 @@ import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.common.Profile; import org.keycloak.common.Profile;
import org.keycloak.common.util.MultivaluedHashMap; import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.common.util.ObjectUtil; import org.keycloak.common.util.ObjectUtil;
import org.keycloak.common.util.reflections.Types;
import org.keycloak.credential.CredentialAuthentication; import org.keycloak.credential.CredentialAuthentication;
import org.keycloak.credential.CredentialModel; import org.keycloak.credential.CredentialModel;
import org.keycloak.credential.UserCredentialStoreManager; import org.keycloak.credential.CredentialProvider;
import org.keycloak.credential.CredentialProviderFactory;
import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel; import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel; import org.keycloak.models.UserModel;
@ -229,7 +231,9 @@ public class UserStorageTest extends AbstractAuthTest {
@Test @Test
@ModelTest @ModelTest
public void testCast(KeycloakSession session) throws Exception { public void testCast(KeycloakSession session) throws Exception {
UserCredentialStoreManager.getCredentialProviders(session, CredentialAuthentication.class).collect(Collectors.toList()); session.getKeycloakSessionFactory().getProviderFactoriesStream(CredentialProvider.class)
.filter(f -> Types.supports(CredentialAuthentication.class, f, CredentialProviderFactory.class))
.map(f -> (CredentialAuthentication) session.getProvider(CredentialProvider.class, f.getId())).collect(Collectors.toList());
} }
@Test @Test
@ -883,19 +887,19 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor"); UserModel user = currentSession.users().getUserByUsername(realm, "thor");
Assert.assertFalse(StorageId.isLocalStorage(user)); Assert.assertFalse(StorageId.isLocalStorage(user));
Stream<CredentialModel> credentials = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user); Stream<CredentialModel> credentials = user.getUserCredentialManager().getStoredCredentialsStream();
org.keycloak.testsuite.Assert.assertEquals(0, credentials.count()); org.keycloak.testsuite.Assert.assertEquals(0, credentials.count());
// Create password // Create password
CredentialModel passwordCred = PasswordCredentialModel.createFromValues("my-algorithm", "theSalt".getBytes(), 22, "ABC"); CredentialModel passwordCred = PasswordCredentialModel.createFromValues("my-algorithm", "theSalt".getBytes(), 22, "ABC");
passwordCred = currentSession.userCredentialManager().createCredential(realm, user, passwordCred); passwordCred = user.getUserCredentialManager().createStoredCredential(passwordCred);
passwordId.set(passwordCred.getId()); passwordId.set(passwordCred.getId());
// Create Password and 2 OTP credentials (password was already created) // Create Password and 2 OTP credentials (password was already created)
CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1"); CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1");
CredentialModel otp2 = OTPCredentialModel.createFromPolicy(realm, "secret2"); CredentialModel otp2 = OTPCredentialModel.createFromPolicy(realm, "secret2");
otp1 = currentSession.userCredentialManager().createCredential(realm, user, otp1); otp1 = user.getUserCredentialManager().createStoredCredential(otp1);
otp2 = currentSession.userCredentialManager().createCredential(realm, user, otp2); otp2 = user.getUserCredentialManager().createStoredCredential(otp2);
otp1Id.set(otp1.getId()); otp1Id.set(otp1.getId());
otp2Id.set(otp2.getId()); otp2Id.set(otp2.getId());
}); });
@ -906,18 +910,18 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor"); UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: password, otp1, otp2 // Assert priorities: password, otp1, otp2
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, passwordId.get(), otp1Id.get(), otp2Id.get()); assertOrder(list, passwordId.get(), otp1Id.get(), otp2Id.get());
// Assert can't move password when newPreviousCredential not found // Assert can't move password when newPreviousCredential not found
assertFalse(currentSession.userCredentialManager().moveCredentialTo(realm, user, passwordId.get(), "not-known")); assertFalse(user.getUserCredentialManager().moveStoredCredentialTo(passwordId.get(), "not-known"));
// Assert can't move credential when not found // Assert can't move credential when not found
assertFalse(currentSession.userCredentialManager().moveCredentialTo(realm, user, "not-known", otp2Id.get())); assertFalse(user.getUserCredentialManager().moveStoredCredentialTo("not-known", otp2Id.get()));
// Move otp2 up // Move otp2 up
assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), passwordId.get())); assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), passwordId.get()));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -925,12 +929,12 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor"); UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: password, otp2, otp1 // Assert priorities: password, otp2, otp1
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, passwordId.get(), otp2Id.get(), otp1Id.get()); assertOrder(list, passwordId.get(), otp2Id.get(), otp1Id.get());
// Move otp2 to the top // Move otp2 to the top
org.keycloak.testsuite.Assert.assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), null)); org.keycloak.testsuite.Assert.assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), null));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -938,12 +942,12 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor"); UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: otp2, password, otp1 // Assert priorities: otp2, password, otp1
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, otp2Id.get(), passwordId.get(), otp1Id.get()); assertOrder(list, otp2Id.get(), passwordId.get(), otp1Id.get());
// Move password down // Move password down
assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, passwordId.get(), otp1Id.get())); assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(passwordId.get(), otp1Id.get()));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -951,12 +955,12 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor"); UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: otp2, otp1, password // Assert priorities: otp2, otp1, password
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, otp2Id.get(), otp1Id.get(), passwordId.get()); assertOrder(list, otp2Id.get(), otp1Id.get(), passwordId.get());
// Remove otp2 down two positions // Remove otp2 down two positions
assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), passwordId.get())); assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), passwordId.get()));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -964,12 +968,12 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor"); UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: otp2, otp1, password // Assert priorities: otp2, otp1, password
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, otp1Id.get(), passwordId.get(), otp2Id.get()); assertOrder(list, otp1Id.get(), passwordId.get(), otp2Id.get());
// Remove password // Remove password
assertTrue(currentSession.userCredentialManager().removeStoredCredential(realm, user, passwordId.get())); assertTrue(user.getUserCredentialManager().removeStoredCredentialById(passwordId.get()));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -977,7 +981,7 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor"); UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: otp2, password // Assert priorities: otp2, password
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, otp1Id.get(), otp2Id.get()); assertOrder(list, otp1Id.get(), otp2Id.get());
}); });
@ -993,7 +997,7 @@ public class UserStorageTest extends AbstractAuthTest {
Assert.assertFalse(StorageId.isLocalStorage(user)); Assert.assertFalse(StorageId.isLocalStorage(user));
CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1"); CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1");
session.userCredentialManager().createCredential(realm, user, otp1); user.getUserCredentialManager().createStoredCredential(otp1);
}); });
UserResource user1 = ApiUtil.findUserByUsernameId(testRealmResource(), "thor"); UserResource user1 = ApiUtil.findUserByUsernameId(testRealmResource(), "thor");

View file

@ -242,7 +242,7 @@ public class PasswordHashingTest extends AbstractTestRealmKeycloakTest {
return testingClient.server("test").fetch(session -> { return testingClient.server("test").fetch(session -> {
RealmModel realm = session.getContext().getRealm(); RealmModel realm = session.getContext().getRealm();
UserModel user = session.users().getUserByUsername(realm, username); UserModel user = session.users().getUserByUsername(realm, username);
return session.userCredentialManager().getStoredCredentialsByTypeStream(realm, user, CredentialRepresentation.PASSWORD) return user.getUserCredentialManager().getStoredCredentialsByTypeStream(CredentialRepresentation.PASSWORD)
.findFirst().orElse(null); .findFirst().orElse(null);
}, CredentialModel.class); }, CredentialModel.class);
} }

View file

@ -120,7 +120,7 @@ public class RecoveryAuthnCodesAuthenticatorTest extends AbstractTestRealmKeyclo
generatedRecoveryAuthnCodes, generatedRecoveryAuthnCodes,
System.currentTimeMillis(), System.currentTimeMillis(),
null); null);
session.userCredentialManager().createCredential(realm, user, recoveryAuthnCodesCred); user.getUserCredentialManager().createStoredCredential(recoveryAuthnCodesCred);
}); });
passwordPage.clickTryAnotherWayLink(); passwordPage.clickTryAnotherWayLink();
selectAuthenticatorPage.assertCurrent(); selectAuthenticatorPage.assertCurrent();
@ -194,7 +194,7 @@ public class RecoveryAuthnCodesAuthenticatorTest extends AbstractTestRealmKeyclo
generatedRecoveryAuthnCodes, generatedRecoveryAuthnCodes,
System.currentTimeMillis(), System.currentTimeMillis(),
null); null);
session.userCredentialManager().createCredential(realm, user, recoveryAuthnCodesCred); user.getUserCredentialManager().createStoredCredential(recoveryAuthnCodesCred);
}); });
passwordPage.clickTryAnotherWayLink(); passwordPage.clickTryAnotherWayLink();
selectAuthenticatorPage.assertCurrent(); selectAuthenticatorPage.assertCurrent();

View file

@ -42,7 +42,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest {
RealmModel realm = currentSession.realms().getRealmByName("test"); RealmModel realm = currentSession.realms().getRealmByName("test");
UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost");
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
Assert.assertEquals(1, list.size()); Assert.assertEquals(1, list.size());
passwordId.set(list.get(0).getId()); passwordId.set(list.get(0).getId());
@ -50,8 +50,8 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest {
// Create 2 OTP credentials (password was already created) // Create 2 OTP credentials (password was already created)
CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1"); CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1");
CredentialModel otp2 = OTPCredentialModel.createFromPolicy(realm, "secret2"); CredentialModel otp2 = OTPCredentialModel.createFromPolicy(realm, "secret2");
otp1 = currentSession.userCredentialManager().createCredential(realm, user, otp1); otp1 = user.getUserCredentialManager().createStoredCredential(otp1);
otp2 = currentSession.userCredentialManager().createCredential(realm, user, otp2); otp2 = user.getUserCredentialManager().createStoredCredential(otp2);
otp1Id.set(otp1.getId()); otp1Id.set(otp1.getId());
otp2Id.set(otp2.getId()); otp2Id.set(otp2.getId());
}); });
@ -62,18 +62,18 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest {
UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost");
// Assert priorities: password, otp1, otp2 // Assert priorities: password, otp1, otp2
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, passwordId.get(), otp1Id.get(), otp2Id.get()); assertOrder(list, passwordId.get(), otp1Id.get(), otp2Id.get());
// Assert can't move password when newPreviousCredential not found // Assert can't move password when newPreviousCredential not found
Assert.assertFalse(currentSession.userCredentialManager().moveCredentialTo(realm, user, passwordId.get(), "not-known")); Assert.assertFalse(user.getUserCredentialManager().moveStoredCredentialTo(passwordId.get(), "not-known"));
// Assert can't move credential when not found // Assert can't move credential when not found
Assert.assertFalse(currentSession.userCredentialManager().moveCredentialTo(realm, user, "not-known", otp2Id.get())); Assert.assertFalse(user.getUserCredentialManager().moveStoredCredentialTo("not-known", otp2Id.get()));
// Move otp2 up 1 position // Move otp2 up 1 position
Assert.assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), passwordId.get())); Assert.assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), passwordId.get()));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -81,12 +81,12 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest {
UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost");
// Assert priorities: password, otp2, otp1 // Assert priorities: password, otp2, otp1
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, passwordId.get(), otp2Id.get(), otp1Id.get()); assertOrder(list, passwordId.get(), otp2Id.get(), otp1Id.get());
// Move otp2 to the top // Move otp2 to the top
Assert.assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), null)); Assert.assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), null));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -94,12 +94,12 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest {
UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost");
// Assert priorities: otp2, password, otp1 // Assert priorities: otp2, password, otp1
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, otp2Id.get(), passwordId.get(), otp1Id.get()); assertOrder(list, otp2Id.get(), passwordId.get(), otp1Id.get());
// Move password down // Move password down
Assert.assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, passwordId.get(), otp1Id.get())); Assert.assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(passwordId.get(), otp1Id.get()));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -107,12 +107,12 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest {
UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost");
// Assert priorities: otp2, otp1, password // Assert priorities: otp2, otp1, password
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, otp2Id.get(), otp1Id.get(), passwordId.get()); assertOrder(list, otp2Id.get(), otp1Id.get(), passwordId.get());
// Remove otp2 down two positions // Remove otp2 down two positions
Assert.assertTrue(currentSession.userCredentialManager().moveCredentialTo(realm, user, otp2Id.get(), passwordId.get())); Assert.assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), passwordId.get()));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -120,12 +120,12 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest {
UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost");
// Assert priorities: otp2, otp1, password // Assert priorities: otp2, otp1, password
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, otp1Id.get(), passwordId.get(), otp2Id.get()); assertOrder(list, otp1Id.get(), passwordId.get(), otp2Id.get());
// Remove password // Remove password
Assert.assertTrue(currentSession.userCredentialManager().removeStoredCredential(realm, user, passwordId.get())); Assert.assertTrue(user.getUserCredentialManager().removeStoredCredentialById(passwordId.get()));
}); });
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> { KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -133,7 +133,7 @@ public class CredentialModelTest extends AbstractTestRealmKeycloakTest {
UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost"); UserModel user = currentSession.users().getUserByUsername(realm, "test-user@localhost");
// Assert priorities: otp2, password // Assert priorities: otp2, password
List<CredentialModel> list = currentSession.userCredentialManager().getStoredCredentialsStream(realm, user) List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
.collect(Collectors.toList()); .collect(Collectors.toList());
assertOrder(list, otp1Id.get(), otp2Id.get()); assertOrder(list, otp1Id.get(), otp2Id.get());
}); });

View file

@ -88,13 +88,13 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest {
Assert.assertNotEquals(r1user1.getId(), r2user1.getId()); Assert.assertNotEquals(r1user1.getId(), r2user1.getId());
// Test password // Test password
currentSession.userCredentialManager().updateCredential(realm1, r1user1, UserCredentialModel.password("pass1")); r1user1.getUserCredentialManager().updateCredential(UserCredentialModel.password("pass1"));
currentSession.userCredentialManager().updateCredential(realm2, r2user1, UserCredentialModel.password("pass2")); r2user1.getUserCredentialManager().updateCredential(UserCredentialModel.password("pass2"));
Assert.assertTrue(currentSession.userCredentialManager().isValid(realm1, r1user1, UserCredentialModel.password("pass1"))); Assert.assertTrue(r1user1.getUserCredentialManager().isValid(UserCredentialModel.password("pass1")));
Assert.assertFalse(currentSession.userCredentialManager().isValid(realm1, r1user1, UserCredentialModel.password("pass2"))); Assert.assertFalse(r1user1.getUserCredentialManager().isValid(UserCredentialModel.password("pass2")));
Assert.assertFalse(currentSession.userCredentialManager().isValid(realm2, r2user1, UserCredentialModel.password("pass1"))); Assert.assertFalse(r2user1.getUserCredentialManager().isValid(UserCredentialModel.password("pass1")));
Assert.assertTrue(currentSession.userCredentialManager().isValid(realm2, r2user1, UserCredentialModel.password("pass2"))); Assert.assertTrue(r2user1.getUserCredentialManager().isValid(UserCredentialModel.password("pass2")));
// Test searching // Test searching
Assert.assertEquals(2, currentSession.users().searchForUserStream(realm1, "user").count()); Assert.assertEquals(2, currentSession.users().searchForUserStream(realm1, "user").count());

View file

@ -224,13 +224,13 @@ public class ClientTokenExchangeSAML2Test extends AbstractKeycloakTest {
UserModel user = session.users().addUser(realm, "user"); UserModel user = session.users().addUser(realm, "user");
user.setEnabled(true); user.setEnabled(true);
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password")); user.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
user.grantRole(exampleRole); user.grantRole(exampleRole);
user.grantRole(impersonateRole); user.grantRole(impersonateRole);
UserModel bad = session.users().addUser(realm, "bad-impersonator"); UserModel bad = session.users().addUser(realm, "bad-impersonator");
bad.setEnabled(true); bad.setEnabled(true);
session.userCredentialManager().updateCredential(realm, bad, UserCredentialModel.password("password")); bad.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
} }
@Override @Override
@ -704,7 +704,7 @@ public class ClientTokenExchangeSAML2Test extends AbstractKeycloakTest {
UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user"); UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user");
impersonatedUser.setEnabled(true); impersonatedUser.setEnabled(true);
session.userCredentialManager().updateCredential(realm, impersonatedUser, UserCredentialModel.password("password")); impersonatedUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
impersonatedUser.grantRole(exampleRole); impersonatedUser.grantRole(exampleRole);
} }

View file

@ -237,13 +237,13 @@ public class ClientTokenExchangeTest extends AbstractKeycloakTest {
UserModel user = session.users().addUser(realm, "user"); UserModel user = session.users().addUser(realm, "user");
user.setEnabled(true); user.setEnabled(true);
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password")); user.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
user.grantRole(exampleRole); user.grantRole(exampleRole);
user.grantRole(impersonateRole); user.grantRole(impersonateRole);
UserModel bad = session.users().addUser(realm, "bad-impersonator"); UserModel bad = session.users().addUser(realm, "bad-impersonator");
bad.setEnabled(true); bad.setEnabled(true);
session.userCredentialManager().updateCredential(realm, bad, UserCredentialModel.password("password")); bad.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
} }
public static void setUpUserImpersonatePermissions(KeycloakSession session) { public static void setUpUserImpersonatePermissions(KeycloakSession session) {
@ -863,7 +863,7 @@ public class ClientTokenExchangeTest extends AbstractKeycloakTest {
UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user"); UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user");
impersonatedUser.setEnabled(true); impersonatedUser.setEnabled(true);
session.userCredentialManager().updateCredential(realm, impersonatedUser, UserCredentialModel.password("password")); impersonatedUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
impersonatedUser.grantRole(exampleRole); impersonatedUser.grantRole(exampleRole);
} }

View file

@ -77,7 +77,7 @@ public class UserCommands {
user.setEnabled(true); user.setEnabled(true);
user.setEmail(username + "@keycloak.org"); user.setEmail(username + "@keycloak.org");
UserCredentialModel passwordCred = UserCredentialModel.password(password); UserCredentialModel passwordCred = UserCredentialModel.password(password);
session.userCredentialManager().updateCredential(realm, user, passwordCred); user.getUserCredentialManager().updateCredential(passwordCred);
for (RoleModel role : roles) { for (RoleModel role : roles) {
user.grantRole(role); user.grantRole(role);