Renaming SingleUserCredentialManager and UserModel.getUserCredentialManager():

- class SingleUserCredentialManager to SingleEntityCredentialManager
- method UserModel.getUserCredentialManager() to credentialManager()

Renaming of API without "get" prefix to make it consistent with other APIs like for example with KeycloakSession
This commit is contained in:
Hynek Mlnarik 2022-05-26 22:01:25 +02:00 committed by Hynek Mlnařík
parent 14a369a8cc
commit e396d0daa1
82 changed files with 541 additions and 727 deletions

View file

@ -24,7 +24,6 @@ import org.keycloak.credential.CredentialModel;
import org.keycloak.credential.CredentialProvider;
import org.keycloak.credential.CredentialTypeMetadata;
import org.keycloak.credential.CredentialTypeMetadataContext;
import org.keycloak.credential.UserCredentialStore;
import org.keycloak.examples.authenticator.credential.SecretQuestionCredentialModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
@ -57,7 +56,7 @@ public class SecretQuestionCredentialProvider implements CredentialProvider<Secr
if (challengeResponse == null) {
return false;
}
CredentialModel credentialModel = user.getUserCredentialManager().getStoredCredentialById(input.getCredentialId());
CredentialModel credentialModel = user.credentialManager().getStoredCredentialById(input.getCredentialId());
SecretQuestionCredentialModel sqcm = getCredentialFromModel(credentialModel);
return sqcm.getSecretQuestionSecretData().getAnswer().equals(challengeResponse);
}
@ -70,7 +69,7 @@ public class SecretQuestionCredentialProvider implements CredentialProvider<Secr
@Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
if (!supportsCredentialType(credentialType)) return false;
return user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType).findAny().isPresent();
return user.credentialManager().getStoredCredentialsByTypeStream(credentialType).findAny().isPresent();
}
@Override
@ -78,12 +77,12 @@ public class SecretQuestionCredentialProvider implements CredentialProvider<Secr
if (credentialModel.getCreatedDate() == null) {
credentialModel.setCreatedDate(Time.currentTimeMillis());
}
return user.getUserCredentialManager().createStoredCredential(credentialModel);
return user.credentialManager().createStoredCredential(credentialModel);
}
@Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
return user.credentialManager().removeStoredCredentialById(credentialId);
}
@Override

View file

@ -168,7 +168,7 @@ public class KerberosFederationProvider implements UserStorageProvider,
@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
if (!(input instanceof UserCredentialModel)) return false;
if (input.getType().equals(PasswordCredentialModel.TYPE) && !((LegacySingleUserCredentialManager) user.getUserCredentialManager()).isConfiguredLocally(PasswordCredentialModel.TYPE)) {
if (input.getType().equals(PasswordCredentialModel.TYPE) && !((LegacySingleUserCredentialManager) user.credentialManager()).isConfiguredLocally(PasswordCredentialModel.TYPE)) {
return validPassword(user.getUsername(), input.getChallengeResponse());
} else {
return false; // invalid cred type

View file

@ -713,7 +713,7 @@ public class LDAPStorageProvider implements UserStorageProvider,
@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
if (!(input instanceof UserCredentialModel)) return false;
if (input.getType().equals(PasswordCredentialModel.TYPE) && !((LegacySingleUserCredentialManager) user.getUserCredentialManager()).isConfiguredLocally(PasswordCredentialModel.TYPE)) {
if (input.getType().equals(PasswordCredentialModel.TYPE) && !((LegacySingleUserCredentialManager) user.credentialManager()).isConfiguredLocally(PasswordCredentialModel.TYPE)) {
return validPassword(realm, user, input.getChallengeResponse());
} else {
return false; // invalid cred type

View file

@ -0,0 +1,119 @@
package org.keycloak.models.cache.infinispan;
import org.keycloak.credential.CredentialInput;
import org.keycloak.credential.CredentialModel;
import org.keycloak.models.SingleEntityCredentialManager;
import java.util.List;
import java.util.stream.Stream;
/**
* @author Alexander Schwartz
*/
public abstract class SingleEntityCredentialManagerCacheAdapter implements SingleEntityCredentialManager {
private final SingleEntityCredentialManager singleEntityCredentialManager;
protected SingleEntityCredentialManagerCacheAdapter(SingleEntityCredentialManager singleEntityCredentialManager) {
this.singleEntityCredentialManager = singleEntityCredentialManager;
}
public abstract void invalidateCacheForEntity();
@Override
public boolean isValid(List<CredentialInput> inputs) {
// validating a password might still update its hashes, similar logic might apply to OTP logic
// instead of having each
invalidateCacheForEntity();
return singleEntityCredentialManager.isValid(inputs);
}
@Override
public boolean updateCredential(CredentialInput input) {
invalidateCacheForEntity();
return singleEntityCredentialManager.updateCredential(input);
}
@Override
public void updateStoredCredential(CredentialModel cred) {
invalidateCacheForEntity();
singleEntityCredentialManager.updateStoredCredential(cred);
}
@Override
public CredentialModel createStoredCredential(CredentialModel cred) {
invalidateCacheForEntity();
return singleEntityCredentialManager.createStoredCredential(cred);
}
@Override
public boolean removeStoredCredentialById(String id) {
invalidateCacheForEntity();
return singleEntityCredentialManager.removeStoredCredentialById(id);
}
@Override
public CredentialModel getStoredCredentialById(String id) {
return singleEntityCredentialManager.getStoredCredentialById(id);
}
@Override
public Stream<CredentialModel> getStoredCredentialsStream() {
return singleEntityCredentialManager.getStoredCredentialsStream();
}
@Override
public Stream<CredentialModel> getStoredCredentialsByTypeStream(String type) {
return singleEntityCredentialManager.getStoredCredentialsByTypeStream(type);
}
@Override
public CredentialModel getStoredCredentialByNameAndType(String name, String type) {
return singleEntityCredentialManager.getStoredCredentialByNameAndType(name, type);
}
@Override
public boolean moveStoredCredentialTo(String id, String newPreviousCredentialId) {
invalidateCacheForEntity();
return singleEntityCredentialManager.moveStoredCredentialTo(id, newPreviousCredentialId);
}
@Override
public void updateCredentialLabel(String credentialId, String userLabel) {
invalidateCacheForEntity();
singleEntityCredentialManager.updateCredentialLabel(credentialId, userLabel);
}
@Override
public void disableCredentialType(String credentialType) {
invalidateCacheForEntity();
singleEntityCredentialManager.disableCredentialType(credentialType);
}
@Override
public Stream<String> getDisableableCredentialTypesStream() {
return singleEntityCredentialManager.getDisableableCredentialTypesStream();
}
@Override
public boolean isConfiguredFor(String type) {
return singleEntityCredentialManager.isConfiguredFor(type);
}
@Override
public boolean isConfiguredLocally(String type) {
return singleEntityCredentialManager.isConfiguredLocally(type);
}
@Override
public Stream<String> getConfiguredUserStorageCredentialTypesStream() {
return singleEntityCredentialManager.getConfiguredUserStorageCredentialTypesStream();
}
@Override
public CredentialModel createCredentialThroughProvider(CredentialModel model) {
invalidateCacheForEntity();
return singleEntityCredentialManager.createCredentialThroughProvider(model);
}
}

View file

@ -1,119 +0,0 @@
package org.keycloak.models.cache.infinispan;
import org.keycloak.credential.CredentialInput;
import org.keycloak.credential.CredentialModel;
import org.keycloak.models.SingleUserCredentialManager;
import java.util.List;
import java.util.stream.Stream;
/**
* @author Alexander Schwartz
*/
public abstract class SingleUserCredentialManagerCacheAdapter implements SingleUserCredentialManager {
private final SingleUserCredentialManager singleUserCredentialManager;
protected SingleUserCredentialManagerCacheAdapter(SingleUserCredentialManager singleUserCredentialManager) {
this.singleUserCredentialManager = singleUserCredentialManager;
}
public abstract void invalidateCacheForUser();
@Override
public boolean isValid(List<CredentialInput> inputs) {
// validating a password might still update its hashes, similar logic might apply to OTP logic
// instead of having each
invalidateCacheForUser();
return singleUserCredentialManager.isValid(inputs);
}
@Override
public boolean updateCredential(CredentialInput input) {
invalidateCacheForUser();
return singleUserCredentialManager.updateCredential(input);
}
@Override
public void updateStoredCredential(CredentialModel cred) {
invalidateCacheForUser();
singleUserCredentialManager.updateStoredCredential(cred);
}
@Override
public CredentialModel createStoredCredential(CredentialModel cred) {
invalidateCacheForUser();
return singleUserCredentialManager.createStoredCredential(cred);
}
@Override
public boolean removeStoredCredentialById(String id) {
invalidateCacheForUser();
return singleUserCredentialManager.removeStoredCredentialById(id);
}
@Override
public CredentialModel getStoredCredentialById(String id) {
return singleUserCredentialManager.getStoredCredentialById(id);
}
@Override
public Stream<CredentialModel> getStoredCredentialsStream() {
return singleUserCredentialManager.getStoredCredentialsStream();
}
@Override
public Stream<CredentialModel> getStoredCredentialsByTypeStream(String type) {
return singleUserCredentialManager.getStoredCredentialsByTypeStream(type);
}
@Override
public CredentialModel getStoredCredentialByNameAndType(String name, String type) {
return singleUserCredentialManager.getStoredCredentialByNameAndType(name, type);
}
@Override
public boolean moveStoredCredentialTo(String id, String newPreviousCredentialId) {
invalidateCacheForUser();
return singleUserCredentialManager.moveStoredCredentialTo(id, newPreviousCredentialId);
}
@Override
public void updateCredentialLabel(String credentialId, String userLabel) {
invalidateCacheForUser();
singleUserCredentialManager.updateCredentialLabel(credentialId, userLabel);
}
@Override
public void disableCredentialType(String credentialType) {
invalidateCacheForUser();
singleUserCredentialManager.disableCredentialType(credentialType);
}
@Override
public Stream<String> getDisableableCredentialTypesStream() {
return singleUserCredentialManager.getDisableableCredentialTypesStream();
}
@Override
public boolean isConfiguredFor(String type) {
return singleUserCredentialManager.isConfiguredFor(type);
}
@Override
public boolean isConfiguredLocally(String type) {
return singleUserCredentialManager.isConfiguredLocally(type);
}
@Override
public Stream<String> getConfiguredUserStorageCredentialTypesStream() {
return singleUserCredentialManager.getConfiguredUserStorageCredentialTypesStream();
}
@Override
public CredentialModel createCredentialThroughProvider(CredentialModel model) {
invalidateCacheForUser();
return singleUserCredentialManager.createCredentialThroughProvider(model);
}
}

View file

@ -23,7 +23,7 @@ import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserModel;
import org.keycloak.models.cache.CachedUserModel;
import org.keycloak.models.cache.infinispan.entities.CachedUser;
@ -287,12 +287,12 @@ public class UserAdapter implements CachedUserModel.Streams {
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
if (updated == null) {
updated = modelSupplier.get();
if (updated == null) throw new IllegalStateException("Not found in database");
}
return new SingleUserCredentialManagerCacheAdapter(updated.getUserCredentialManager()) {
return new SingleEntityCredentialManagerCacheAdapter(updated.credentialManager()) {
@Override
public CredentialModel getStoredCredentialById(String id) {
if (!userRegisteredForInvalidation) {
@ -330,7 +330,7 @@ public class UserAdapter implements CachedUserModel.Streams {
}
@Override
public void invalidateCacheForUser() {
public void invalidateCacheForEntity() {
if (!userRegisteredForInvalidation) {
userProviderCache.registerUserInvalidation(realm, cached);
userRegisteredForInvalidation = true;

View file

@ -70,7 +70,7 @@ public class CachedUser extends AbstractExtendableRevisioned implements InRealm
this.attributes = new DefaultLazyLoader<>(userModel -> new MultivaluedHashMap<>(userModel.getAttributes()), MultivaluedHashMap::new);
this.roleMappings = new DefaultLazyLoader<>(userModel -> userModel.getRoleMappingsStream().map(RoleModel::getId).collect(Collectors.toSet()), Collections::emptySet);
this.groups = new DefaultLazyLoader<>(userModel -> userModel.getGroupsStream().map(GroupModel::getId).collect(Collectors.toCollection(LinkedHashSet::new)), LinkedHashSet::new);
this.storedCredentials = new DefaultLazyLoader<>(userModel -> userModel.getUserCredentialManager().getStoredCredentialsStream().collect(Collectors.toCollection(LinkedList::new)), LinkedList::new);
this.storedCredentials = new DefaultLazyLoader<>(userModel -> userModel.credentialManager().getStoredCredentialsStream().collect(Collectors.toCollection(LinkedList::new)), LinkedList::new);
}
public String getRealm() {

View file

@ -25,7 +25,7 @@ import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserModel;
import org.keycloak.models.jpa.entities.UserAttributeEntity;
import org.keycloak.models.jpa.entities.UserEntity;
@ -518,7 +518,7 @@ public class UserAdapter implements UserModel.Streams, JpaModel<UserEntity> {
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
return new LegacySingleUserCredentialManager(session, realm, this);
}

View file

@ -24,7 +24,7 @@ import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserModelDefaultMethods;
import org.keycloak.models.utils.KeycloakModelUtils;
@ -257,7 +257,7 @@ public class InMemoryUserAdapter extends UserModelDefaultMethods.Streams {
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
return new LegacySingleUserCredentialManager(session, realm, this);
}

View file

@ -46,87 +46,87 @@ public class UserCredentialStoreManager implements UserCredentialManager.Streams
}
@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.userCredentialManager() instead
public void updateCredential(RealmModel realm, UserModel user, CredentialModel cred) {
warnAboutUsage();
user.getUserCredentialManager().updateStoredCredential(cred);
user.credentialManager().updateStoredCredential(cred);
}
@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.userCredentialManager() instead
public CredentialModel createCredential(RealmModel realm, UserModel user, CredentialModel cred) {
warnAboutUsage();
return user.getUserCredentialManager().createStoredCredential(cred);
return user.credentialManager().createStoredCredential(cred);
}
@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.userCredentialManager() instead
public boolean removeStoredCredential(RealmModel realm, UserModel user, String id) {
warnAboutUsage();
return user.getUserCredentialManager().removeStoredCredentialById(id);
return user.credentialManager().removeStoredCredentialById(id);
}
@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.userCredentialManager() instead
public CredentialModel getStoredCredentialById(RealmModel realm, UserModel user, String id) {
warnAboutUsage();
return user.getUserCredentialManager().getStoredCredentialById(id);
return user.credentialManager().getStoredCredentialById(id);
}
@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.userCredentialManager() instead
public Stream<CredentialModel> getStoredCredentialsStream(RealmModel realm, UserModel user) {
warnAboutUsage();
return user.getUserCredentialManager().getStoredCredentialsStream();
return user.credentialManager().getStoredCredentialsStream();
}
@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.userCredentialManager() instead
public Stream<CredentialModel> getStoredCredentialsByTypeStream(RealmModel realm, UserModel user, String type) {
warnAboutUsage();
return user.getUserCredentialManager().getStoredCredentialsByTypeStream(type);
return user.credentialManager().getStoredCredentialsByTypeStream(type);
}
@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.userCredentialManager() instead
public CredentialModel getStoredCredentialByNameAndType(RealmModel realm, UserModel user, String name, String type) {
warnAboutUsage();
return user.getUserCredentialManager().getStoredCredentialByNameAndType(name, type);
return user.credentialManager().getStoredCredentialByNameAndType(name, type);
}
@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.userCredentialManager() instead
public boolean moveCredentialTo(RealmModel realm, UserModel user, String id, String newPreviousCredentialId){
warnAboutUsage();
return user.getUserCredentialManager().moveStoredCredentialTo(id, newPreviousCredentialId);
return user.credentialManager().moveStoredCredentialTo(id, newPreviousCredentialId);
}
@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.userCredentialManager() instead
public boolean isValid(RealmModel realm, UserModel user, CredentialInput... inputs) {
warnAboutUsage();
return isValid(realm, user, Arrays.asList(inputs));
}
@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.userCredentialManager() instead
public CredentialModel createCredentialThroughProvider(RealmModel realm, UserModel user, CredentialModel model){
warnAboutUsage();
return user.getUserCredentialManager().createCredentialThroughProvider(model);
return user.credentialManager().createCredentialThroughProvider(model);
}
@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.userCredentialManager() instead
public void updateCredentialLabel(RealmModel realm, UserModel user, String credentialId, String userLabel){
warnAboutUsage();
user.getUserCredentialManager().updateCredentialLabel(credentialId, userLabel);
user.credentialManager().updateCredentialLabel(credentialId, userLabel);
}
@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.userCredentialManager() instead
public boolean isValid(RealmModel realm, UserModel user, List<CredentialInput> inputs) {
warnAboutUsage();
return user.getUserCredentialManager().isValid(inputs);
return user.credentialManager().isValid(inputs);
}
@Deprecated // Keep this up to and including Keycloak 19, then inline
@ -139,42 +139,42 @@ public class UserCredentialStoreManager implements UserCredentialManager.Streams
}
@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.userCredentialManager() instead
public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) {
warnAboutUsage();
return user.getUserCredentialManager().updateCredential(input);
return user.credentialManager().updateCredential(input);
}
@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.userCredentialManager() instead
public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) {
warnAboutUsage();
user.getUserCredentialManager().disableCredentialType(credentialType);
user.credentialManager().disableCredentialType(credentialType);
}
@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.userCredentialManager() instead
public Stream<String> getDisableableCredentialTypesStream(RealmModel realm, UserModel user) {
warnAboutUsage();
return user.getUserCredentialManager().getDisableableCredentialTypesStream();
return user.credentialManager().getDisableableCredentialTypesStream();
}
@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.userCredentialManager() instead
public boolean isConfiguredFor(RealmModel realm, UserModel user, String type) {
warnAboutUsage();
return user.getUserCredentialManager().isConfiguredFor(type);
return user.credentialManager().isConfiguredFor(type);
}
@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.userCredentialManager() instead
public boolean isConfiguredLocally(RealmModel realm, UserModel user, String type) {
warnAboutUsage();
return user.getUserCredentialManager().isConfiguredLocally(type);
return user.credentialManager().isConfiguredLocally(type);
}
@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.userCredentialManager() instead
public CredentialValidationOutput authenticate(KeycloakSession session, RealmModel realm, CredentialInput input) {
warnAboutUsage();
return session.users().getUserByCredential(realm, input);
@ -189,10 +189,10 @@ public class UserCredentialStoreManager implements UserCredentialManager.Streams
}
@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.userCredentialManager() instead
public Stream<String> getConfiguredUserStorageCredentialTypesStream(RealmModel realm, UserModel user) {
warnAboutUsage();
return user.getUserCredentialManager().getConfiguredUserStorageCredentialTypesStream();
return user.credentialManager().getConfiguredUserStorageCredentialTypesStream();
}
@Override
@ -203,7 +203,7 @@ public class UserCredentialStoreManager implements UserCredentialManager.Streams
private static void warnAboutUsage() {
if (log.isEnabled(Logger.Level.WARN)) {
// check if warning is enabled first before constructing the exception that is expensive to construct
log.warn("Calls to session.userCredentialManager() now deprecated. Use user.getUserCredentialManager() instead!", new RuntimeException());
log.warn("Calls to session.userCredentialManager() now deprecated. Use user.userCredentialManager() instead!", new RuntimeException());
}
}

View file

@ -20,9 +20,11 @@ package org.keycloak.credential;
import org.keycloak.common.util.reflections.Types;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserModel;
import org.keycloak.storage.AbstractStorageManager;
import org.keycloak.storage.DatastoreProvider;
import org.keycloak.storage.LegacyStoreManagers;
import org.keycloak.storage.StorageId;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.storage.UserStorageProviderFactory;
@ -40,19 +42,17 @@ import java.util.stream.Stream;
*
* @author Alexander Schwartz
*/
public class LegacySingleUserCredentialManager extends AbstractStorageManager<UserStorageProvider, UserStorageProviderModel> implements SingleUserCredentialManager {
public class LegacySingleUserCredentialManager extends AbstractStorageManager<UserStorageProvider, UserStorageProviderModel> implements SingleEntityCredentialManager {
private final UserModel user;
private final KeycloakSession session;
private final RealmModel realm;
private final LegacySingleUserCredentialManagerStrategy strategy;
public LegacySingleUserCredentialManager(KeycloakSession session, RealmModel realm, UserModel user) {
super(session, UserStorageProviderFactory.class, UserStorageProvider.class, UserStorageProviderModel::new, "user");
this.user = user;
this.session = session;
this.realm = realm;
this.strategy = new LegacySingleUserCredentialManagerStrategy(session, realm, user);
}
@Override
@ -74,8 +74,6 @@ public class LegacySingleUserCredentialManager extends AbstractStorageManager<Us
}
}
strategy.validateCredentials(toValidate);
getCredentialProviders(session, CredentialInputValidator.class)
.forEach(validator -> validate(realm, user, toValidate, validator));
@ -97,8 +95,7 @@ public class LegacySingleUserCredentialManager extends AbstractStorageManager<Us
}
}
return strategy.updateCredential(input) ||
getCredentialProviders(session, CredentialInputUpdater.class)
return getCredentialProviders(session, CredentialInputUpdater.class)
.filter(updater -> updater.supportsCredentialType(input.getType()))
.anyMatch(updater -> updater.updateCredential(realm, user, input));
}
@ -106,45 +103,45 @@ public class LegacySingleUserCredentialManager extends AbstractStorageManager<Us
@Override
public void updateStoredCredential(CredentialModel cred) {
throwExceptionIfInvalidUser(user);
strategy.updateStoredCredential(cred);
getStoreForUser(user).updateCredential(realm, user, cred);
}
@Override
public CredentialModel createStoredCredential(CredentialModel cred) {
throwExceptionIfInvalidUser(user);
return strategy.createStoredCredential(cred);
return getStoreForUser(user).createCredential(realm, user, cred);
}
@Override
public boolean removeStoredCredentialById(String id) {
throwExceptionIfInvalidUser(user);
return strategy.removeStoredCredentialById(id);
return getStoreForUser(user).removeStoredCredential(realm, user, id);
}
@Override
public CredentialModel getStoredCredentialById(String id) {
return strategy.getStoredCredentialById(id);
return getStoreForUser(user).getStoredCredentialById(realm, user, id);
}
@Override
public Stream<CredentialModel> getStoredCredentialsStream() {
return strategy.getStoredCredentialsStream();
return getStoreForUser(user).getStoredCredentialsStream(realm, user);
}
@Override
public Stream<CredentialModel> getStoredCredentialsByTypeStream(String type) {
return strategy.getStoredCredentialsByTypeStream(type);
return getStoreForUser(user).getStoredCredentialsByTypeStream(realm, user, type);
}
@Override
public CredentialModel getStoredCredentialByNameAndType(String name, String type) {
return strategy.getStoredCredentialByNameAndType(name, type);
return getStoreForUser(user).getStoredCredentialByNameAndType(realm, user, name, type);
}
@Override
public boolean moveStoredCredentialTo(String id, String newPreviousCredentialId) {
throwExceptionIfInvalidUser(user);
return strategy.moveStoredCredentialTo(id, newPreviousCredentialId);
return getStoreForUser(user).moveCredentialTo(realm, user, id, newPreviousCredentialId);
}
@Override
@ -273,5 +270,14 @@ public class LegacySingleUserCredentialManager extends AbstractStorageManager<Us
}
}
private UserCredentialStore getStoreForUser(UserModel user) {
LegacyStoreManagers p = (LegacyStoreManagers) session.getProvider(DatastoreProvider.class);
if (StorageId.isLocalStorage(user.getId())) {
return (UserCredentialStore) p.userLocalStorage();
} else {
return (UserCredentialStore) p.userFederatedStorage();
}
}
}

View file

@ -1,108 +0,0 @@
/*
* Copyright 2022. Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.credential;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.storage.AbstractStorageManager;
import org.keycloak.storage.DatastoreProvider;
import org.keycloak.storage.LegacyStoreManagers;
import org.keycloak.storage.StorageId;
import org.keycloak.storage.UserStorageProvider;
import org.keycloak.storage.UserStorageProviderFactory;
import org.keycloak.storage.UserStorageProviderModel;
import java.util.List;
import java.util.stream.Stream;
/**
* Strategy for {@link LegacySingleUserCredentialManager} to handle classic local storage including federation.
*
* @author Alexander Schwartz
*/
public class LegacySingleUserCredentialManagerStrategy extends AbstractStorageManager<UserStorageProvider, UserStorageProviderModel> implements SingleUserCredentialManagerStrategy {
private final UserModel user;
private final RealmModel realm;
public LegacySingleUserCredentialManagerStrategy(KeycloakSession session, RealmModel realm, UserModel user) {
super(session, UserStorageProviderFactory.class, UserStorageProvider.class, UserStorageProviderModel::new, "user");
this.user = user;
this.realm = realm;
}
@Override
public void validateCredentials(List<CredentialInput> toValidate) {
}
@Override
public boolean updateCredential(CredentialInput input) {
return false;
}
@Override
public void updateStoredCredential(CredentialModel cred) {
getStoreForUser(user).updateCredential(realm, user, cred);
}
@Override
public CredentialModel createStoredCredential(CredentialModel cred) {
return getStoreForUser(user).createCredential(realm, user, cred);
}
@Override
public Boolean removeStoredCredentialById(String id) {
return getStoreForUser(user).removeStoredCredential(realm, user, id);
}
@Override
public CredentialModel getStoredCredentialById(String id) {
return getStoreForUser(user).getStoredCredentialById(realm, user, id);
}
@Override
public Stream<CredentialModel> getStoredCredentialsStream() {
return getStoreForUser(user).getStoredCredentialsStream(realm, user);
}
@Override
public Stream<CredentialModel> getStoredCredentialsByTypeStream(String type) {
return getStoreForUser(user).getStoredCredentialsByTypeStream(realm, user, type);
}
@Override
public CredentialModel getStoredCredentialByNameAndType(String name, String type) {
return getStoreForUser(user).getStoredCredentialByNameAndType(realm, user, name, type);
}
@Override
public boolean moveStoredCredentialTo(String id, String newPreviousCredentialId) {
return getStoreForUser(user).moveCredentialTo(realm, user, id, newPreviousCredentialId);
}
private UserCredentialStore getStoreForUser(UserModel user) {
LegacyStoreManagers p = (LegacyStoreManagers) session.getProvider(DatastoreProvider.class);
if (StorageId.isLocalStorage(user.getId())) {
return (UserCredentialStore) p.userLocalStorage();
} else {
return (UserCredentialStore) p.userFederatedStorage();
}
}
}

View file

@ -20,14 +20,15 @@ package org.keycloak.models.map.credential;
import org.keycloak.credential.CredentialInput;
import java.util.List;
import java.util.stream.Stream;
/**
* Standard implementation for a {@link MapSingleUserCredentialManagerEntity} where the store doesn't provide
* Standard implementation for a {@link MapSingleEntityCredentialManagerEntity} where the store doesn't provide
* validation of credentials.
*
* @author Alexander Schwartz
*/
public class DefaultMapSingleUserCredentialManagerEntity implements MapSingleUserCredentialManagerEntity {
public class DefaultMapSingleEntityCredentialManagerEntity implements MapSingleEntityCredentialManagerEntity {
@Override
public void validateCredentials(List<CredentialInput> inputs) {
}
@ -36,4 +37,14 @@ public class DefaultMapSingleUserCredentialManagerEntity implements MapSingleUse
public boolean updateCredential(CredentialInput input) {
return false;
}
@Override
public boolean isConfiguredFor(String type) {
return false;
}
@Override
public Stream<String> getDisableableCredentialTypesStream() {
return Stream.empty();
}
}

View file

@ -20,13 +20,14 @@ package org.keycloak.models.map.credential;
import org.keycloak.credential.CredentialInput;
import java.util.List;
import java.util.stream.Stream;
/**
* Interface for credential management in entities in the map storage.
*
* @author Alexander Schwartz
*/
public interface MapSingleUserCredentialManagerEntity {
public interface MapSingleEntityCredentialManagerEntity {
/**
* Validate the credentials of a user.
@ -44,4 +45,16 @@ public interface MapSingleUserCredentialManagerEntity {
* credential type isn't supported of the new credentials aren't valid.
*/
boolean updateCredential(CredentialInput input);
/**
* Check if the entity is configured for the given credential type.
* @param type credential type
*/
boolean isConfiguredFor(String type);
/**
* List the credential types that can be disabled for this user.
* @return Stream of credential types
*/
Stream<String> getDisableableCredentialTypesStream();
}

View file

@ -24,39 +24,41 @@ import org.keycloak.credential.CredentialInputValidator;
import org.keycloak.credential.CredentialModel;
import org.keycloak.credential.CredentialProvider;
import org.keycloak.credential.CredentialProviderFactory;
import org.keycloak.credential.SingleUserCredentialManagerStrategy;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserModel;
import org.keycloak.models.map.user.MapUserCredentialEntity;
import org.keycloak.models.map.user.MapUserEntity;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Handling credentials for a given user.
*
* 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
* {@link MapSingleUserCredentialManagerStrategy}.
* and {@link CredentialInputValidator}s.
*
* @author Alexander Schwartz
*/
public class MapSingleUserCredentialManager implements SingleUserCredentialManager {
public class MapSingleUserCredentialManager implements SingleEntityCredentialManager {
private final UserModel user;
private final KeycloakSession session;
private final RealmModel realm;
private final SingleUserCredentialManagerStrategy strategy;
private final MapUserEntity entity;
public MapSingleUserCredentialManager(KeycloakSession session, RealmModel realm, UserModel user, MapUserEntity entity) {
this.user = user;
this.session = session;
this.realm = realm;
this.strategy = new MapSingleUserCredentialManagerStrategy(entity);
this.entity = entity;
}
@Override
@ -67,7 +69,7 @@ public class MapSingleUserCredentialManager implements SingleUserCredentialManag
List<CredentialInput> toValidate = new LinkedList<>(inputs);
strategy.validateCredentials(toValidate);
entity.credentialManager().validateCredentials(toValidate);
getCredentialProviders(session, CredentialInputValidator.class)
.forEach(validator -> validate(realm, user, toValidate, validator));
@ -77,7 +79,7 @@ public class MapSingleUserCredentialManager implements SingleUserCredentialManag
@Override
public boolean updateCredential(CredentialInput input) {
return strategy.updateCredential(input) ||
return entity.credentialManager().updateCredential(input) ||
getCredentialProviders(session, CredentialInputUpdater.class)
.filter(updater -> updater.supportsCredentialType(input.getType()))
.anyMatch(updater -> updater.updateCredential(realm, user, input));
@ -86,45 +88,63 @@ public class MapSingleUserCredentialManager implements SingleUserCredentialManag
@Override
public void updateStoredCredential(CredentialModel cred) {
throwExceptionIfInvalidUser(user);
strategy.updateStoredCredential(cred);
entity.getCredential(cred.getId()).ifPresent(c -> {
c.setCreatedDate(cred.getCreatedDate());
c.setUserLabel(cred.getUserLabel());
c.setType(cred.getType());
c.setSecretData(cred.getSecretData());
c.setCredentialData(cred.getCredentialData());
});
}
@Override
public CredentialModel createStoredCredential(CredentialModel cred) {
throwExceptionIfInvalidUser(user);
return strategy.createStoredCredential(cred);
MapUserCredentialEntity credentialEntity = MapUserCredentialEntity.fromModel(cred);
if (entity.getCredential(cred.getId()).isPresent()) {
throw new ModelDuplicateException("A CredentialModel with given id already exists");
}
entity.addCredential(credentialEntity);
return MapUserCredentialEntity.toModel(credentialEntity);
}
@Override
public boolean removeStoredCredentialById(String id) {
throwExceptionIfInvalidUser(user);
return strategy.removeStoredCredentialById(id);
return entity.removeCredential(id);
}
@Override
public CredentialModel getStoredCredentialById(String id) {
return strategy.getStoredCredentialById(id);
return entity.getCredential(id).map(MapUserCredentialEntity::toModel).orElse(null);
}
@Override
public Stream<CredentialModel> getStoredCredentialsStream() {
return strategy.getStoredCredentialsStream();
return Optional.ofNullable(entity.getCredentials()).orElse(Collections.emptyList()).stream()
.map(MapUserCredentialEntity::toModel);
}
@Override
public Stream<CredentialModel> getStoredCredentialsByTypeStream(String type) {
return strategy.getStoredCredentialsByTypeStream(type);
return getStoredCredentialsStream()
.filter(credential -> Objects.equals(type, credential.getType()));
}
@Override
public CredentialModel getStoredCredentialByNameAndType(String name, String type) {
return strategy.getStoredCredentialByNameAndType(name, type);
return getStoredCredentialsStream()
.filter(credential -> Objects.equals(name, credential.getUserLabel()))
.findFirst().orElse(null);
}
@Override
public boolean moveStoredCredentialTo(String id, String newPreviousCredentialId) {
throwExceptionIfInvalidUser(user);
return strategy.moveStoredCredentialTo(id, newPreviousCredentialId);
return entity.moveCredential(id, newPreviousCredentialId);
}
@Override
@ -144,32 +164,37 @@ public class MapSingleUserCredentialManager implements SingleUserCredentialManag
@Override
public Stream<String> getDisableableCredentialTypesStream() {
// TODO: ask the store
return getCredentialProviders(session, CredentialInputUpdater.class)
.flatMap(updater -> updater.getDisableableCredentialTypesStream(realm, user));
return Stream.concat(entity.credentialManager().getDisableableCredentialTypesStream(),
getCredentialProviders(session, CredentialInputUpdater.class)
.flatMap(updater -> updater.getDisableableCredentialTypesStream(realm, user)))
.distinct();
}
@Override
public boolean isConfiguredFor(String type) {
// TODO: ask the store
return isConfiguredLocally(type);
}
@Override
public boolean isConfiguredLocally(String type) {
return getCredentialProviders(session, CredentialInputValidator.class)
return entity.credentialManager().isConfiguredFor(type) ||
getCredentialProviders(session, CredentialInputValidator.class)
.anyMatch(validator -> validator.supportsCredentialType(type) && validator.isConfiguredFor(realm, user, type));
}
@Override
public Stream<String> getConfiguredUserStorageCredentialTypesStream() {
// TODO ask the store
return getCredentialProviders(session, CredentialProvider.class).map(CredentialProvider::getType)
.filter(credentialType -> UserStorageCredentialConfigured.CONFIGURED == isConfiguredThroughUserStorage(realm, user, credentialType));
@Deprecated
public boolean isConfiguredLocally(String type) {
throw new IllegalArgumentException("this is not supported for map storage");
}
@Override
@Deprecated
public Stream<String> getConfiguredUserStorageCredentialTypesStream() {
// used in the old admin console for users to determine if a password is set for a user
// not used in the new admin console
return Stream.empty();
}
@Override
@Deprecated
public CredentialModel createCredentialThroughProvider(CredentialModel model) {
// this is still called when importing/creating a user via RepresentationToModel.createCredentials
throwExceptionIfInvalidUser(user);
return session.getKeycloakSessionFactory()
.getProviderFactoriesStream(CredentialProvider.class)
@ -180,16 +205,6 @@ public class MapSingleUserCredentialManager implements SingleUserCredentialManag
.orElse(null);
}
private enum UserStorageCredentialConfigured {
CONFIGURED,
USER_STORAGE_DISABLED,
NOT_CONFIGURED
}
private UserStorageCredentialConfigured isConfiguredThroughUserStorage(RealmModel realm, UserModel user, String type) {
return UserStorageCredentialConfigured.NOT_CONFIGURED;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isValid(UserModel user) {
Objects.requireNonNull(user);

View file

@ -1,113 +0,0 @@
/*
* Copyright 2022. Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.models.map.credential;
import org.keycloak.credential.CredentialInput;
import org.keycloak.credential.CredentialModel;
import org.keycloak.credential.SingleUserCredentialManagerStrategy;
import org.keycloak.models.ModelDuplicateException;
import org.keycloak.models.map.user.MapUserCredentialEntity;
import org.keycloak.models.map.user.MapUserEntity;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Implementation of {@link SingleUserCredentialManagerStrategy} for map storages.
* Will delegate calls to the credential manager in the entity.
*
* @author Alexander Schwartz
*/
public class MapSingleUserCredentialManagerStrategy implements SingleUserCredentialManagerStrategy {
private final MapUserEntity entity;
public MapSingleUserCredentialManagerStrategy(MapUserEntity entity) {
this.entity = entity;
}
@Override
public void validateCredentials(List<CredentialInput> toValidate) {
entity.getUserCredentialManager().validateCredentials(toValidate);
}
@Override
public boolean updateCredential(CredentialInput input) {
return entity.getUserCredentialManager().updateCredential(input);
}
@Override
public void updateStoredCredential(CredentialModel credentialModel) {
entity.getCredential(credentialModel.getId()).ifPresent(c -> {
c.setCreatedDate(credentialModel.getCreatedDate());
c.setUserLabel(credentialModel.getUserLabel());
c.setType(credentialModel.getType());
c.setSecretData(credentialModel.getSecretData());
c.setCredentialData(credentialModel.getCredentialData());
});
}
@Override
public CredentialModel createStoredCredential(CredentialModel cred) {
MapUserCredentialEntity credentialEntity = MapUserCredentialEntity.fromModel(cred);
if (entity.getCredential(cred.getId()).isPresent()) {
throw new ModelDuplicateException("A CredentialModel with given id already exists");
}
entity.addCredential(credentialEntity);
return MapUserCredentialEntity.toModel(credentialEntity);
}
@Override
public Boolean removeStoredCredentialById(String id) {
return entity.removeCredential(id);
}
@Override
public CredentialModel getStoredCredentialById(String id) {
return entity.getCredential(id).map(MapUserCredentialEntity::toModel).orElse(null);
}
@Override
public Stream<CredentialModel> getStoredCredentialsStream() {
return Optional.ofNullable(entity.getCredentials()).orElse(Collections.emptyList()).stream()
.map(MapUserCredentialEntity::toModel);
}
@Override
public Stream<CredentialModel> getStoredCredentialsByTypeStream(String type) {
return getStoredCredentialsStream()
.filter(credential -> Objects.equals(type, credential.getType()));
}
@Override
public CredentialModel getStoredCredentialByNameAndType(String name, String type) {
return getStoredCredentialsStream()
.filter(credential -> Objects.equals(name, credential.getUserLabel()))
.findFirst().orElse(null);
}
@Override
public boolean moveStoredCredentialTo(String id, String newPreviousCredentialId) {
return entity.moveCredential(id, newPreviousCredentialId);
}
}

View file

@ -24,8 +24,8 @@ import org.keycloak.models.map.common.AbstractEntity;
import org.keycloak.models.map.common.DeepCloner;
import org.keycloak.models.map.common.EntityWithAttributes;
import org.keycloak.models.map.common.UpdatableEntity;
import org.keycloak.models.map.credential.DefaultMapSingleUserCredentialManagerEntity;
import org.keycloak.models.map.credential.MapSingleUserCredentialManagerEntity;
import org.keycloak.models.map.credential.DefaultMapSingleEntityCredentialManagerEntity;
import org.keycloak.models.map.credential.MapSingleEntityCredentialManagerEntity;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.Collections;
@ -248,8 +248,7 @@ public interface MapUserEntity extends UpdatableEntity, AbstractEntity, EntityWi
Long getNotBefore();
void setNotBefore(Long notBefore);
@IgnoreForEntityImplementationGenerator
default MapSingleUserCredentialManagerEntity getUserCredentialManager() {
return new DefaultMapSingleUserCredentialManagerEntity();
default MapSingleEntityCredentialManagerEntity credentialManager() {
return new DefaultMapSingleEntityCredentialManagerEntity();
}
}

View file

@ -41,7 +41,7 @@ import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RequiredActionProviderModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserConsentModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserModel.SearchableFields;
@ -110,7 +110,7 @@ public class MapUserProvider implements UserProvider.Streams {
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
return new MapSingleUserCredentialManager(session, realm, this, entity);
}
};

View file

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

View file

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

View file

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

View file

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

View file

@ -100,7 +100,7 @@ public class CredentialHelper {
String totpSecret = credentialModel.getOTPSecretData().getValue();
UserCredentialModel otpUserCredential = new UserCredentialModel("", realm.getOTPPolicy().getType(), totpSecret);
boolean userStorageCreated = user.getUserCredentialManager().updateCredential(otpUserCredential);
boolean userStorageCreated = user.credentialManager().updateCredential(otpUserCredential);
String credentialId = null;
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.
UserCredentialModel credential = new UserCredentialModel(credentialId, otpCredentialProvider.getType(), totpCode);
return user.getUserCredentialManager().isValid(credential);
return user.credentialManager().isValid(credential);
}
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
if (!removed) {
logger.debug("Removing OTP credential from userStorage");
user.getUserCredentialManager().disableCredentialType(OTPCredentialModel.TYPE);
user.credentialManager().disableCredentialType(OTPCredentialModel.TYPE);
}
}

View file

@ -21,8 +21,6 @@ import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.provider.Provider;
import java.io.IOException;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
@ -43,7 +41,7 @@ public interface CredentialProvider<T extends CredentialModel> extends Provider
T getCredentialFromModel(CredentialModel model);
default T getDefaultCredential(KeycloakSession session, RealmModel realm, UserModel user) {
CredentialModel model = user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType())
CredentialModel model = user.credentialManager().getStoredCredentialsByTypeStream(getType())
.findFirst().orElse(null);
return model != null ? getCredentialFromModel(model) : null;
}

View file

@ -1,55 +0,0 @@
/*
* Copyright 2022. Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.credential;
import java.util.List;
import java.util.stream.Stream;
/**
* Use this to implement extendable strategies for the {@link org.keycloak.models.SingleUserCredentialManager}.
*/
public interface SingleUserCredentialManagerStrategy {
/**
* Validate the credentials passed as a list. The implementation should remove all credentials that validate
* successfully from the list. An empty list signals to the caller that authentication has completed successfully.
*/
void validateCredentials(List<CredentialInput> toValidate);
/**
* Update the credential.
* @return true is the credential was update, false otherwise
*/
boolean updateCredential(CredentialInput input);
void updateStoredCredential(CredentialModel cred);
CredentialModel createStoredCredential(CredentialModel cred) ;
Boolean removeStoredCredentialById(String id);
CredentialModel getStoredCredentialById(String id);
Stream<CredentialModel> getStoredCredentialsStream();
Stream<CredentialModel> getStoredCredentialsByTypeStream(String type);
CredentialModel getStoredCredentialByNameAndType(String name, String type);
boolean moveStoredCredentialTo(String id, String newPreviousCredentialId);
}

View file

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

View file

@ -24,44 +24,95 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public interface SingleUserCredentialManager {
/**
* Validates and manages the credentials of a known entity (for example, a user).
*/
public interface SingleEntityCredentialManager {
/**
* Validates list of credentials.
* Validate a list of credentials.
*
* @return <code>true</code> if inputs are valid
*/
boolean isValid(List<CredentialInput> inputs);
/**
* Validate a list of credentials.
*
* @return <code>true</code> if inputs are valid
*/
default boolean isValid(CredentialInput... inputs) {
return isValid(Arrays.asList(inputs));
}
/**
* Updates a credentials of the user.
* Updates a credential of the entity with the inputs provided by the entity.
* @return <code>true</code> if credentials have been updated successfully
*/
boolean updateCredential(CredentialInput input);
/**
* Updates a credential of the entity with an updated {@link CredentialModel}.
* Usually called by a {@link org.keycloak.credential.CredentialProvider}.
*/
void updateStoredCredential(CredentialModel cred);
/**
* Updates a credential of the entity with an updated {@link CredentialModel}.
* Usually called by a {@link org.keycloak.credential.CredentialProvider}.
*/
CredentialModel createStoredCredential(CredentialModel cred);
/**
* Updates a credential of the entity with an updated {@link CredentialModel}.
* Usually called by a {@link org.keycloak.credential.CredentialProvider}, or from the account management
* when a user removes, for example, an OTP token.
*/
boolean removeStoredCredentialById(String id);
/**
* Read a stored credential.
*/
CredentialModel getStoredCredentialById(String id);
/**
* Read stored credentials as a stream.
*/
Stream<CredentialModel> getStoredCredentialsStream();
/**
* Read stored credentials by type as a stream.
*/
Stream<CredentialModel> getStoredCredentialsByTypeStream(String type);
CredentialModel getStoredCredentialByNameAndType(String name, String type);
/**
* Re-order the stored credentials.
*/
boolean moveStoredCredentialTo(String id, String newPreviousCredentialId);
void updateCredentialLabel(String credentialId, String userLabel);
/**
* Update the label for a stored credentials chosen by the owner of the entity.
*/
void updateCredentialLabel(String credentialId, String credentialLabel);
/**
* Disable a credential by type.
*/
void disableCredentialType(String credentialType);
/**
* List the credentials that can be disabled, for example, to show the list to the entity (aka user) or an admin.
* @return stream with credential types that can be disabled
*/
Stream<String> getDisableableCredentialTypesStream();
/**
* Check if the credential type is configured for this entity.
* @param type credential type to check
* @return <code>true</code> if the credential type has been
*/
boolean isConfiguredFor(String type);
// TODO: not needed for new store? -> no, will be removed without replacement
@ -69,8 +120,10 @@ public interface SingleUserCredentialManager {
boolean isConfiguredLocally(String type);
// TODO: not needed for new store? -> no, will be removed without replacement
@Deprecated
Stream<String> getConfiguredUserStorageCredentialTypesStream();
// TODO: not needed for new store? -> no, will be removed without replacement
@Deprecated
CredentialModel createCredentialThroughProvider(CredentialModel model);
}

View file

@ -28,7 +28,7 @@ import java.util.stream.Stream;
/**
* Manage the credentials for a user.
*
* @deprecated Instead of this class, use {@link UserModel#getUserCredentialManager()} instead.
* @deprecated Instead of this class, use {@link UserModel#credentialManager()} instead.
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
@ -101,7 +101,7 @@ public interface UserCredentialManager extends UserCredentialStore {
* @param realm
* @param user
* @return
* @deprecated Use {@link UserModel#getUserCredentialManager()} and {@link SingleUserCredentialManager#getDisableableCredentialTypesStream()} instead.
* @deprecated Use {@link UserModel#credentialManager()} and {@link SingleEntityCredentialManager#getDisableableCredentialTypesStream()} instead.
*/
@Deprecated
Set<String> getDisableableCredentialTypes(RealmModel realm, UserModel user);
@ -115,7 +115,7 @@ public interface UserCredentialManager extends UserCredentialStore {
* @return a non-null {@link Stream} of credential types.
*/
default Stream<String> getDisableableCredentialTypesStream(RealmModel realm, UserModel user) {
return user.getUserCredentialManager().getDisableableCredentialTypesStream();
return user.credentialManager().getDisableableCredentialTypesStream();
}
/**
@ -158,7 +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.
* This will always return empty list for "local" users, which are not backed by any user storage
*
* @deprecated Use {@link UserModel#getUserCredentialManager()} and then call {@link SingleUserCredentialManager#getConfiguredUserStorageCredentialTypesStream()}
* @deprecated Use {@link UserModel#credentialManager()} and then call {@link SingleEntityCredentialManager#getConfiguredUserStorageCredentialTypesStream()}
* instead.
*/
@Deprecated
@ -175,7 +175,7 @@ public interface UserCredentialManager extends UserCredentialStore {
* @return a non-null {@link Stream} of credential types.
*/
default Stream<String> getConfiguredUserStorageCredentialTypesStream(RealmModel realm, UserModel user) {
return user.getUserCredentialManager().getConfiguredUserStorageCredentialTypesStream();
return user.credentialManager().getConfiguredUserStorageCredentialTypesStream();
}
/**
@ -188,7 +188,7 @@ public interface UserCredentialManager extends UserCredentialStore {
interface Streams extends UserCredentialManager, UserCredentialStore.Streams {
@Override
default Set<String> getDisableableCredentialTypes(RealmModel realm, UserModel user) {
return user.getUserCredentialManager().getDisableableCredentialTypesStream().collect(Collectors.toSet());
return user.credentialManager().getDisableableCredentialTypesStream().collect(Collectors.toSet());
}
@Override
@ -196,7 +196,7 @@ public interface UserCredentialManager extends UserCredentialStore {
@Override
default List<String> getConfiguredUserStorageCredentialTypes(RealmModel realm, UserModel user) {
return user.getUserCredentialManager().getConfiguredUserStorageCredentialTypesStream().collect(Collectors.toList());
return user.credentialManager().getConfiguredUserStorageCredentialTypesStream().collect(Collectors.toList());
}
@Override

View file

@ -298,7 +298,10 @@ public interface UserModel extends RoleMapperModel {
String getServiceAccountClientLink();
void setServiceAccountClientLink(String clientInternalId);
SingleUserCredentialManager getUserCredentialManager();
/**
* Instance of a user credential manager to validate and update the credentials of this user.
*/
SingleEntityCredentialManager credentialManager();
enum RequiredAction {
VERIFY_EMAIL,

View file

@ -20,7 +20,7 @@ package org.keycloak.models.utils;
import org.keycloak.models.ClientModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserModel;
import java.util.List;
@ -211,8 +211,8 @@ public class UserModelDelegate implements UserModel.Streams {
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
return delegate.getUserCredentialManager();
public SingleEntityCredentialManager credentialManager() {
return delegate.credentialManager();
}
public UserModel getDelegate() {

View file

@ -80,9 +80,9 @@ class AuthenticationSelectionResolver {
if (processor.getAuthenticationSession().getAuthenticatedUser() != null) {
authenticationSelectionList =
Stream.concat(
processor.getAuthenticationSession().getAuthenticatedUser().getUserCredentialManager().getStoredCredentialsStream()
processor.getAuthenticationSession().getAuthenticatedUser().credentialManager().getStoredCredentialsStream()
.map(CredentialModel::getType),
processor.getAuthenticationSession().getAuthenticatedUser().getUserCredentialManager()
processor.getAuthenticationSession().getAuthenticatedUser().credentialManager()
.getConfiguredUserStorageCredentialTypesStream())
.distinct()
.filter(typeAuthExecMap::containsKey)

View file

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

View file

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

View file

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

View file

@ -11,7 +11,6 @@ import org.keycloak.events.Errors;
import org.keycloak.forms.login.LoginFormsProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialManager;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.RecoveryAuthnCodesCredentialModel;
@ -58,7 +57,7 @@ public class RecoveryAuthnCodesFormAuthenticator implements Authenticator {
RealmModel targetRealm = authnFlowContext.getRealm();
UserModel authenticatedUser = authnFlowContext.getUser();
if (!isDisabledByBruteForce(authnFlowContext, authenticatedUser)) {
boolean isValid = authenticatedUser.getUserCredentialManager().isValid(
boolean isValid = authenticatedUser.credentialManager().isValid(
UserCredentialModel.buildFromBackupAuthnCode(recoveryAuthnCodeUserInput.replace("-", "")));
if (!isValid) {
Response responseChallenge = createLoginForm(authnFlowContext, true,
@ -67,14 +66,14 @@ public class RecoveryAuthnCodesFormAuthenticator implements Authenticator {
authnFlowContext.failureChallenge(AuthenticationFlowError.INVALID_CREDENTIALS, responseChallenge);
} else {
result = true;
Optional<CredentialModel> optUserCredentialFound = authenticatedUser.getUserCredentialManager().getStoredCredentialsByTypeStream(
Optional<CredentialModel> optUserCredentialFound = authenticatedUser.credentialManager().getStoredCredentialsByTypeStream(
RecoveryAuthnCodesCredentialModel.TYPE).findFirst();
RecoveryAuthnCodesCredentialModel recoveryCodeCredentialModel = null;
if (optUserCredentialFound.isPresent()) {
recoveryCodeCredentialModel = RecoveryAuthnCodesCredentialModel
.createFromCredentialModel(optUserCredentialFound.get());
if (recoveryCodeCredentialModel.allCodesUsed()) {
authenticatedUser.getUserCredentialManager().removeStoredCredentialById(
authenticatedUser.credentialManager().removeStoredCredentialById(
recoveryCodeCredentialModel.getId());
}
}
@ -134,7 +133,7 @@ public class RecoveryAuthnCodesFormAuthenticator implements Authenticator {
@Override
public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) {
return user.getUserCredentialManager().isConfiguredFor(RecoveryAuthnCodesCredentialModel.TYPE);
return user.credentialManager().isConfiguredFor(RecoveryAuthnCodesCredentialModel.TYPE);
}
@Override

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -37,7 +37,6 @@ import org.keycloak.models.ModelException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.utils.FormMessage;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.messages.Messages;
@ -46,7 +45,6 @@ import org.keycloak.sessions.AuthenticationSessionModel;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@ -139,7 +137,7 @@ public class UpdatePassword implements RequiredActionProvider, RequiredActionFac
}
try {
user.getUserCredentialManager().updateCredential(UserCredentialModel.password(passwordNew, false));
user.credentialManager().updateCredential(UserCredentialModel.password(passwordNew, false));
context.success();
} catch (ModelException me) {
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");
final Stream<CredentialModel> otpCredentials = (otpCredentialProvider.isConfiguredFor(context.getRealm(), context.getUser()))
? context.getUser().getUserCredentialManager().getStoredCredentialsByTypeStream(OTPCredentialModel.TYPE)
? context.getUser().credentialManager().getStoredCredentialsByTypeStream(OTPCredentialModel.TYPE)
: Stream.empty();
if (otpCredentials.count() >= 1 && Validation.isBlank(userLabel)) {
Response challenge = context.form()

View file

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

View file

@ -19,7 +19,6 @@ package org.keycloak.credential;
import org.jboss.logging.Logger;
import org.keycloak.common.util.ObjectUtil;
import org.keycloak.common.util.Time;
import org.keycloak.models.RequiredActionProviderModel;
import org.keycloak.models.credential.OTPCredentialModel;
import org.keycloak.models.credential.dto.OTPCredentialData;
import org.keycloak.models.credential.dto.OTPSecretData;
@ -51,12 +50,12 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
if (credentialModel.getCreatedDate() == null) {
credentialModel.setCreatedDate(Time.currentTimeMillis());
}
return user.getUserCredentialManager().createStoredCredential(credentialModel);
return user.credentialManager().createStoredCredential(credentialModel);
}
@Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
return user.credentialManager().removeStoredCredentialById(credentialId);
}
@Override
@ -72,7 +71,7 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
@Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
if (!supportsCredentialType(credentialType)) return false;
return user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType).findAny().isPresent();
return user.credentialManager().getStoredCredentialsByTypeStream(credentialType).findAny().isPresent();
}
public boolean isConfiguredFor(RealmModel realm, UserModel user){
@ -95,7 +94,7 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
return false;
}
CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialInput.getCredentialId());
CredentialModel credential = user.credentialManager().getStoredCredentialById(credentialInput.getCredentialId());
OTPCredentialModel otpCredentialModel = OTPCredentialModel.createFromCredentialModel(credential);
OTPSecretData secretData = otpCredentialModel.getOTPSecretData();
OTPCredentialData credentialData = otpCredentialModel.getOTPCredentialData();
@ -107,7 +106,7 @@ public class OTPCredentialProvider implements CredentialProvider<OTPCredentialMo
return false;
}
otpCredentialModel.updateCounter(counter);
user.getUserCredentialManager().updateStoredCredential(otpCredentialModel);
user.credentialManager().updateStoredCredential(otpCredentialModel);
return true;
} else if (OTPCredentialModel.TOTP.equals(credentialData.getSubType())) {
TimeBasedOTP validator = new TimeBasedOTP(credentialData.getAlgorithm(), credentialData.getDigits(), credentialData.getPeriod(), policy.getLookAheadWindow());

View file

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

View file

@ -1,10 +1,7 @@
package org.keycloak.credential;
import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.common.Profile;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.RecoveryAuthnCodesCredentialModel;
@ -39,15 +36,15 @@ public class RecoveryAuthnCodesCredentialProvider
public CredentialModel createCredential(RealmModel realm, UserModel user,
RecoveryAuthnCodesCredentialModel credentialModel) {
user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType()).findFirst()
user.credentialManager().getStoredCredentialsByTypeStream(getType()).findFirst()
.ifPresent(model -> deleteCredential(realm, user, model.getId()));
return user.getUserCredentialManager().createStoredCredential(credentialModel);
return user.credentialManager().createStoredCredential(credentialModel);
}
@Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
return user.credentialManager().removeStoredCredentialById(credentialId);
}
@Override
@ -95,13 +92,13 @@ public class RecoveryAuthnCodesCredentialProvider
@Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
return user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType).anyMatch(Objects::nonNull);
return user.credentialManager().getStoredCredentialsByTypeStream(credentialType).anyMatch(Objects::nonNull);
}
@Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput credentialInput) {
String rawInputRecoveryAuthnCode = credentialInput.getChallengeResponse();
Optional<CredentialModel> credential = user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType()).findFirst();
Optional<CredentialModel> credential = user.credentialManager().getStoredCredentialsByTypeStream(getType()).findFirst();
if (credential.isPresent()) {
RecoveryAuthnCodesCredentialModel credentialModel = RecoveryAuthnCodesCredentialModel
.createFromCredentialModel(credential.get());
@ -111,7 +108,7 @@ public class RecoveryAuthnCodesCredentialProvider
String nextRecoveryCode = nextRecoveryAuthnCode.get().getEncodedHashedValue();
if (RecoveryAuthnCodesUtils.verifyRecoveryCodeInput(rawInputRecoveryAuthnCode, nextRecoveryCode)) {
credentialModel.removeRecoveryAuthnCode();
user.getUserCredentialManager().updateStoredCredential(credentialModel);
user.credentialManager().updateStoredCredential(credentialModel);
return true;
}

View file

@ -33,7 +33,6 @@ import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import com.webauthn4j.WebAuthnManager;
import com.webauthn4j.authenticator.Authenticator;
import com.webauthn4j.authenticator.AuthenticatorImpl;
import com.webauthn4j.data.AuthenticationData;
@ -71,13 +70,13 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
credentialModel.setCreatedDate(Time.currentTimeMillis());
}
return user.getUserCredentialManager().createStoredCredential(credentialModel);
return user.credentialManager().createStoredCredential(credentialModel);
}
@Override
public boolean deleteCredential(RealmModel realm, UserModel user, String credentialId) {
logger.debugv("Delete WebAuthn credential. username = {0}, credentialId = {1}", user.getUsername(), credentialId);
return user.getUserCredentialManager().removeStoredCredentialById(credentialId);
return user.credentialManager().removeStoredCredentialById(credentialId);
}
@Override
@ -170,7 +169,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
@Override
public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) {
if (!supportsCredentialType(credentialType)) return false;
return user.getUserCredentialManager().getStoredCredentialsByTypeStream(credentialType).count() > 0;
return user.credentialManager().getStoredCredentialsByTypeStream(credentialType).count() > 0;
}
@ -208,7 +207,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
logger.debugv("response.getAuthenticatorData().getFlags() = {0}", authenticationData.getAuthenticatorData().getFlags());
CredentialModel credModel = user.getUserCredentialManager().getStoredCredentialById(auth.getCredentialDBId());
CredentialModel credModel = user.credentialManager().getStoredCredentialById(auth.getCredentialDBId());
WebAuthnCredentialModel webAuthnCredModel = getCredentialFromModel(credModel);
// update authenticator counter
@ -217,7 +216,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
long count = auth.getCount();
if (count > 0) {
webAuthnCredModel.updateCounter(count + 1);
user.getUserCredentialManager().updateStoredCredential(webAuthnCredModel);
user.credentialManager().updateStoredCredential(webAuthnCredModel);
}
logger.debugf("Successfully validated WebAuthn credential for user %s", user.getUsername());
@ -242,7 +241,7 @@ public class WebAuthnCredentialProvider implements CredentialProvider<WebAuthnCr
private List<WebAuthnCredentialModelInput> getWebAuthnCredentialModelList(RealmModel realm, UserModel user) {
return user.getUserCredentialManager().getStoredCredentialsByTypeStream(getType())
return user.credentialManager().getStoredCredentialsByTypeStream(getType())
.map(this::getCredentialInputFromCredentialModel)
.collect(Collectors.toList());
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -140,7 +140,7 @@ public class AccountConsole {
boolean isTotpConfigured = false;
boolean deleteAccountAllowed = false;
if (user != null) {
isTotpConfigured = user.getUserCredentialManager().isConfiguredFor(realm.getOTPPolicy().getType());
isTotpConfigured = user.credentialManager().isConfiguredFor(realm.getOTPPolicy().getType());
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();
}

View file

@ -175,7 +175,7 @@ public class AccountCredentialResource {
.collect(Collectors.toList());
Set<String> enabledCredentialTypes = getEnabledCredentialTypes(credentialProviders);
Stream<CredentialModel> modelsStream = includeUserCredentials ? user.getUserCredentialManager().getStoredCredentialsStream() : Stream.empty();
Stream<CredentialModel> modelsStream = includeUserCredentials ? user.credentialManager().getStoredCredentialsStream() : Stream.empty();
List<CredentialModel> models = modelsStream.collect(Collectors.toList());
Function<CredentialProvider, CredentialContainer> toCredentialContainer = (credentialProvider) -> {
@ -204,7 +204,7 @@ public class AccountCredentialResource {
userCredentialMetadataModels = credentialMetadataList.stream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList());
if (userCredentialMetadataModels.isEmpty() &&
user.getUserCredentialManager().isConfiguredFor(credentialProvider.getType())) {
user.credentialManager().isConfiguredFor(credentialProvider.getType())) {
// 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
CredentialMetadataRepresentation metadataRepresentation = new CredentialMetadataRepresentation();
@ -279,11 +279,11 @@ public class AccountCredentialResource {
@NoCache
public void removeCredential(final @PathParam("credentialId") String credentialId) {
auth.require(AccountRoles.MANAGE_ACCOUNT);
CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialId);
CredentialModel credential = user.credentialManager().getStoredCredentialById(credentialId);
if (credential == null) {
throw new NotFoundException("Credential not found");
}
user.getUserCredentialManager().removeStoredCredentialById(credentialId);
user.credentialManager().removeStoredCredentialById(credentialId);
}
@ -299,14 +299,14 @@ public class AccountCredentialResource {
@NoCache
public void setLabel(final @PathParam("credentialId") String credentialId, String userLabel) {
auth.require(AccountRoles.MANAGE_ACCOUNT);
CredentialModel credential = user.getUserCredentialManager().getStoredCredentialById(credentialId);
CredentialModel credential = user.credentialManager().getStoredCredentialById(credentialId);
if (credential == null) {
throw new NotFoundException("Credential not found");
}
try {
String label = JsonSerialization.readValue(userLabel, String.class);
user.getUserCredentialManager().updateCredentialLabel(credentialId, label);
user.credentialManager().updateCredentialLabel(credentialId, label);
} catch (IOException ioe) {
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);
if (!user.getUserCredentialManager().isValid(cred)) {
if (!user.credentialManager().isValid(cred)) {
setReferrerOnPage();
errorEvent.error(Errors.INVALID_USER_CREDENTIALS);
return account.setError(Status.OK, Messages.INVALID_PASSWORD_EXISTING).createResponse(AccountPages.PASSWORD);
@ -620,7 +620,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
}
try {
user.getUserCredentialManager().updateCredential(UserCredentialModel.password(passwordNew, false));
user.credentialManager().updateCredential(UserCredentialModel.password(passwordNew, false));
} catch (ReadOnlyException mre) {
setReferrerOnPage();
errorEvent.error(Errors.NOT_ALLOWED);
@ -1028,7 +1028,7 @@ public class AccountFormService extends AbstractSecuredLocalService {
}
public static boolean isPasswordSet(KeycloakSession session, RealmModel realm, UserModel user) {
return user.getUserCredentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
return user.credentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
}
private String[] getReferrer() {

View file

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

View file

@ -23,11 +23,11 @@ public class PasswordUtil {
*/
@Deprecated
public boolean isConfigured(KeycloakSession session, RealmModel realm, UserModel user) {
return user.getUserCredentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
return user.credentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
}
public boolean isConfigured() {
return user.getUserCredentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
return user.credentialManager().isConfiguredFor(PasswordCredentialModel.TYPE);
}
public void update() {

View file

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

View file

@ -40,7 +40,7 @@ import org.keycloak.models.KeycloakSession;
import org.keycloak.models.OTPPolicy;
import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.cache.UserCache;
@ -104,7 +104,7 @@ public class BackwardsCompatibilityUserStorage implements UserLookupProvider, Us
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
return new LegacySingleUserCredentialManager(session, realm, this);
}
};

View file

@ -24,7 +24,7 @@ import org.keycloak.credential.CredentialModel;
import org.keycloak.credential.LegacySingleUserCredentialManager;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.keycloak.storage.StorageId;
@ -167,7 +167,7 @@ public class PassThroughFederatedUserStorageProvider implements
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
return new LegacySingleUserCredentialManager(session, realm, this);
}
};

View file

@ -27,7 +27,7 @@ import org.keycloak.models.KeycloakSession;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.PasswordCredentialModel;
@ -145,7 +145,7 @@ public class UserMapStorage implements UserLookupProvider.Streams, UserStoragePr
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
return new LegacySingleUserCredentialManager(session, realm, this);
}
};

View file

@ -24,7 +24,7 @@ import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.SingleUserCredentialManager;
import org.keycloak.models.SingleEntityCredentialManager;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.credential.PasswordCredentialModel;
@ -136,7 +136,7 @@ public class UserPropertyFileStorage implements UserLookupProvider.Streams, User
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
return new LegacySingleUserCredentialManager(session, realm, this);
}
};
@ -148,7 +148,7 @@ public class UserPropertyFileStorage implements UserLookupProvider.Streams, User
}
@Override
public SingleUserCredentialManager getUserCredentialManager() {
public SingleEntityCredentialManager credentialManager() {
return new LegacySingleUserCredentialManager(session, realm, this);
}
};

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -887,19 +887,19 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor");
Assert.assertFalse(StorageId.isLocalStorage(user));
Stream<CredentialModel> credentials = user.getUserCredentialManager().getStoredCredentialsStream();
Stream<CredentialModel> credentials = user.credentialManager().getStoredCredentialsStream();
org.keycloak.testsuite.Assert.assertEquals(0, credentials.count());
// Create password
CredentialModel passwordCred = PasswordCredentialModel.createFromValues("my-algorithm", "theSalt".getBytes(), 22, "ABC");
passwordCred = user.getUserCredentialManager().createStoredCredential(passwordCred);
passwordCred = user.credentialManager().createStoredCredential(passwordCred);
passwordId.set(passwordCred.getId());
// Create Password and 2 OTP credentials (password was already created)
CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1");
CredentialModel otp2 = OTPCredentialModel.createFromPolicy(realm, "secret2");
otp1 = user.getUserCredentialManager().createStoredCredential(otp1);
otp2 = user.getUserCredentialManager().createStoredCredential(otp2);
otp1 = user.credentialManager().createStoredCredential(otp1);
otp2 = user.credentialManager().createStoredCredential(otp2);
otp1Id.set(otp1.getId());
otp2Id.set(otp2.getId());
});
@ -910,18 +910,18 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: password, otp1, otp2
List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
List<CredentialModel> list = user.credentialManager().getStoredCredentialsStream()
.collect(Collectors.toList());
assertOrder(list, passwordId.get(), otp1Id.get(), otp2Id.get());
// Assert can't move password when newPreviousCredential not found
assertFalse(user.getUserCredentialManager().moveStoredCredentialTo(passwordId.get(), "not-known"));
assertFalse(user.credentialManager().moveStoredCredentialTo(passwordId.get(), "not-known"));
// Assert can't move credential when not found
assertFalse(user.getUserCredentialManager().moveStoredCredentialTo("not-known", otp2Id.get()));
assertFalse(user.credentialManager().moveStoredCredentialTo("not-known", otp2Id.get()));
// Move otp2 up
assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), passwordId.get()));
assertTrue(user.credentialManager().moveStoredCredentialTo(otp2Id.get(), passwordId.get()));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -929,12 +929,12 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: password, otp2, otp1
List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
List<CredentialModel> list = user.credentialManager().getStoredCredentialsStream()
.collect(Collectors.toList());
assertOrder(list, passwordId.get(), otp2Id.get(), otp1Id.get());
// Move otp2 to the top
org.keycloak.testsuite.Assert.assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), null));
org.keycloak.testsuite.Assert.assertTrue(user.credentialManager().moveStoredCredentialTo(otp2Id.get(), null));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -942,12 +942,12 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: otp2, password, otp1
List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
List<CredentialModel> list = user.credentialManager().getStoredCredentialsStream()
.collect(Collectors.toList());
assertOrder(list, otp2Id.get(), passwordId.get(), otp1Id.get());
// Move password down
assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(passwordId.get(), otp1Id.get()));
assertTrue(user.credentialManager().moveStoredCredentialTo(passwordId.get(), otp1Id.get()));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -955,12 +955,12 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: otp2, otp1, password
List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
List<CredentialModel> list = user.credentialManager().getStoredCredentialsStream()
.collect(Collectors.toList());
assertOrder(list, otp2Id.get(), otp1Id.get(), passwordId.get());
// Remove otp2 down two positions
assertTrue(user.getUserCredentialManager().moveStoredCredentialTo(otp2Id.get(), passwordId.get()));
assertTrue(user.credentialManager().moveStoredCredentialTo(otp2Id.get(), passwordId.get()));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -968,12 +968,12 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: otp2, otp1, password
List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
List<CredentialModel> list = user.credentialManager().getStoredCredentialsStream()
.collect(Collectors.toList());
assertOrder(list, otp1Id.get(), passwordId.get(), otp2Id.get());
// Remove password
assertTrue(user.getUserCredentialManager().removeStoredCredentialById(passwordId.get()));
assertTrue(user.credentialManager().removeStoredCredentialById(passwordId.get()));
});
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), (KeycloakSession currentSession) -> {
@ -981,7 +981,7 @@ public class UserStorageTest extends AbstractAuthTest {
UserModel user = currentSession.users().getUserByUsername(realm, "thor");
// Assert priorities: otp2, password
List<CredentialModel> list = user.getUserCredentialManager().getStoredCredentialsStream()
List<CredentialModel> list = user.credentialManager().getStoredCredentialsStream()
.collect(Collectors.toList());
assertOrder(list, otp1Id.get(), otp2Id.get());
});
@ -997,7 +997,7 @@ public class UserStorageTest extends AbstractAuthTest {
Assert.assertFalse(StorageId.isLocalStorage(user));
CredentialModel otp1 = OTPCredentialModel.createFromPolicy(realm, "secret1");
user.getUserCredentialManager().createStoredCredential(otp1);
user.credentialManager().createStoredCredential(otp1);
});
UserResource user1 = ApiUtil.findUserByUsernameId(testRealmResource(), "thor");

View file

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

View file

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

View file

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

View file

@ -88,13 +88,13 @@ public class MultipleRealmsTest extends AbstractTestRealmKeycloakTest {
Assert.assertNotEquals(r1user1.getId(), r2user1.getId());
// Test password
r1user1.getUserCredentialManager().updateCredential(UserCredentialModel.password("pass1"));
r2user1.getUserCredentialManager().updateCredential(UserCredentialModel.password("pass2"));
r1user1.credentialManager().updateCredential(UserCredentialModel.password("pass1"));
r2user1.credentialManager().updateCredential(UserCredentialModel.password("pass2"));
Assert.assertTrue(r1user1.getUserCredentialManager().isValid(UserCredentialModel.password("pass1")));
Assert.assertFalse(r1user1.getUserCredentialManager().isValid(UserCredentialModel.password("pass2")));
Assert.assertFalse(r2user1.getUserCredentialManager().isValid(UserCredentialModel.password("pass1")));
Assert.assertTrue(r2user1.getUserCredentialManager().isValid(UserCredentialModel.password("pass2")));
Assert.assertTrue(r1user1.credentialManager().isValid(UserCredentialModel.password("pass1")));
Assert.assertFalse(r1user1.credentialManager().isValid(UserCredentialModel.password("pass2")));
Assert.assertFalse(r2user1.credentialManager().isValid(UserCredentialModel.password("pass1")));
Assert.assertTrue(r2user1.credentialManager().isValid(UserCredentialModel.password("pass2")));
// Test searching
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");
user.setEnabled(true);
user.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
user.credentialManager().updateCredential(UserCredentialModel.password("password"));
user.grantRole(exampleRole);
user.grantRole(impersonateRole);
UserModel bad = session.users().addUser(realm, "bad-impersonator");
bad.setEnabled(true);
bad.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
bad.credentialManager().updateCredential(UserCredentialModel.password("password"));
}
@Override
@ -704,7 +704,7 @@ public class ClientTokenExchangeSAML2Test extends AbstractKeycloakTest {
UserModel impersonatedUser = session.users().addUser(realm, "impersonated-user");
impersonatedUser.setEnabled(true);
impersonatedUser.getUserCredentialManager().updateCredential(UserCredentialModel.password("password"));
impersonatedUser.credentialManager().updateCredential(UserCredentialModel.password("password"));
impersonatedUser.grantRole(exampleRole);
}

View file

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

View file

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