diff --git a/core/src/main/java/org/keycloak/representations/idm/CredentialRepresentation.java b/core/src/main/java/org/keycloak/representations/idm/CredentialRepresentation.java index 568dfd157d..f48d726dd7 100755 --- a/core/src/main/java/org/keycloak/representations/idm/CredentialRepresentation.java +++ b/core/src/main/java/org/keycloak/representations/idm/CredentialRepresentation.java @@ -17,6 +17,10 @@ package org.keycloak.representations.idm; +import org.keycloak.common.util.MultivaluedHashMap; + +import java.util.Map; + /** * @author Bill Burke * @version $Revision: 1 $ @@ -45,6 +49,7 @@ public class CredentialRepresentation { private Integer digits; private Integer period; private Long createdDate; + private MultivaluedHashMap config; // only used when updating a credential. Might set required action protected Boolean temporary; @@ -144,4 +149,12 @@ public class CredentialRepresentation { public void setCreatedDate(Long createdDate) { this.createdDate = createdDate; } + + public MultivaluedHashMap getConfig() { + return config; + } + + public void setConfig(MultivaluedHashMap config) { + this.config = config; + } } diff --git a/core/src/main/java/org/keycloak/representations/idm/UserRepresentation.java b/core/src/main/java/org/keycloak/representations/idm/UserRepresentation.java index e6e7ddd814..b715bf5c95 100755 --- a/core/src/main/java/org/keycloak/representations/idm/UserRepresentation.java +++ b/core/src/main/java/org/keycloak/representations/idm/UserRepresentation.java @@ -123,10 +123,12 @@ public class UserRepresentation { this.enabled = enabled; } + @Deprecated public Boolean isTotp() { return totp; } + @Deprecated public void setTotp(Boolean totp) { this.totp = totp; } diff --git a/distribution/demo-dist/src/main/xslt/standalone.xsl b/distribution/demo-dist/src/main/xslt/standalone.xsl index ca45244efe..d67ce63f02 100755 --- a/distribution/demo-dist/src/main/xslt/standalone.xsl +++ b/distribution/demo-dist/src/main/xslt/standalone.xsl @@ -43,7 +43,7 @@ - jdbc:h2:${jboss.server.data.dir}/keycloak;AUTO_SERVER=TRUE + jdbc:h2:${jboss.server.data.dir}/keycloak;AUTO_SERVER=TRUE h2 sa diff --git a/examples/providers/authenticator/README.md b/examples/providers/authenticator/README.md index 54dc752734..ef612cc2a7 100755 --- a/examples/providers/authenticator/README.md +++ b/examples/providers/authenticator/README.md @@ -1,31 +1,23 @@ Example Custom Authenticator =================================================== -This is an example of defining a custom Authenticator and Required action. This example is explained in the user documentation -of Keycloak. To deploy, build this directory then take the jar and copy it to providers directory. Alternatively you can deploy as a module by running: +1. First, Keycloak must be running. - KEYCLOAK_HOME/bin/jboss-cli.sh --command="module add --name=org.keycloak.examples.secret-question --resources=target/authenticator-required-action-example.jar --dependencies=org.keycloak.keycloak-core,org.keycloak.keycloak-server-spi,org.keycloak.keycloak-services,org.jboss.resteasy.resteasy-jaxrs,javax.ws.rs.api" +2. Execute the follow. This will build the example and deploy it -Then registering the provider by editing `standalone/configuration/standalone.xml` and adding the module to the providers element: + $ mvn clean install wildfly:deploy - - ... - module:org.keycloak.examples.secret-question - +3. Copy the secret-question.ftl and secret-question-config.ftl files to the themes/base/login directory. -You then have to copy the secret-question.ftl and secret-question-config.ftl files to the themes/base/login directory. +4. Login to admin console. Hit browser refresh if you are already logged in so that the new providers show up. -After you do all this, you then have to reboot keycloak. When reboot is complete, you will need to log into -the admin console to create a new flow with your new authenticator. +5. Go to the Authentication menu item and go to the Flow tab, you will be able to view the currently + defined flows. You cannot modify an built in flows, so, to add the Authenticator you + have to copy an existing flow or create your own. Copy the "Browser" flow. -If you go to the Authentication menu item and go to the Flow tab, you will be able to view the currently -defined flows. You cannot modify an built in flows, so, to add the Authenticator you -have to copy an existing flow or create your own. +6. In your copy, click the "Actions" menu item and "Add Execution". Pick Secret Question -Next you have to register your required action. -Click on the Required Actions tab. Click on the Register button and choose your new Required Action. -Your new required action should now be displayed and enabled in the required actions list. +7. Next you have to register the required action that you created. Click on the Required Actions tab in the Authenticaiton menu. + Click on the Register button and choose your new Required Action. + Your new required action should now be displayed and enabled in the required actions list. -I'm hoping the UI is intuitive enough so that you -can figure out for yourself how to create a flow and add the Authenticator and Required Action. We're looking to add a screencast -to show this in action. diff --git a/examples/providers/authenticator/pom.xml b/examples/providers/authenticator/pom.xml index 5a1b100d15..16a95d6fe6 100755 --- a/examples/providers/authenticator/pom.xml +++ b/examples/providers/authenticator/pom.xml @@ -55,5 +55,22 @@ authenticator-required-action-example + + + org.apache.maven.plugins + maven-compiler-plugin + + 1.8 + 1.8 + + + + org.wildfly.plugins + wildfly-maven-plugin + + false + + + diff --git a/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionAuthenticator.java b/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionAuthenticator.java index 3fdd4ff6e4..fb71a7c9cf 100755 --- a/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionAuthenticator.java +++ b/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionAuthenticator.java @@ -17,17 +17,20 @@ package org.keycloak.examples.authenticator; +import org.jboss.resteasy.spi.HttpResponse; +import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.keycloak.authentication.AuthenticationFlowContext; import org.keycloak.authentication.AuthenticationFlowError; import org.keycloak.authentication.Authenticator; +import org.keycloak.common.util.ServerCookie; import org.keycloak.models.AuthenticatorConfigModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; -import org.keycloak.models.UserCredentialValueModel; +import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserModel; -import org.keycloak.services.util.CookieHelper; import javax.ws.rs.core.Cookie; +import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.net.URI; @@ -86,25 +89,29 @@ public class SecretQuestionAuthenticator implements Authenticator { } URI uri = context.getUriInfo().getBaseUriBuilder().path("realms").path(context.getRealm().getName()).build(); - CookieHelper.addCookie("SECRET_QUESTION_ANSWERED", "true", + addCookie("SECRET_QUESTION_ANSWERED", "true", uri.getRawPath(), null, null, maxCookieAge, false, true); } + public static void addCookie(String name, String value, String path, String domain, String comment, int maxAge, boolean secure, boolean httpOnly) { + HttpResponse response = ResteasyProviderFactory.getContextData(HttpResponse.class); + StringBuffer cookieBuf = new StringBuffer(); + ServerCookie.appendCookieValue(cookieBuf, 1, name, value, path, domain, comment, maxAge, secure, httpOnly); + String cookie = cookieBuf.toString(); + response.getOutputHeaders().add(HttpHeaders.SET_COOKIE, cookie); + } + + protected boolean validateAnswer(AuthenticationFlowContext context) { MultivaluedMap formData = context.getHttpRequest().getDecodedFormParameters(); String secret = formData.getFirst("secret_answer"); - UserCredentialValueModel cred = null; - for (UserCredentialValueModel model : context.getUser().getCredentialsDirectly()) { - if (model.getType().equals(CREDENTIAL_TYPE)) { - cred = model; - break; - } - } - - return cred.getValue().equals(secret); + UserCredentialModel input = new UserCredentialModel(); + input.setType(SecretQuestionCredentialProvider.SECRET_QUESTION); + input.setValue(secret); + return context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), input); } @Override @@ -114,7 +121,7 @@ public class SecretQuestionAuthenticator implements Authenticator { @Override public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { - return session.users().configuredForCredentialType(CREDENTIAL_TYPE, realm, user); + return session.userCredentialManager().isConfiguredFor(realm, user, SecretQuestionCredentialProvider.SECRET_QUESTION); } @Override diff --git a/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionCredentialProvider.java b/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionCredentialProvider.java new file mode 100644 index 0000000000..520aeb0080 --- /dev/null +++ b/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionCredentialProvider.java @@ -0,0 +1,117 @@ +/* + * Copyright 2016 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.examples.authenticator; + +import org.keycloak.common.util.Time; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialInputUpdater; +import org.keycloak.credential.CredentialInputValidator; +import org.keycloak.credential.CredentialModel; +import org.keycloak.credential.CredentialProvider; +import org.keycloak.credential.PasswordCredentialProvider; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.RealmModel; +import org.keycloak.models.UserCredentialModel; +import org.keycloak.models.UserModel; +import org.keycloak.models.cache.CachedUserModel; +import org.keycloak.models.cache.OnUserCache; + +import java.util.List; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class SecretQuestionCredentialProvider implements CredentialProvider, CredentialInputValidator, CredentialInputUpdater, OnUserCache { + public static final String SECRET_QUESTION = "SECRET_QUESTION"; + public static final String CACHE_KEY = SecretQuestionCredentialProvider.class.getName() + "." + SECRET_QUESTION; + + protected KeycloakSession session; + + public SecretQuestionCredentialProvider(KeycloakSession session) { + this.session = session; + } + + public CredentialModel getSecret(RealmModel realm, UserModel user) { + CredentialModel secret = null; + if (user instanceof CachedUserModel) { + CachedUserModel cached = (CachedUserModel)user; + secret = (CredentialModel)cached.getCachedWith().get(CACHE_KEY); + + } else { + List creds = session.userCredentialManager().getStoredCredentialsByType(realm, user, SECRET_QUESTION); + if (!creds.isEmpty()) secret = creds.get(0); + } + return secret; + } + + + @Override + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + if (!SECRET_QUESTION.equals(input.getType())) return false; + if (!(input instanceof UserCredentialModel)) return false; + UserCredentialModel credInput = (UserCredentialModel) input; + List creds = session.userCredentialManager().getStoredCredentialsByType(realm, user, SECRET_QUESTION); + if (creds.isEmpty()) { + CredentialModel secret = new CredentialModel(); + secret.setType(SECRET_QUESTION); + secret.setValue(credInput.getValue()); + secret.setCreatedDate(Time.currentTimeMillis()); + session.userCredentialManager().createCredential(realm ,user, secret); + } else { + creds.get(0).setValue(credInput.getValue()); + session.userCredentialManager().updateCredential(realm, user, creds.get(0)); + } + session.getUserCache().evict(realm, user); + return true; + } + + @Override + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + if (!SECRET_QUESTION.equals(credentialType)) return; + session.userCredentialManager().disableCredential(realm, user, credentialType); + session.getUserCache().evict(realm, user); + + } + + @Override + public boolean supportsCredentialType(String credentialType) { + return SECRET_QUESTION.equals(credentialType); + } + + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + if (!SECRET_QUESTION.equals(credentialType)) return false; + return getSecret(realm, user) != null; + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (!SECRET_QUESTION.equals(input.getType())) return false; + if (!(input instanceof UserCredentialModel)) return false; + + String secret = getSecret(realm, user).getValue(); + + return secret != null && ((UserCredentialModel)input).getValue().equals(secret); + } + + @Override + public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) { + List creds = session.userCredentialManager().getStoredCredentialsByType(realm, user, SECRET_QUESTION); + if (!creds.isEmpty()) user.getCachedWith().put(CACHE_KEY, creds.get(0)); + } +} diff --git a/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionCredentialProviderFactory.java b/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionCredentialProviderFactory.java new file mode 100644 index 0000000000..98b65ae9df --- /dev/null +++ b/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionCredentialProviderFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright 2016 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.examples.authenticator; + +import org.keycloak.credential.CredentialProvider; +import org.keycloak.credential.CredentialProviderFactory; +import org.keycloak.models.KeycloakSession; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class SecretQuestionCredentialProviderFactory implements CredentialProviderFactory { + @Override + public String getId() { + return "secret-question"; + } + + @Override + public CredentialProvider create(KeycloakSession session) { + return new SecretQuestionCredentialProvider(session); + } +} diff --git a/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionRequiredAction.java b/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionRequiredAction.java index f196205b70..a1a65459e7 100755 --- a/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionRequiredAction.java +++ b/examples/providers/authenticator/src/main/java/org/keycloak/examples/authenticator/SecretQuestionRequiredAction.java @@ -19,6 +19,7 @@ package org.keycloak.examples.authenticator; import org.keycloak.authentication.RequiredActionContext; import org.keycloak.authentication.RequiredActionProvider; +import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserCredentialValueModel; import javax.ws.rs.core.Response; @@ -45,10 +46,10 @@ public class SecretQuestionRequiredAction implements RequiredActionProvider { @Override public void processAction(RequiredActionContext context) { String answer = (context.getHttpRequest().getDecodedFormParameters().getFirst("secret_answer")); - UserCredentialValueModel model = new UserCredentialValueModel(); - model.setValue(answer); - model.setType(SecretQuestionAuthenticator.CREDENTIAL_TYPE); - context.getUser().updateCredentialDirectly(model); + UserCredentialModel input = new UserCredentialModel(); + input.setType(SecretQuestionCredentialProvider.SECRET_QUESTION); + input.setValue(answer); + context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), input); context.success(); } diff --git a/examples/providers/authenticator/src/main/resources/META-INF/services/org.keycloak.credential.CredentialProviderFactory b/examples/providers/authenticator/src/main/resources/META-INF/services/org.keycloak.credential.CredentialProviderFactory new file mode 100644 index 0000000000..a221e371cc --- /dev/null +++ b/examples/providers/authenticator/src/main/resources/META-INF/services/org.keycloak.credential.CredentialProviderFactory @@ -0,0 +1 @@ + org.keycloak.examples.authenticator.SecretQuestionCredentialProviderFactory \ No newline at end of file diff --git a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/BasePropertiesFederationProvider.java b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/BasePropertiesFederationProvider.java index ddf54404d3..3ee3a0b779 100755 --- a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/BasePropertiesFederationProvider.java +++ b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/BasePropertiesFederationProvider.java @@ -17,6 +17,7 @@ package org.keycloak.examples.federation.properties; +import org.keycloak.credential.CredentialInput; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; @@ -146,48 +147,29 @@ public abstract class BasePropertiesFederationProvider implements UserFederation return properties.containsKey(local.getUsername()); } - /** - * hardcoded to only return PASSWORD - * - * @param user - * @return - */ - @Override - public Set getSupportedCredentialTypes(UserModel user) { - return supportedCredentialTypes; - } - @Override public Set getSupportedCredentialTypes() { return supportedCredentialTypes; } @Override - public boolean validCredentials(RealmModel realm, UserModel user, List input) { - for (UserCredentialModel cred : input) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - String password = properties.getProperty(user.getUsername()); - if (password == null) return false; - return password.equals(cred.getValue()); - } else { - return false; // invalid cred type - } - } - return false; + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel)) return false; + + UserCredentialModel cred = (UserCredentialModel)input; + String password = properties.getProperty(user.getUsername()); + if (password == null) return false; + return password.equals(cred.getValue()); } @Override - public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) { - for (UserCredentialModel cred : input) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - String password = properties.getProperty(user.getUsername()); - if (password == null) return false; - return password.equals(cred.getValue()); - } else { - return false; // invalid cred type - } - } - return true; + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + return getSupportedCredentialTypes().contains(credentialType); + } + + @Override + public boolean supportsCredentialType(String credentialType) { + return getSupportedCredentialTypes().contains(credentialType); } @Override diff --git a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationProvider.java b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationProvider.java index 2776b292ad..ee57104793 100755 --- a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationProvider.java +++ b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ClasspathPropertiesFederationProvider.java @@ -17,8 +17,10 @@ package org.keycloak.examples.federation.properties; +import org.keycloak.credential.CredentialInput; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; +import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserFederationProviderModel; import org.keycloak.models.UserModel; @@ -80,6 +82,13 @@ public class ClasspathPropertiesFederationProvider extends BasePropertiesFederat throw new IllegalStateException("Remove not supported"); } + @Override + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + return false; + } + @Override + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + } } diff --git a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/FilePropertiesFederationProvider.java b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/FilePropertiesFederationProvider.java index 2bfa932674..bc506843f8 100755 --- a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/FilePropertiesFederationProvider.java +++ b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/FilePropertiesFederationProvider.java @@ -17,8 +17,10 @@ package org.keycloak.examples.federation.properties; +import org.keycloak.credential.CredentialInput; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; +import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserFederationProviderModel; import org.keycloak.models.UserModel; @@ -98,6 +100,13 @@ public class FilePropertiesFederationProvider extends BasePropertiesFederationPr } } + @Override + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + return false; + } + @Override + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + } } diff --git a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ReadonlyUserModelProxy.java b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ReadonlyUserModelProxy.java index d1cec50d69..5a1e0df059 100755 --- a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ReadonlyUserModelProxy.java +++ b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/ReadonlyUserModelProxy.java @@ -39,19 +39,4 @@ public class ReadonlyUserModelProxy extends UserModelDelegate { throw new IllegalStateException("Username is readonly"); } - @Override - public void updateCredentialDirectly(UserCredentialValueModel cred) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - throw new IllegalStateException("Passwords are readonly"); - } - super.updateCredentialDirectly(cred); - } - - @Override - public void updateCredential(UserCredentialModel cred) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - throw new IllegalStateException("Passwords are readonly"); - } - super.updateCredential(cred); - } } diff --git a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/WritableUserModelProxy.java b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/WritableUserModelProxy.java index 93f0b3ddf0..e294f82dd3 100755 --- a/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/WritableUserModelProxy.java +++ b/examples/providers/federation-provider/src/main/java/org/keycloak/examples/federation/properties/WritableUserModelProxy.java @@ -64,26 +64,4 @@ public class WritableUserModelProxy extends UserModelDelegate { } - @Override - public void updateCredentialDirectly(UserCredentialValueModel cred) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - throw new IllegalStateException("Shouldn't be using this method"); - } - super.updateCredentialDirectly(cred); - } - - @Override - public void updateCredential(UserCredentialModel cred) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - synchronized (provider.getProperties()) { - if (!provider.getProperties().containsKey(delegate.getUsername())) { - throw new IllegalStateException("no user of that in properties file"); - } - provider.getProperties().setProperty(delegate.getUsername(), cred.getValue()); - provider.save(); - } - } else { - super.updateCredential(cred); - } - } } diff --git a/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/EjbExampleUserStorageProvider.java b/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/EjbExampleUserStorageProvider.java index a9bbc9b961..8f7f147d43 100644 --- a/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/EjbExampleUserStorageProvider.java +++ b/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/EjbExampleUserStorageProvider.java @@ -18,16 +18,21 @@ package org.keycloak.examples.storage.user; import org.jboss.logging.Logger; import org.keycloak.component.ComponentModel; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialInputUpdater; +import org.keycloak.credential.CredentialInputValidator; +import org.keycloak.credential.CredentialModel; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserModel; +import org.keycloak.models.cache.CachedUserModel; +import org.keycloak.models.cache.OnUserCache; import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.storage.StorageId; import org.keycloak.storage.UserStorageProvider; -import org.keycloak.storage.user.UserCredentialValidatorProvider; import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.storage.user.UserQueryProvider; import org.keycloak.storage.user.UserRegistrationProvider; @@ -52,9 +57,13 @@ import java.util.Map; public class EjbExampleUserStorageProvider implements UserStorageProvider, UserLookupProvider, UserRegistrationProvider, - UserCredentialValidatorProvider, - UserQueryProvider { + UserQueryProvider, + CredentialInputUpdater, + CredentialInputValidator, + OnUserCache +{ private static final Logger logger = Logger.getLogger(EjbExampleUserStorageProvider.class); + public static final String PASSWORD_CACHE_KEY = UserAdapter.class.getName() + ".password"; @PersistenceContext protected EntityManager em; @@ -150,18 +159,69 @@ public class EjbExampleUserStorageProvider implements UserStorageProvider, } @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List input) { - // having a "password" attribute is a workaround so that passwords can be cached. All done for performance reasons... - // If we override getCredentialsDirectly/updateCredentialsDirectly - // then the realm passsword policy will/may try and overwrite the plain text password with a hash. - // If you don't like this workaround, you can query the database every time to validate the password - for (UserCredentialModel cred : input) { - if (!UserCredentialModel.PASSWORD.equals(cred.getType())) return false; - if (!cred.getValue().equals(user.getFirstAttribute("password"))) return false; + public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) { + String password = ((UserAdapter)delegate).getPassword(); + if (password != null) { + user.getCachedWith().put(PASSWORD_CACHE_KEY, password); } + } + + @Override + public boolean supportsCredentialType(String credentialType) { + return CredentialModel.PASSWORD.equals(credentialType); + } + + @Override + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel)) return false; + UserCredentialModel cred = (UserCredentialModel)input; + UserAdapter adapter = getUserAdapter(user); + adapter.setPassword(cred.getValue()); + return true; } + public UserAdapter getUserAdapter(UserModel user) { + UserAdapter adapter = null; + if (user instanceof CachedUserModel) { + adapter = (UserAdapter)((CachedUserModel)user).getDelegateForUpdate(); + } else { + adapter = (UserAdapter)user; + } + return adapter; + } + + @Override + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + if (!supportsCredentialType(credentialType)) return; + + getUserAdapter(user).setPassword(null); + + } + + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + return supportsCredentialType(credentialType) && getPassword(user) != null; + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel)) return false; + UserCredentialModel cred = (UserCredentialModel)input; + String password = getPassword(user); + return password != null && password.equals(cred.getValue()); + } + + public String getPassword(UserModel user) { + String password = null; + if (user instanceof CachedUserModel) { + password = (String)((CachedUserModel)user).getCachedWith().get(PASSWORD_CACHE_KEY); + } else if (user instanceof UserAdapter) { + password = ((UserAdapter)user).getPassword(); + } + return password; + } + @Override public int getUsersCount(RealmModel realm) { Object count = em.createNamedQuery("getUserCount") diff --git a/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/EjbExampleUserStorageProviderFactory.java b/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/EjbExampleUserStorageProviderFactory.java index a1db65d1b8..1e16100478 100644 --- a/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/EjbExampleUserStorageProviderFactory.java +++ b/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/EjbExampleUserStorageProviderFactory.java @@ -16,6 +16,7 @@ */ package org.keycloak.examples.storage.user; +import org.jboss.logging.Logger; import org.keycloak.Config; import org.keycloak.component.ComponentModel; import org.keycloak.models.KeycloakSession; @@ -32,6 +33,7 @@ import java.util.List; * @version $Revision: 1 $ */ public class EjbExampleUserStorageProviderFactory implements UserStorageProviderFactory { + private static final Logger logger = Logger.getLogger(EjbExampleUserStorageProviderFactory.class); @Override @@ -56,4 +58,10 @@ public class EjbExampleUserStorageProviderFactory implements UserStorageProvider public String getHelpText() { return "JPA Example User Storage Provider"; } + + @Override + public void close() { + logger.info("<<<<<< Closing factory"); + + } } diff --git a/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/UserAdapter.java b/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/UserAdapter.java index 6276f7f842..8c8bcd6025 100644 --- a/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/UserAdapter.java +++ b/examples/providers/user-storage-jpa/src/main/java/org/keycloak/examples/storage/user/UserAdapter.java @@ -34,7 +34,7 @@ import java.util.Map; * @version $Revision: 1 $ */ public class UserAdapter extends AbstractUserAdapterFederatedStorage { - private static final Logger logger = Logger.getLogger(EjbExampleUserStorageProvider.class); + private static final Logger logger = Logger.getLogger(UserAdapter.class); protected UserEntity entity; protected String keycloakId; @@ -44,6 +44,14 @@ public class UserAdapter extends AbstractUserAdapterFederatedStorage { keycloakId = StorageId.keycloakId(model, entity.getId()); } + public String getPassword() { + return entity.getPassword(); + } + + public void setPassword(String password) { + entity.setPassword(password); + } + @Override public String getUsername() { return entity.getUsername(); @@ -70,26 +78,10 @@ public class UserAdapter extends AbstractUserAdapterFederatedStorage { return keycloakId; } - @Override - public void updateCredential(UserCredentialModel cred) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - entity.setPassword(cred.getValue()); - } else { - super.updateCredential(cred); - } - } - @Override public void setSingleAttribute(String name, String value) { if (name.equals("phone")) { entity.setPhone(value); - } else if (name.equals("password")) { - // ignore - - // having a "password" attribute is a workaround so that passwords can be cached. All done for performance reasons... - // If we override getCredentialsDirectly/updateCredentialsDirectly - // then the realm passsword policy will/may try and overwrite the plain text password with a hash. - // If you don't like this workaround, you can query the database every time to validate the password } else { super.setSingleAttribute(name, value); } @@ -99,13 +91,6 @@ public class UserAdapter extends AbstractUserAdapterFederatedStorage { public void removeAttribute(String name) { if (name.equals("phone")) { entity.setPhone(null); - } else if (name.equals("password")) { - // ignore - - // having a "password" attribute is a workaround so that passwords can be cached. All done for performance reasons... - // If we override getCredentialsDirectly/updateCredentialsDirectly - // then the realm passsword policy will/may try and overwrite the plain text password with a hash. - // If you don't like this workaround, you can query the database every time to validate the password } else { super.removeAttribute(name); } @@ -115,13 +100,6 @@ public class UserAdapter extends AbstractUserAdapterFederatedStorage { public void setAttribute(String name, List values) { if (name.equals("phone")) { entity.setPhone(values.get(0)); - } else if (name.equals("password")) { - // ignore - - // having a "password" attribute is a workaround so that passwords can be cached. All done for performance reasons... - // If we override getCredentialsDirectly/updateCredentialsDirectly - // then the realm passsword policy will/may try and overwrite the plain text password with a hash. - // If you don't like this workaround, you can query the database every time to validate the password } else { super.setAttribute(name, values); } @@ -131,12 +109,6 @@ public class UserAdapter extends AbstractUserAdapterFederatedStorage { public String getFirstAttribute(String name) { if (name.equals("phone")) { return entity.getPhone(); - } else if (name.equals("password")) { - // having a "password" attribute is a workaround so that passwords can be cached. All done for performance reasons... - // If we override getCredentialsDirectly/updateCredentialsDirectly - // then the realm passsword policy will/may try and overwrite the plain text password with a hash. - // If you don't like this workaround, you can query the database every time to validate the password - return entity.getPassword(); } else { return super.getFirstAttribute(name); } @@ -148,12 +120,6 @@ public class UserAdapter extends AbstractUserAdapterFederatedStorage { MultivaluedHashMap all = new MultivaluedHashMap<>(); all.putAll(attrs); all.add("phone", entity.getPhone()); - - // having a "password" attribute is a workaround so that passwords can be cached. All done for performance reasons... - // If we override getCredentialsDirectly/updateCredentialsDirectly - // then the realm passsword policy will/may try and overwrite the plain text password with a hash. - // If you don't like this workaround, you can query the database every time to validate the password - all.add("password", entity.getPassword()); return all; } diff --git a/examples/providers/user-storage-jpa/src/main/resources/META-INF/persistence.xml b/examples/providers/user-storage-jpa/src/main/resources/META-INF/persistence.xml index 9894af479e..51082e159c 100644 --- a/examples/providers/user-storage-jpa/src/main/resources/META-INF/persistence.xml +++ b/examples/providers/user-storage-jpa/src/main/resources/META-INF/persistence.xml @@ -4,7 +4,7 @@ xsi:schemaLocation=" http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> - + java:jboss/datasources/ExampleDS org.keycloak.examples.storage.user.UserEntity diff --git a/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java b/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java index e6cfae2495..2d0b4b2f20 100755 --- a/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java +++ b/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/KerberosFederationProvider.java @@ -26,11 +26,14 @@ import java.util.Map; import java.util.Set; import org.jboss.logging.Logger; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialModel; import org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator; import org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; +import org.keycloak.models.ModelReadOnlyException; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; @@ -40,6 +43,7 @@ import org.keycloak.models.UserFederationProviderModel; import org.keycloak.models.UserModel; import org.keycloak.common.constants.KerberosConstants; import org.keycloak.services.managers.UserManager; +import org.keycloak.storage.adapter.AbstractUserAdapter; /** * @author Marek Posolda @@ -142,31 +146,6 @@ public class KerberosFederationProvider implements UserFederationProvider { return kerberosPrincipal.equalsIgnoreCase(local.getFirstAttribute(KERBEROS_PRINCIPAL)); } - @Override - public Set getSupportedCredentialTypes(UserModel local) { - Set supportedCredTypes = new HashSet(); - supportedCredTypes.add(UserCredentialModel.KERBEROS); - - if (kerberosConfig.isAllowPasswordAuthentication()) { - boolean passwordSupported = true; - if (kerberosConfig.getEditMode() == EditMode.UNSYNCED ) { - - // Password from KC database has preference over kerberos password - for (UserCredentialValueModel cred : local.getCredentialsDirectly()) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - passwordSupported = false; - } - } - } - - if (passwordSupported) { - supportedCredTypes.add(UserCredentialModel.PASSWORD); - } - } - - return supportedCredTypes; - } - @Override public Set getSupportedCredentialTypes() { Set supportedCredTypes = new HashSet(); @@ -175,15 +154,37 @@ public class KerberosFederationProvider implements UserFederationProvider { } @Override - public boolean validCredentials(RealmModel realm, UserModel user, List input) { - for (UserCredentialModel cred : input) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - return validPassword(user.getUsername(), cred.getValue()); - } else { - return false; // invalid cred type - } + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + if (!(input instanceof UserCredentialModel) || !CredentialModel.PASSWORD.equals(input.getType())) return false; + if (kerberosConfig.getEditMode() == EditMode.READ_ONLY) { + throw new ModelReadOnlyException("Can't change password in Keycloak database. Change password with your Kerberos server"); + } + return false; + } + + @Override + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + + } + + @Override + public boolean supportsCredentialType(String credentialType) { + return credentialType.equals(CredentialModel.KERBEROS) || (kerberosConfig.isAllowPasswordAuthentication() && credentialType.equals(CredentialModel.PASSWORD)); + } + + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + return supportsCredentialType(credentialType); + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (!(input instanceof UserCredentialModel)) return false; + if (input.getType().equals(UserCredentialModel.PASSWORD) && !session.userCredentialManager().isConfiguredLocally(realm, user, UserCredentialModel.PASSWORD)) { + return validPassword(user.getUsername(), ((UserCredentialModel)input).getValue()); + } else { + return false; // invalid cred type } - return true; } protected boolean validPassword(String username, String password) { @@ -195,11 +196,6 @@ public class KerberosFederationProvider implements UserFederationProvider { } } - @Override - public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) { - return validCredentials(realm, user, Arrays.asList(input)); - } - @Override public CredentialValidationOutput validCredentials(RealmModel realm, UserCredentialModel credential) { if (credential.getType().equals(UserCredentialModel.KERBEROS)) { diff --git a/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/ReadOnlyKerberosUserModelDelegate.java b/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/ReadOnlyKerberosUserModelDelegate.java index 4cc4824b37..2a4e3b161f 100644 --- a/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/ReadOnlyKerberosUserModelDelegate.java +++ b/federation/kerberos/src/main/java/org/keycloak/federation/kerberos/ReadOnlyKerberosUserModelDelegate.java @@ -34,12 +34,4 @@ public class ReadOnlyKerberosUserModelDelegate extends UserModelDelegate { this.provider = provider; } - @Override - public void updateCredential(UserCredentialModel cred) { - if (provider.getSupportedCredentialTypes(delegate).contains(cred.getType())) { - throw new ModelReadOnlyException("Can't change password in Keycloak database. Change password with your Kerberos server"); - } - - delegate.updateCredential(cred); - } } diff --git a/federation/ldap/src/main/java/org/keycloak/federation/ldap/LDAPFederationProvider.java b/federation/ldap/src/main/java/org/keycloak/federation/ldap/LDAPFederationProvider.java index be103c3f2b..d16deaf5b6 100755 --- a/federation/ldap/src/main/java/org/keycloak/federation/ldap/LDAPFederationProvider.java +++ b/federation/ldap/src/main/java/org/keycloak/federation/ldap/LDAPFederationProvider.java @@ -18,6 +18,9 @@ package org.keycloak.federation.ldap; import org.jboss.logging.Logger; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialInputUpdater; +import org.keycloak.credential.CredentialModel; import org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator; import org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator; import org.keycloak.federation.ldap.idm.model.LDAPObject; @@ -28,12 +31,14 @@ import org.keycloak.federation.ldap.idm.store.ldap.LDAPIdentityStore; import org.keycloak.federation.ldap.kerberos.LDAPProviderKerberosConfig; import org.keycloak.federation.ldap.mappers.LDAPFederationMapper; import org.keycloak.federation.ldap.mappers.LDAPMappersComparator; +import org.keycloak.federation.ldap.mappers.PasswordUpdated; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.LDAPConstants; import org.keycloak.models.ModelDuplicateException; import org.keycloak.models.ModelException; +import org.keycloak.models.ModelReadOnlyException; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; @@ -73,6 +78,7 @@ public class LDAPFederationProvider implements UserFederationProvider { protected LDAPIdentityStore ldapIdentityStore; protected EditMode editMode; protected LDAPProviderKerberosConfig kerberosConfig; + protected PasswordUpdated updater; protected final Set supportedCredentialTypes = new HashSet<>(); @@ -90,6 +96,10 @@ public class LDAPFederationProvider implements UserFederationProvider { } } + public void setUpdater(PasswordUpdated updater) { + this.updater = updater; + } + public KeycloakSession getSession() { return session; } @@ -139,20 +149,6 @@ public class LDAPFederationProvider implements UserFederationProvider { return proxied; } - @Override - public Set getSupportedCredentialTypes(UserModel local) { - Set supportedCredentialTypes = new HashSet(this.supportedCredentialTypes); - if (editMode == EditMode.UNSYNCED ) { - for (UserCredentialValueModel cred : local.getCredentialsDirectly()) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - // User has changed password in KC local database. Use KC password instead of LDAP password - supportedCredentialTypes.remove(UserCredentialModel.PASSWORD); - } - } - } - return supportedCredentialTypes; - } - @Override public Set getSupportedCredentialTypes() { return new HashSet(this.supportedCredentialTypes); @@ -409,20 +405,47 @@ public class LDAPFederationProvider implements UserFederationProvider { @Override - public boolean validCredentials(RealmModel realm, UserModel user, List input) { - for (UserCredentialModel cred : input) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - return validPassword(realm, user, cred.getValue()); - } else { - return false; // invalid cred type - } + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + if (!CredentialModel.PASSWORD.equals(input.getType()) || ! (input instanceof UserCredentialModel)) return false; + if (editMode == EditMode.READ_ONLY) { + throw new ModelReadOnlyException("Federated storage is not writable"); + + } else if (editMode == EditMode.WRITABLE) { + LDAPIdentityStore ldapIdentityStore = getLdapIdentityStore(); + UserCredentialModel cred = (UserCredentialModel)input; + String password = cred.getValue(); + LDAPObject ldapUser = loadAndValidateUser(realm, user); + ldapIdentityStore.updatePassword(ldapUser, password); + if (updater != null) updater.passwordUpdated(user, ldapUser, input); + return true; + } else { + return false; } - return true; } @Override - public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) { - return validCredentials(realm, user, Arrays.asList(input)); + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + + } + + @Override + public boolean supportsCredentialType(String credentialType) { + return getSupportedCredentialTypes().contains(credentialType); + } + + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + return getSupportedCredentialTypes().contains(credentialType); + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (!(input instanceof UserCredentialModel)) return false; + if (input.getType().equals(UserCredentialModel.PASSWORD) && !session.userCredentialManager().isConfiguredLocally(realm, user, UserCredentialModel.PASSWORD)) { + return validPassword(realm, user, ((UserCredentialModel)input).getValue()); + } else { + return false; // invalid cred type + } } @Override diff --git a/federation/ldap/src/main/java/org/keycloak/federation/ldap/ReadonlyLDAPUserModelDelegate.java b/federation/ldap/src/main/java/org/keycloak/federation/ldap/ReadonlyLDAPUserModelDelegate.java index bfe3bcc597..c71b26aef6 100755 --- a/federation/ldap/src/main/java/org/keycloak/federation/ldap/ReadonlyLDAPUserModelDelegate.java +++ b/federation/ldap/src/main/java/org/keycloak/federation/ldap/ReadonlyLDAPUserModelDelegate.java @@ -50,14 +50,6 @@ public class ReadonlyLDAPUserModelDelegate extends UserModelDelegate implements throw new ModelReadOnlyException("Federated storage is not writable"); } - @Override - public void updateCredential(UserCredentialModel cred) { - if (provider.getSupportedCredentialTypes(delegate).contains(cred.getType())) { - throw new ModelReadOnlyException("Federated storage is not writable"); - } - delegate.updateCredential(cred); - } - @Override public void setEmail(String email) { throw new ModelReadOnlyException("Federated storage is not writable"); diff --git a/federation/ldap/src/main/java/org/keycloak/federation/ldap/WritableLDAPUserModelDelegate.java b/federation/ldap/src/main/java/org/keycloak/federation/ldap/WritableLDAPUserModelDelegate.java index 5a235f5fde..4644cd9f9b 100755 --- a/federation/ldap/src/main/java/org/keycloak/federation/ldap/WritableLDAPUserModelDelegate.java +++ b/federation/ldap/src/main/java/org/keycloak/federation/ldap/WritableLDAPUserModelDelegate.java @@ -40,20 +40,4 @@ public class WritableLDAPUserModelDelegate extends UserModelDelegate implements this.ldapObject = ldapObject; } - @Override - public void updateCredential(UserCredentialModel cred) { - if (!provider.getSupportedCredentialTypes(delegate).contains(cred.getType())) { - delegate.updateCredential(cred); - return; - } - - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - LDAPIdentityStore ldapIdentityStore = provider.getLdapIdentityStore(); - String password = cred.getValue(); - ldapIdentityStore.updatePassword(ldapObject, password); - } else { - logger.warnf("Don't know how to update credential of type [%s] for user [%s]", cred.getType(), delegate.getUsername()); - } - } - } diff --git a/server-spi/src/main/java/org/keycloak/storage/user/UserCredentialValidatorProvider.java b/federation/ldap/src/main/java/org/keycloak/federation/ldap/mappers/PasswordUpdated.java similarity index 67% rename from server-spi/src/main/java/org/keycloak/storage/user/UserCredentialValidatorProvider.java rename to federation/ldap/src/main/java/org/keycloak/federation/ldap/mappers/PasswordUpdated.java index 4c3d89790d..1ec5ad8e3c 100644 --- a/server-spi/src/main/java/org/keycloak/storage/user/UserCredentialValidatorProvider.java +++ b/federation/ldap/src/main/java/org/keycloak/federation/ldap/mappers/PasswordUpdated.java @@ -14,20 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.keycloak.storage.user; +package org.keycloak.federation.ldap.mappers; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.RealmModel; -import org.keycloak.models.UserCredentialModel; +import org.keycloak.credential.CredentialInput; +import org.keycloak.federation.ldap.idm.model.LDAPObject; import org.keycloak.models.UserModel; -import java.util.List; -import java.util.Set; - /** * @author Bill Burke * @version $Revision: 1 $ */ -public interface UserCredentialValidatorProvider { - boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List input); +public interface PasswordUpdated { + void passwordUpdated(UserModel user, LDAPObject ldapUser, CredentialInput input); } diff --git a/federation/ldap/src/main/java/org/keycloak/federation/ldap/mappers/msad/MSADUserAccountControlMapper.java b/federation/ldap/src/main/java/org/keycloak/federation/ldap/mappers/msad/MSADUserAccountControlMapper.java index 229ac87dd6..ba6139d23b 100644 --- a/federation/ldap/src/main/java/org/keycloak/federation/ldap/mappers/msad/MSADUserAccountControlMapper.java +++ b/federation/ldap/src/main/java/org/keycloak/federation/ldap/mappers/msad/MSADUserAccountControlMapper.java @@ -25,10 +25,12 @@ import java.util.regex.Pattern; import javax.naming.AuthenticationException; import org.jboss.logging.Logger; +import org.keycloak.credential.CredentialInput; import org.keycloak.federation.ldap.LDAPFederationProvider; import org.keycloak.federation.ldap.idm.model.LDAPObject; import org.keycloak.federation.ldap.idm.query.internal.LDAPQuery; import org.keycloak.federation.ldap.mappers.AbstractLDAPFederationMapper; +import org.keycloak.federation.ldap.mappers.PasswordUpdated; import org.keycloak.models.LDAPConstants; import org.keycloak.models.ModelException; import org.keycloak.models.RealmModel; @@ -44,7 +46,7 @@ import org.keycloak.models.utils.UserModelDelegate; * * @author Marek Posolda */ -public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { +public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper implements PasswordUpdated { private static final Logger logger = Logger.getLogger(MSADUserAccountControlMapper.class); @@ -53,6 +55,7 @@ public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { public MSADUserAccountControlMapper(UserFederationMapperModel mapperModel, LDAPFederationProvider ldapProvider, RealmModel realm) { super(mapperModel, ldapProvider, realm); + ldapProvider.setUpdater(this); } @Override @@ -68,6 +71,26 @@ public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { } } + @Override + public void passwordUpdated(UserModel user, LDAPObject ldapUser, CredentialInput input) { + logger.debugf("Going to update userAccountControl for ldap user '%s' after successful password update", ldapUser.getDn().toString()); + + // Normally it's read-only + ldapUser.removeReadOnlyAttributeName(LDAPConstants.PWD_LAST_SET); + + ldapUser.setSingleAttribute(LDAPConstants.PWD_LAST_SET, "-1"); + + UserAccountControl control = getUserAccountControl(ldapUser); + control.remove(UserAccountControl.PASSWD_NOTREQD); + control.remove(UserAccountControl.PASSWORD_EXPIRED); + + if (user.isEnabled()) { + control.remove(UserAccountControl.ACCOUNTDISABLE); + } + + updateUserAccountControl(ldapUser, control); + } + @Override public UserModel proxy(LDAPObject ldapUser, UserModel delegate) { return new MSADUserModelDelegate(delegate, ldapUser); @@ -135,6 +158,22 @@ public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { return e; } + protected UserAccountControl getUserAccountControl(LDAPObject ldapUser) { + String userAccountControl = ldapUser.getAttributeAsString(LDAPConstants.USER_ACCOUNT_CONTROL); + long longValue = userAccountControl == null ? 0 : Long.parseLong(userAccountControl); + return new UserAccountControl(longValue); + } + + // Update user in LDAP + protected void updateUserAccountControl(LDAPObject ldapUser, UserAccountControl accountControl) { + String userAccountControlValue = String.valueOf(accountControl.getValue()); + logger.debugf("Updating userAccountControl of user '%s' to value '%s'", ldapUser.getDn().toString(), userAccountControlValue); + + ldapUser.setSingleAttribute(LDAPConstants.USER_ACCOUNT_CONTROL, userAccountControlValue); + ldapProvider.getLdapIdentityStore().update(ldapUser); + } + + public class MSADUserModelDelegate extends UserModelDelegate { @@ -151,7 +190,7 @@ public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { if (getPwdLastSet() > 0) { // Merge KC and MSAD - return kcEnabled && !getUserAccountControl().has(UserAccountControl.ACCOUNTDISABLE); + return kcEnabled && !getUserAccountControl(ldapUser).has(UserAccountControl.ACCOUNTDISABLE); } else { // If new MSAD user is created and pwdLastSet is still 0, MSAD account is in disabled state. So read just from Keycloak DB. User is not able to login via MSAD anyway return kcEnabled; @@ -166,44 +205,14 @@ public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { if (ldapProvider.getEditMode() == UserFederationProvider.EditMode.WRITABLE && getPwdLastSet() > 0) { logger.debugf("Going to propagate enabled=%s for ldapUser '%s' to MSAD", enabled, ldapUser.getDn().toString()); - UserAccountControl control = getUserAccountControl(); + UserAccountControl control = getUserAccountControl(ldapUser); if (enabled) { control.remove(UserAccountControl.ACCOUNTDISABLE); } else { control.add(UserAccountControl.ACCOUNTDISABLE); } - updateUserAccountControl(control); - } - } - - @Override - public void updateCredential(UserCredentialModel cred) { - // Update LDAP password first - try { - super.updateCredential(cred); - } catch (ModelException me) { - me = processFailedPasswordUpdateException(me); - throw me; - } - - if (ldapProvider.getEditMode() == UserFederationProvider.EditMode.WRITABLE && cred.getType().equals(UserCredentialModel.PASSWORD)) { - logger.debugf("Going to update userAccountControl for ldap user '%s' after successful password update", ldapUser.getDn().toString()); - - // Normally it's read-only - ldapUser.removeReadOnlyAttributeName(LDAPConstants.PWD_LAST_SET); - - ldapUser.setSingleAttribute(LDAPConstants.PWD_LAST_SET, "-1"); - - UserAccountControl control = getUserAccountControl(); - control.remove(UserAccountControl.PASSWD_NOTREQD); - control.remove(UserAccountControl.PASSWORD_EXPIRED); - - if (super.isEnabled()) { - control.remove(UserAccountControl.ACCOUNTDISABLE); - } - - updateUserAccountControl(control); + updateUserAccountControl(ldapUser, control); } } @@ -243,7 +252,7 @@ public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { if (ldapProvider.getEditMode() == UserFederationProvider.EditMode.WRITABLE && RequiredAction.UPDATE_PASSWORD.toString().equals(action)) { // Don't set pwdLastSet in MSAD when it is new user - UserAccountControl accountControl = getUserAccountControl(); + UserAccountControl accountControl = getUserAccountControl(ldapUser); if (accountControl.getValue() != 0 && !accountControl.has(UserAccountControl.PASSWD_NOTREQD)) { logger.debugf("Going to remove required action UPDATE_PASSWORD from MSAD for ldap user '%s' ", ldapUser.getDn().toString()); @@ -261,7 +270,7 @@ public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { Set requiredActions = super.getRequiredActions(); if (ldapProvider.getEditMode() == UserFederationProvider.EditMode.WRITABLE) { - if (getPwdLastSet() == 0 || getUserAccountControl().has(UserAccountControl.PASSWORD_EXPIRED)) { + if (getPwdLastSet() == 0 || getUserAccountControl(ldapUser).has(UserAccountControl.PASSWORD_EXPIRED)) { requiredActions = new HashSet<>(requiredActions); requiredActions.add(RequiredAction.UPDATE_PASSWORD.toString()); return requiredActions; @@ -276,20 +285,7 @@ public class MSADUserAccountControlMapper extends AbstractLDAPFederationMapper { return pwdLastSet == null ? 0 : Long.parseLong(pwdLastSet); } - protected UserAccountControl getUserAccountControl() { - String userAccountControl = ldapUser.getAttributeAsString(LDAPConstants.USER_ACCOUNT_CONTROL); - long longValue = userAccountControl == null ? 0 : Long.parseLong(userAccountControl); - return new UserAccountControl(longValue); - } - // Update user in LDAP - protected void updateUserAccountControl(UserAccountControl accountControl) { - String userAccountControlValue = String.valueOf(accountControl.getValue()); - logger.debugf("Updating userAccountControl of user '%s' to value '%s'", ldapUser.getDn().toString(), userAccountControlValue); - - ldapUser.setSingleAttribute(LDAPConstants.USER_ACCOUNT_CONTROL, userAccountControlValue); - ldapProvider.getLdapIdentityStore().update(ldapUser); - } } } diff --git a/federation/sssd/src/main/java/org/keycloak/federation/sssd/ReadonlySSSDUserModelDelegate.java b/federation/sssd/src/main/java/org/keycloak/federation/sssd/ReadonlySSSDUserModelDelegate.java index 52061c9d18..75b6fd8f56 100755 --- a/federation/sssd/src/main/java/org/keycloak/federation/sssd/ReadonlySSSDUserModelDelegate.java +++ b/federation/sssd/src/main/java/org/keycloak/federation/sssd/ReadonlySSSDUserModelDelegate.java @@ -54,22 +54,6 @@ public class ReadonlySSSDUserModelDelegate extends UserModelDelegate implements throw new ModelReadOnlyException("Federated storage is not writable"); } - @Override - public void updateCredentialDirectly(UserCredentialValueModel cred) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - throw new IllegalStateException("Federated storage is not writable"); - } - super.updateCredentialDirectly(cred); - } - - @Override - public void updateCredential(UserCredentialModel cred) { - if (provider.getSupportedCredentialTypes(delegate).contains(cred.getType())) { - throw new ModelReadOnlyException("Federated storage is not writable"); - } - delegate.updateCredential(cred); - } - @Override public void setEmail(String email) { throw new ModelReadOnlyException("Federated storage is not writable"); diff --git a/federation/sssd/src/main/java/org/keycloak/federation/sssd/SSSDFederationProvider.java b/federation/sssd/src/main/java/org/keycloak/federation/sssd/SSSDFederationProvider.java index a9089ec0b1..ba47871b51 100755 --- a/federation/sssd/src/main/java/org/keycloak/federation/sssd/SSSDFederationProvider.java +++ b/federation/sssd/src/main/java/org/keycloak/federation/sssd/SSSDFederationProvider.java @@ -19,11 +19,14 @@ package org.keycloak.federation.sssd; import org.freedesktop.dbus.Variant; import org.jboss.logging.Logger; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialModel; import org.keycloak.federation.sssd.api.Sssd; import org.keycloak.federation.sssd.impl.PAMAuthenticator; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; +import org.keycloak.models.ModelReadOnlyException; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; @@ -162,30 +165,39 @@ public class SSSDFederationProvider implements UserFederationProvider { return Sssd.getRawAttribute(attributes.get("mail")).equalsIgnoreCase(local.getEmail()); } - @Override - public Set getSupportedCredentialTypes(UserModel user) { - return supportedCredentialTypes; - } - @Override public Set getSupportedCredentialTypes() { return supportedCredentialTypes; } @Override - public boolean validCredentials(RealmModel realm, UserModel user, List input) { - for (UserCredentialModel cred : input) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - PAMAuthenticator pam = factory.createPAMAuthenticator(user.getUsername(), cred.getValue()); - return (pam.authenticate() != null); - } - } - return false; + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + if (!(input instanceof UserCredentialModel) || !CredentialModel.PASSWORD.equals(input.getType())) return false; + throw new ModelReadOnlyException("Federated storage is not writable"); } @Override - public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) { - return validCredentials(realm, user, Arrays.asList(input)); + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + + } + + @Override + public boolean supportsCredentialType(String credentialType) { + return CredentialModel.PASSWORD.equals(credentialType); + } + + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + return CredentialModel.PASSWORD.equals(credentialType); + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel)) return false; + + UserCredentialModel cred = (UserCredentialModel)input; + PAMAuthenticator pam = factory.createPAMAuthenticator(user.getUsername(), cred.getValue()); + return (pam.authenticate() != null); } @Override diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java index ea6698cf83..002761ea29 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java @@ -60,12 +60,14 @@ public class UserAdapter implements CachedUserModel { this.realm = realm; } - protected void getDelegateForUpdate() { + @Override + public UserModel getDelegateForUpdate() { if (updated == null) { userProviderCache.registerUserInvalidation(realm, cached); updated = userProviderCache.getDelegate().getUserById(getId(), realm); if (updated == null) throw new IllegalStateException("Not found in database"); } + return updated; } @Override @@ -119,12 +121,6 @@ public class UserAdapter implements CachedUserModel { return cached.isEnabled(); } - @Override - public boolean isOtpEnabled() { - if (updated != null) return updated.isOtpEnabled(); - return cached.isTotp(); - } - @Override public void setEnabled(boolean enabled) { getDelegateForUpdate(); @@ -247,30 +243,6 @@ public class UserAdapter implements CachedUserModel { updated.setEmailVerified(verified); } - @Override - public void setOtpEnabled(boolean totp) { - getDelegateForUpdate(); - updated.setOtpEnabled(totp); - } - - @Override - public void updateCredential(UserCredentialModel cred) { - getDelegateForUpdate(); - updated.updateCredential(cred); - } - - @Override - public List getCredentialsDirectly() { - if (updated != null) return updated.getCredentialsDirectly(); - return cached.getCredentials(); - } - - @Override - public void updateCredentialDirectly(UserCredentialValueModel cred) { - getDelegateForUpdate(); - updated.updateCredentialDirectly(cred); - } - @Override public String getFederationLink() { if (updated != null) return updated.getFederationLink(); diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java index b38d9aab1b..73007680a6 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java @@ -168,21 +168,22 @@ public class UserCacheSession implements UserCache { } CachedUser cached = cache.get(id, CachedUser.class); + UserModel delegate = null; boolean wasCached = cached != null; if (cached == null) { logger.trace("not cached"); Long loaded = cache.getCurrentRevision(id); - UserModel model = getDelegate().getUserById(id, realm); - if (model == null) { + delegate = getDelegate().getUserById(id, realm); + if (delegate == null) { logger.trace("delegate returning null"); return null; } - cached = new CachedUser(loaded, realm, model); + cached = new CachedUser(loaded, realm, delegate); cache.addRevisioned(cached, startupRevision); } logger.trace("returning new cache adapter"); UserAdapter adapter = new UserAdapter(cached, this, session, realm); - if (!wasCached) onCache(realm, adapter); + if (!wasCached) onCache(realm, adapter, delegate); managedUsers.put(id, adapter); return adapter; } @@ -251,24 +252,24 @@ public class UserCacheSession implements UserCache { } } - protected UserAdapter getUserAdapter(RealmModel realm, String userId, Long loaded, UserModel model) { + protected UserAdapter getUserAdapter(RealmModel realm, String userId, Long loaded, UserModel delegate) { CachedUser cached = cache.get(userId, CachedUser.class); boolean wasCached = cached != null; if (cached == null) { - cached = new CachedUser(loaded, realm, model); + cached = new CachedUser(loaded, realm, delegate); cache.addRevisioned(cached, startupRevision); } UserAdapter adapter = new UserAdapter(cached, this, session, realm); if (!wasCached) { - onCache(realm, adapter); + onCache(realm, adapter, delegate); } return adapter; } - private void onCache(RealmModel realm, UserAdapter adapter) { - ((OnUserCache)getDelegate()).onCache(realm, adapter); - ((OnUserCache)session.userCredentialManager()).onCache(realm, adapter); + private void onCache(RealmModel realm, UserAdapter adapter, UserModel delegate) { + ((OnUserCache)getDelegate()).onCache(realm, adapter, delegate); + ((OnUserCache)session.userCredentialManager()).onCache(realm, adapter, delegate); } @Override @@ -627,16 +628,6 @@ public class UserCacheSession implements UserCache { return getDelegate().removeFederatedIdentity(realm, user, socialProvider); } - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List input) { - return getDelegate().validCredentials(session, realm, user, input); - } - - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, UserCredentialModel... input) { - return getDelegate().validCredentials(session, realm, user, input); - } - @Override public CredentialValidationOutput validCredentials(KeycloakSession session, RealmModel realm, UserCredentialModel... input) { return getDelegate().validCredentials(session, realm, input); diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedUser.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedUser.java index 7c24594885..bc92c482e9 100755 --- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedUser.java +++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedUser.java @@ -44,9 +44,7 @@ public class CachedUser extends AbstractExtendableRevisioned implements InRealm private String lastName; private String email; private boolean emailVerified; - private List credentials = new LinkedList<>(); private boolean enabled; - private boolean totp; private String federationLink; private String serviceAccountClientLink; private MultivaluedHashMap attributes = new MultivaluedHashMap<>(); @@ -66,9 +64,7 @@ public class CachedUser extends AbstractExtendableRevisioned implements InRealm this.attributes.putAll(user.getAttributes()); this.email = user.getEmail(); this.emailVerified = user.isEmailVerified(); - this.credentials.addAll(user.getCredentialsDirectly()); this.enabled = user.isEnabled(); - this.totp = user.isOtpEnabled(); this.federationLink = user.getFederationLink(); this.serviceAccountClientLink = user.getServiceAccountClientLink(); this.requiredActions.addAll(user.getRequiredActions()); @@ -111,18 +107,10 @@ public class CachedUser extends AbstractExtendableRevisioned implements InRealm return emailVerified; } - public List getCredentials() { - return credentials; - } - public boolean isEnabled() { return enabled; } - public boolean isTotp() { - return totp; - } - public MultivaluedHashMap getAttributes() { return attributes; } diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java index d44c6fe171..51b41530d1 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java @@ -710,16 +710,6 @@ public class JpaUserProvider implements UserProvider, UserCredentialStore { return (entity != null) ? new FederatedIdentityModel(entity.getIdentityProvider(), entity.getUserId(), entity.getUserName(), entity.getToken()) : null; } - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List input) { - return CredentialValidation.validCredentials(session, realm, user, input); - } - - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, UserCredentialModel... input) { - return CredentialValidation.validCredentials(session, realm, user, input); - } - @Override public CredentialValidationOutput validCredentials(KeycloakSession session, RealmModel realm, UserCredentialModel... input) { // Not supported yet @@ -803,7 +793,7 @@ public class JpaUserProvider implements UserProvider, UserCredentialStore { entity.setUser(userRef); em.persist(entity); MultivaluedHashMap config = cred.getConfig(); - if (config != null || !config.isEmpty()) { + if (config != null && !config.isEmpty()) { for (String key : config.keySet()) { List values = config.getList(key); @@ -850,6 +840,7 @@ public class JpaUserProvider implements UserProvider, UserCredentialStore { model.setCreatedDate(entity.getCreatedDate()); model.setDevice(entity.getDevice()); model.setDigits(entity.getDigits()); + model.setHashIterations(entity.getHashIterations()); MultivaluedHashMap config = new MultivaluedHashMap<>(); model.setConfig(config); for (CredentialAttributeEntity attr : entity.getCredentialAttributes()) { diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/UserAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/UserAdapter.java index 49bcac633b..7e0174670a 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/UserAdapter.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/UserAdapter.java @@ -113,11 +113,6 @@ public class UserAdapter implements UserModel, JpaModel { return user.isEnabled(); } - @Override - public boolean isOtpEnabled() { - return user.isTotp(); - } - @Override public void setEnabled(boolean enabled) { user.setEnabled(enabled); @@ -310,204 +305,6 @@ public class UserAdapter implements UserModel, JpaModel { user.setEmailVerified(verified); } - @Override - public void setOtpEnabled(boolean totp) { - user.setTotp(totp); - } - - @Override - public void updateCredential(UserCredentialModel cred) { - - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - updatePasswordCredential(cred); - } else if (UserCredentialModel.isOtp(cred.getType())){ - updateOtpCredential(cred); - - } else { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - credentialEntity.setValue(cred.getValue()); - em.persist(credentialEntity); - user.getCredentials().add(credentialEntity); - } else { - credentialEntity.setValue(cred.getValue()); - } - } - em.flush(); - } - - private void updateOtpCredential(UserCredentialModel cred) { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - - credentialEntity.setValue(cred.getValue()); - OTPPolicy otpPolicy = realm.getOTPPolicy(); - credentialEntity.setAlgorithm(otpPolicy.getAlgorithm()); - credentialEntity.setDigits(otpPolicy.getDigits()); - credentialEntity.setCounter(otpPolicy.getInitialCounter()); - credentialEntity.setPeriod(otpPolicy.getPeriod()); - em.persist(credentialEntity); - user.getCredentials().add(credentialEntity); - } else { - OTPPolicy policy = realm.getOTPPolicy(); - credentialEntity.setDigits(policy.getDigits()); - credentialEntity.setCounter(policy.getInitialCounter()); - credentialEntity.setAlgorithm(policy.getAlgorithm()); - credentialEntity.setValue(cred.getValue()); - credentialEntity.setPeriod(policy.getPeriod()); - } - } - - - - - private void updatePasswordCredential(UserCredentialModel cred) { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - setValue(credentialEntity, cred); - em.persist(credentialEntity); - user.getCredentials().add(credentialEntity); - } else { - - int expiredPasswordsPolicyValue = -1; - PasswordPolicy policy = realm.getPasswordPolicy(); - if(policy != null) { - expiredPasswordsPolicyValue = policy.getExpiredPasswords(); - } - - if (expiredPasswordsPolicyValue != -1) { - user.getCredentials().remove(credentialEntity); - credentialEntity.setType(UserCredentialModel.PASSWORD_HISTORY); - user.getCredentials().add(credentialEntity); - - List credentialEntities = getCredentialEntities(user, UserCredentialModel.PASSWORD_HISTORY); - if (credentialEntities.size() > expiredPasswordsPolicyValue - 1) { - user.getCredentials().removeAll(credentialEntities.subList(expiredPasswordsPolicyValue - 1, credentialEntities.size())); - } - - credentialEntity = setCredentials(user, cred); - setValue(credentialEntity, cred); - em.persist(credentialEntity); - user.getCredentials().add(credentialEntity); - } else { - List credentialEntities = getCredentialEntities(user, UserCredentialModel.PASSWORD_HISTORY); - if (credentialEntities != null && credentialEntities.size() > 0) { - user.getCredentials().removeAll(credentialEntities); - } - setValue(credentialEntity, cred); - } - } - } - - private CredentialEntity setCredentials(UserEntity user, UserCredentialModel cred) { - CredentialEntity credentialEntity = new CredentialEntity(); - credentialEntity.setId(KeycloakModelUtils.generateId()); - credentialEntity.setType(cred.getType()); - credentialEntity.setDevice(cred.getDevice()); - credentialEntity.setUser(user); - return credentialEntity; - } - - private void setValue(CredentialEntity credentialEntity, UserCredentialModel cred) { - UserCredentialValueModel encoded = PasswordHashManager.encode(session, realm, cred.getValue()); - credentialEntity.setCreatedDate(Time.toMillis(Time.currentTime())); - credentialEntity.setAlgorithm(encoded.getAlgorithm()); - credentialEntity.setValue(encoded.getValue()); - credentialEntity.setSalt(encoded.getSalt()); - credentialEntity.setHashIterations(encoded.getHashIterations()); - } - - private CredentialEntity getCredentialEntity(UserEntity userEntity, String credType) { - for (CredentialEntity entity : userEntity.getCredentials()) { - if (entity.getType().equals(credType)) { - return entity; - } - } - - return null; - } - - private List getCredentialEntities(UserEntity userEntity, String credType) { - List credentialEntities = new ArrayList(); - for (CredentialEntity entity : userEntity.getCredentials()) { - if (entity.getType().equals(credType)) { - credentialEntities.add(entity); - } - } - - // Avoiding direct use of credSecond.getCreatedDate() - credFirst.getCreatedDate() to prevent Integer Overflow - // Orders from most recent to least recent - Collections.sort(credentialEntities, new Comparator() { - public int compare(CredentialEntity credFirst, CredentialEntity credSecond) { - if (credFirst.getCreatedDate() > credSecond.getCreatedDate()) { - return -1; - } else if (credFirst.getCreatedDate() < credSecond.getCreatedDate()) { - return 1; - } else { - return 0; - } - } - }); - return credentialEntities; - } - - @Override - public List getCredentialsDirectly() { - List credentials = new ArrayList<>(user.getCredentials()); - List result = new ArrayList<>(); - - for (CredentialEntity credEntity : credentials) { - UserCredentialValueModel credModel = new UserCredentialValueModel(); - credModel.setType(credEntity.getType()); - credModel.setDevice(credEntity.getDevice()); - credModel.setValue(credEntity.getValue()); - credModel.setCreatedDate(credEntity.getCreatedDate()); - credModel.setSalt(credEntity.getSalt()); - credModel.setHashIterations(credEntity.getHashIterations()); - credModel.setCounter(credEntity.getCounter()); - credModel.setAlgorithm(credEntity.getAlgorithm()); - credModel.setDigits(credEntity.getDigits()); - credModel.setPeriod(credEntity.getPeriod()); - - result.add(credModel); - } - - return result; - } - - @Override - public void updateCredentialDirectly(UserCredentialValueModel credModel) { - CredentialEntity credentialEntity = getCredentialEntity(user, credModel.getType()); - - if (credentialEntity == null) { - credentialEntity = new CredentialEntity(); - credentialEntity.setId(KeycloakModelUtils.generateId()); - credentialEntity.setType(credModel.getType()); - credentialEntity.setCreatedDate(credModel.getCreatedDate()); - credentialEntity.setUser(user); - em.persist(credentialEntity); - user.getCredentials().add(credentialEntity); - } - - credentialEntity.setValue(credModel.getValue()); - credentialEntity.setSalt(credModel.getSalt()); - credentialEntity.setDevice(credModel.getDevice()); - credentialEntity.setHashIterations(credModel.getHashIterations()); - credentialEntity.setCounter(credModel.getCounter()); - credentialEntity.setAlgorithm(credModel.getAlgorithm()); - credentialEntity.setDigits(credModel.getDigits()); - credentialEntity.setPeriod(credModel.getPeriod()); - - em.flush(); - } - - @Override public Set getGroups() { // we query ids only as the group might be cached and following the @ManyToOne will result in a load diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserEntity.java b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserEntity.java index d110a17eb3..2af7673fb7 100755 --- a/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserEntity.java +++ b/model/jpa/src/main/java/org/keycloak/models/jpa/entities/UserEntity.java @@ -76,8 +76,6 @@ public class UserEntity { protected String email; @Column(name = "ENABLED") protected boolean enabled; - @Column(name = "TOTP") - protected boolean totp; @Column(name = "EMAIL_VERIFIED") protected boolean emailVerified; @@ -168,14 +166,6 @@ public class UserEntity { this.emailConstraint = emailConstraint; } - public boolean isTotp() { - return totp; - } - - public void setTotp(boolean totp) { - this.totp = totp; - } - public boolean isEmailVerified() { return emailVerified; } diff --git a/model/jpa/src/main/java/org/keycloak/storage/jpa/JpaUserFederatedStorageProvider.java b/model/jpa/src/main/java/org/keycloak/storage/jpa/JpaUserFederatedStorageProvider.java index 1c72da0744..090674b4b2 100644 --- a/model/jpa/src/main/java/org/keycloak/storage/jpa/JpaUserFederatedStorageProvider.java +++ b/model/jpa/src/main/java/org/keycloak/storage/jpa/JpaUserFederatedStorageProvider.java @@ -47,6 +47,7 @@ import org.keycloak.storage.federated.UserGroupMembershipFederatedStorage; import org.keycloak.storage.federated.UserRequiredActionsFederatedStorage; import org.keycloak.storage.federated.UserRoleMappingsFederatedStorage; import org.keycloak.storage.jpa.entity.BrokerLinkEntity; +import org.keycloak.storage.jpa.entity.FederatedUser; import org.keycloak.storage.jpa.entity.FederatedUserAttributeEntity; import org.keycloak.storage.jpa.entity.FederatedUserConsentEntity; import org.keycloak.storage.jpa.entity.FederatedUserConsentProtocolMapperEntity; @@ -95,9 +96,24 @@ public class JpaUserFederatedStorageProvider implements } + /** + * We create an entry so that its easy to iterate over all things in the database. Specifically useful for export + * + */ + protected void createIndex(RealmModel realm, UserModel user) { + if (em.find(FederatedUser.class, user.getId()) == null) { + FederatedUser fedUser = new FederatedUser(); + fedUser.setId(user.getId()); + fedUser.setRealmId(realm.getId()); + fedUser.setStorageProviderId(StorageId.resolveProviderId(user)); + em.persist(fedUser); + } + } + @Override public void setAttribute(RealmModel realm, UserModel user, String name, List values) { + createIndex(realm, user); deleteAttribute(realm, user, name); em.flush(); for (String value : values) { @@ -126,6 +142,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void setSingleAttribute(RealmModel realm, UserModel user, String name, String value) { + createIndex(realm, user); deleteAttribute(realm, user, name); em.flush(); persistAttributeValue(realm, user, name, value); @@ -133,6 +150,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void removeAttribute(RealmModel realm, UserModel user, String name) { + // createIndex(realm, user); don't need to create an index for removal deleteAttribute(realm, user, name); em.flush(); } @@ -180,6 +198,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel link) { + createIndex(realm, user); BrokerLinkEntity entity = new BrokerLinkEntity(); entity.setRealmId(realm.getId()); entity.setUserId(user.getId()); @@ -211,6 +230,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void updateFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel model) { + createIndex(realm, user); BrokerLinkEntity entity = getBrokerLinkEntity(realm, user, model.getIdentityProvider()); if (entity == null) return; entity.setBrokerUserName(model.getUserName()); @@ -243,6 +263,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void addConsent(RealmModel realm, UserModel user, UserConsentModel consent) { + createIndex(realm, user); String clientId = consent.getClient().getId(); FederatedUserConsentEntity consentEntity = getGrantedConsentEntity(user, clientId); @@ -285,6 +306,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void updateConsent(RealmModel realm, UserModel user, UserConsentModel consent) { + createIndex(realm, user); String clientId = consent.getClient().getId(); FederatedUserConsentEntity consentEntity = getGrantedConsentEntity(user, clientId); @@ -432,12 +454,14 @@ public class JpaUserFederatedStorageProvider implements @Override public void updateCredential(RealmModel realm, UserModel user, UserCredentialModel cred) { + createIndex(realm, user); FederatedCredentials.updateCredential(session, this, realm, user, cred); } @Override public void updateCredential(RealmModel realm, UserModel user, UserCredentialValueModel cred) { + createIndex(realm, user); FederatedUserCredentialEntity entity = null; if (cred.getId() != null) entity = em.find(FederatedUserCredentialEntity.class, cred.getId()); boolean newEntity = false; @@ -490,6 +514,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void joinGroup(RealmModel realm, UserModel user, GroupModel group) { if (isMemberOf(realm, user, group)) return; + createIndex(realm, user); FederatedUserGroupMembershipEntity entity = new FederatedUserGroupMembershipEntity(); entity.setUserId(user.getId()); entity.setStorageProviderId(StorageId.resolveProviderId(user)); @@ -553,6 +578,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void addRequiredAction(RealmModel realm, UserModel user, String action) { + createIndex(realm, user); if (user.getRequiredActions().contains(action)) return; FederatedUserRequiredActionEntity entity = new FederatedUserRequiredActionEntity(); entity.setUserId(user.getId()); @@ -576,6 +602,7 @@ public class JpaUserFederatedStorageProvider implements @Override public void grantRole(RealmModel realm, UserModel user, RoleModel role) { if (user.hasRole(role)) return; + createIndex(realm, user); FederatedUserRoleMappingEntity entity = new FederatedUserRoleMappingEntity(); entity.setUserId(user.getId()); entity.setStorageProviderId(StorageId.resolveProviderId(user)); @@ -645,6 +672,7 @@ public class JpaUserFederatedStorageProvider implements public void updateCredential(RealmModel realm, UserModel user, CredentialModel cred) { FederatedUserCredentialEntity entity = em.find(FederatedUserCredentialEntity.class, cred.getId()); if (entity == null) return; + createIndex(realm, user); entity.setAlgorithm(cred.getAlgorithm()); entity.setCounter(cred.getCounter()); entity.setCreatedDate(cred.getCreatedDate()); @@ -696,6 +724,7 @@ public class JpaUserFederatedStorageProvider implements @Override public CredentialModel createCredential(RealmModel realm, UserModel user, CredentialModel cred) { + createIndex(realm, user); FederatedUserCredentialEntity entity = new FederatedUserCredentialEntity(); String id = cred.getId() == null ? KeycloakModelUtils.generateId() : cred.getId(); entity.setId(id); @@ -714,7 +743,7 @@ public class JpaUserFederatedStorageProvider implements entity.setStorageProviderId(StorageId.resolveProviderId(user)); em.persist(entity); MultivaluedHashMap config = cred.getConfig(); - if (config != null || !config.isEmpty()) { + if (config != null && !config.isEmpty()) { for (String key : config.keySet()) { List values = config.getList(key); @@ -761,6 +790,7 @@ public class JpaUserFederatedStorageProvider implements model.setCreatedDate(entity.getCreatedDate()); model.setDevice(entity.getDevice()); model.setDigits(entity.getDigits()); + model.setHashIterations(entity.getHashIterations()); MultivaluedHashMap config = new MultivaluedHashMap<>(); model.setConfig(config); for (FederatedUserCredentialAttributeEntity attr : entity.getCredentialAttributes()) { @@ -805,6 +835,15 @@ public class JpaUserFederatedStorageProvider implements return toModel(results.get(0)); } + @Override + public List getStoredUsers(RealmModel realm, int first, int max) { + TypedQuery query = em.createNamedQuery("getFederatedUserIds", String.class) + .setParameter("realmId", realm.getId()) + .setFirstResult(first) + .setMaxResults(max); + return query.getResultList(); + } + @Override public void preRemove(RealmModel realm) { int num = em.createNamedQuery("deleteFederatedUserConsentRolesByRealm") @@ -827,6 +866,8 @@ public class JpaUserFederatedStorageProvider implements .setParameter("realmId", realm.getId()).executeUpdate(); num = em.createNamedQuery("deleteFederatedUserGroupMembershipByRealm") .setParameter("realmId", realm.getId()).executeUpdate(); + num = em.createNamedQuery("deleteFederatedUsersByRealm") + .setParameter("realmId", realm.getId()).executeUpdate(); } @Override @@ -855,6 +896,10 @@ public class JpaUserFederatedStorageProvider implements .setParameter("realmId", realm.getId()) .setParameter("link", link.getId()) .executeUpdate(); + num = em.createNamedQuery("deleteFederatedUsersByRealmAndLink") + .setParameter("realmId", realm.getId()) + .setParameter("link", link.getId()) + .executeUpdate(); } @Override @@ -924,6 +969,10 @@ public class JpaUserFederatedStorageProvider implements .setParameter("userId", user.getId()) .setParameter("realmId", realm.getId()) .executeUpdate(); + em.createNamedQuery("deleteFederatedUserByUser") + .setParameter("userId", user.getId()) + .setParameter("realmId", realm.getId()) + .executeUpdate(); } @@ -961,6 +1010,9 @@ public class JpaUserFederatedStorageProvider implements em.createNamedQuery("deleteFederatedUserRoleMappingsByStorageProvider") .setParameter("storageProviderId", model.getId()) .executeUpdate(); + em.createNamedQuery("deleteFederatedUsersByStorageProvider") + .setParameter("storageProviderId", model.getId()) + .executeUpdate(); } } diff --git a/model/jpa/src/main/java/org/keycloak/storage/jpa/entity/FederatedUser.java b/model/jpa/src/main/java/org/keycloak/storage/jpa/entity/FederatedUser.java new file mode 100644 index 0000000000..c4ace99fed --- /dev/null +++ b/model/jpa/src/main/java/org/keycloak/storage/jpa/entity/FederatedUser.java @@ -0,0 +1,85 @@ +/* + * Copyright 2016 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.storage.jpa.entity; + +import org.keycloak.models.jpa.entities.UserAttributeEntity; + +import javax.persistence.Access; +import javax.persistence.AccessType; +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.Table; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +@NamedQueries({ + @NamedQuery(name="getFederatedUserIds", query="select f.id from FederatedUser f where f.realmId=:realmId"), + @NamedQuery(name="deleteFederatedUserByUser", query="delete from FederatedUser f where f.id = :userId and f.realmId=:realmId"), + @NamedQuery(name="deleteFederatedUsersByRealm", query="delete from FederatedUser f where f.realmId=:realmId"), + @NamedQuery(name="deleteFederatedUsersByStorageProvider", query="delete from FederatedUser f where f.storageProviderId=:storageProviderId"), + @NamedQuery(name="deleteFederatedUsersByRealmAndLink", query="delete from FederatedUser f where f.id IN (select u.id from UserEntity u where u.realmId=:realmId and u.federationLink=:link)") +}) +@Entity +@Table(name="FEDERATED_USER") +public class FederatedUser { + + @Id + @Column(name="ID") + @Access(AccessType.PROPERTY) // we do this because relationships often fetch id, but not entity. This avoids an extra SQL + protected String id; + + @Column(name = "REALM_ID") + protected String realmId; + + @Column(name = "STORAGE_PROVIDER_ID") + protected String storageProviderId; + + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getRealmId() { + return realmId; + } + + public void setRealmId(String realmId) { + this.realmId = realmId; + } + + public String getStorageProviderId() { + return storageProviderId; + } + + public void setStorageProviderId(String storageProviderId) { + this.storageProviderId = storageProviderId; + } +} diff --git a/model/jpa/src/main/resources/META-INF/jpa-changelog-2.3.0.xml b/model/jpa/src/main/resources/META-INF/jpa-changelog-2.3.0.xml new file mode 100755 index 0000000000..6a3f9feb73 --- /dev/null +++ b/model/jpa/src/main/resources/META-INF/jpa-changelog-2.3.0.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml b/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml index 55a52b60cb..8990fc438c 100755 --- a/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml +++ b/model/jpa/src/main/resources/META-INF/jpa-changelog-master.xml @@ -36,4 +36,5 @@ + diff --git a/model/jpa/src/main/resources/META-INF/persistence.xml b/model/jpa/src/main/resources/META-INF/persistence.xml index 6288fe5e2a..c93a440421 100755 --- a/model/jpa/src/main/resources/META-INF/persistence.xml +++ b/model/jpa/src/main/resources/META-INF/persistence.xml @@ -70,6 +70,7 @@ org.keycloak.storage.jpa.entity.BrokerLinkEntity + org.keycloak.storage.jpa.entity.FederatedUser org.keycloak.storage.jpa.entity.FederatedUserAttributeEntity org.keycloak.storage.jpa.entity.FederatedUserConsentEntity org.keycloak.storage.jpa.entity.FederatedUserConsentRoleEntity diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java index 9ad2c1ea36..87c64873e0 100755 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/MongoUserProvider.java @@ -513,16 +513,6 @@ public class MongoUserProvider implements UserProvider { getMongoStore().updateEntities(MongoUserConsentEntity.class, query, pull, invocationContext); } - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List input) { - return CredentialValidation.validCredentials(session, realm, user, input); - } - - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, UserCredentialModel... input) { - return CredentialValidation.validCredentials(session, realm, user, input); - } - @Override public CredentialValidationOutput validCredentials(KeycloakSession session, RealmModel realm, UserCredentialModel... input) { // Not supported yet diff --git a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java index b89ab0102a..f642ef14f7 100755 --- a/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java +++ b/model/mongo/src/main/java/org/keycloak/models/mongo/keycloak/adapters/UserAdapter.java @@ -243,216 +243,6 @@ public class UserAdapter extends AbstractMongoAdapter implement getMongoStore().pullItemFromList(user, "requiredActions", actionName, invocationContext); } - @Override - public boolean isOtpEnabled() { - return user.isTotp(); - } - - @Override - public void setOtpEnabled(boolean totp) { - user.setTotp(totp); - updateUser(); - } - - @Override - public void updateCredential(UserCredentialModel cred) { - - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - updatePasswordCredential(cred); - } else if (UserCredentialModel.isOtp(cred.getType())){ - updateOtpCredential(cred); - } else { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - credentialEntity.setValue(cred.getValue()); - user.getCredentials().add(credentialEntity); - } else { - credentialEntity.setValue(cred.getValue()); - } - } - getMongoStore().updateEntity(user, invocationContext); - } - - private void updateOtpCredential(UserCredentialModel cred) { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - credentialEntity.setValue(cred.getValue()); - OTPPolicy otpPolicy = realm.getOTPPolicy(); - credentialEntity.setAlgorithm(otpPolicy.getAlgorithm()); - credentialEntity.setDigits(otpPolicy.getDigits()); - credentialEntity.setCounter(otpPolicy.getInitialCounter()); - credentialEntity.setPeriod(otpPolicy.getPeriod()); - user.getCredentials().add(credentialEntity); - } else { - credentialEntity.setValue(cred.getValue()); - OTPPolicy policy = realm.getOTPPolicy(); - credentialEntity.setDigits(policy.getDigits()); - credentialEntity.setCounter(policy.getInitialCounter()); - credentialEntity.setAlgorithm(policy.getAlgorithm()); - credentialEntity.setPeriod(policy.getPeriod()); - } - } - - - private void updatePasswordCredential(UserCredentialModel cred) { - CredentialEntity credentialEntity = getCredentialEntity(user, cred.getType()); - - if (credentialEntity == null) { - credentialEntity = setCredentials(user, cred); - setValue(credentialEntity, cred); - user.getCredentials().add(credentialEntity); - } else { - - int expiredPasswordsPolicyValue = -1; - PasswordPolicy policy = realm.getPasswordPolicy(); - if(policy != null) { - expiredPasswordsPolicyValue = policy.getExpiredPasswords(); - } - - if (expiredPasswordsPolicyValue != -1) { - user.getCredentials().remove(credentialEntity); - credentialEntity.setType(UserCredentialModel.PASSWORD_HISTORY); - user.getCredentials().add(credentialEntity); - - List credentialEntities = getCredentialEntities(user, UserCredentialModel.PASSWORD_HISTORY); - if (credentialEntities.size() > expiredPasswordsPolicyValue - 1) { - user.getCredentials().removeAll(credentialEntities.subList(expiredPasswordsPolicyValue - 1, credentialEntities.size())); - } - - credentialEntity = setCredentials(user, cred); - setValue(credentialEntity, cred); - user.getCredentials().add(credentialEntity); - } else { - List credentialEntities = getCredentialEntities(user, UserCredentialModel.PASSWORD_HISTORY); - if (credentialEntities != null && credentialEntities.size() > 0) { - user.getCredentials().removeAll(credentialEntities); - } - setValue(credentialEntity, cred); - } - } - } - - private CredentialEntity setCredentials(MongoUserEntity user, UserCredentialModel cred) { - CredentialEntity credentialEntity = new CredentialEntity(); - credentialEntity.setType(cred.getType()); - credentialEntity.setDevice(cred.getDevice()); - return credentialEntity; - } - - private void setValue(CredentialEntity credentialEntity, UserCredentialModel cred) { - UserCredentialValueModel encoded = PasswordHashManager.encode(session, realm, cred.getValue()); - credentialEntity.setCreatedDate(Time.toMillis(Time.currentTime())); - credentialEntity.setAlgorithm(encoded.getAlgorithm()); - credentialEntity.setValue(encoded.getValue()); - credentialEntity.setSalt(encoded.getSalt()); - credentialEntity.setHashIterations(encoded.getHashIterations()); - } - - private CredentialEntity getCredentialEntity(MongoUserEntity userEntity, String credType) { - for (CredentialEntity entity : userEntity.getCredentials()) { - if (entity.getType().equals(credType)) { - return entity; - } - } - - return null; - } - - private List getCredentialEntities(MongoUserEntity userEntity, String credType) { - List credentialEntities = new ArrayList(); - for (CredentialEntity entity : userEntity.getCredentials()) { - if (entity.getType().equals(credType)) { - credentialEntities.add(entity); - } - } - - // Avoiding direct use of credSecond.getCreatedDate() - credFirst.getCreatedDate() to prevent Integer Overflow - // Orders from most recent to least recent - Collections.sort(credentialEntities, new Comparator() { - public int compare(CredentialEntity credFirst, CredentialEntity credSecond) { - if (credFirst.getCreatedDate() > credSecond.getCreatedDate()) { - return -1; - } else if (credFirst.getCreatedDate() < credSecond.getCreatedDate()) { - return 1; - } else { - return 0; - } - } - }); - return credentialEntities; - } - - @Override - public List getCredentialsDirectly() { - List credentials = user.getCredentials(); - List result = new ArrayList(); - for (CredentialEntity credEntity : credentials) { - UserCredentialValueModel credModel = new UserCredentialValueModel(); - credModel.setType(credEntity.getType()); - credModel.setDevice(credEntity.getDevice()); - credModel.setCreatedDate(credEntity.getCreatedDate()); - credModel.setValue(credEntity.getValue()); - credModel.setSalt(credEntity.getSalt()); - credModel.setHashIterations(credEntity.getHashIterations()); - credModel.setAlgorithm(credEntity.getAlgorithm()); - - if (UserCredentialModel.isOtp(credEntity.getType())) { - credModel.setCounter(credEntity.getCounter()); - if (credEntity.getAlgorithm() == null) { - // for migration where these values would be null - credModel.setAlgorithm(realm.getOTPPolicy().getAlgorithm()); - } else { - credModel.setAlgorithm(credEntity.getAlgorithm()); - } - if (credEntity.getDigits() == 0) { - // for migration where these values would be 0 - credModel.setDigits(realm.getOTPPolicy().getDigits()); - } else { - credModel.setDigits(credEntity.getDigits()); - } - - if (credEntity.getPeriod() == 0) { - // for migration where these values would be 0 - credModel.setPeriod(realm.getOTPPolicy().getPeriod()); - } else { - credModel.setPeriod(credEntity.getPeriod()); - } - } - - result.add(credModel); - } - - return result; - } - - @Override - public void updateCredentialDirectly(UserCredentialValueModel credModel) { - CredentialEntity credentialEntity = getCredentialEntity(user, credModel.getType()); - - if (credentialEntity == null) { - credentialEntity = new CredentialEntity(); - credentialEntity.setType(credModel.getType()); - credModel.setCreatedDate(credModel.getCreatedDate()); - user.getCredentials().add(credentialEntity); - } - - credentialEntity.setValue(credModel.getValue()); - credentialEntity.setSalt(credModel.getSalt()); - credentialEntity.setDevice(credModel.getDevice()); - credentialEntity.setHashIterations(credModel.getHashIterations()); - credentialEntity.setCounter(credModel.getCounter()); - credentialEntity.setAlgorithm(credModel.getAlgorithm()); - credentialEntity.setDigits(credModel.getDigits()); - credentialEntity.setPeriod(credModel.getPeriod()); - - - getMongoStore().updateEntity(user, invocationContext); - } - protected void updateUser() { super.updateMongoEntity(); } diff --git a/server-spi/src/main/java/org/keycloak/credential/CredentialProviderFactory.java b/server-spi/src/main/java/org/keycloak/credential/CredentialProviderFactory.java index 480dd1c5c2..9ad2bc8c87 100755 --- a/server-spi/src/main/java/org/keycloak/credential/CredentialProviderFactory.java +++ b/server-spi/src/main/java/org/keycloak/credential/CredentialProviderFactory.java @@ -24,6 +24,7 @@ import org.keycloak.component.ComponentValidationException; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.provider.ProviderConfigProperty; +import org.keycloak.provider.ProviderFactory; import org.keycloak.storage.UserStorageProvider; import java.util.Collections; @@ -34,16 +35,7 @@ import java.util.Set; * @author Bill Burke * @version $Revision: 1 $ */ -public interface CredentialProviderFactory extends ComponentFactory { - /** - * called per Keycloak transaction. - * - * @param session - * @param model - * @return - */ - T create(KeycloakSession session, ComponentModel model); - +public interface CredentialProviderFactory extends ProviderFactory { /** * This is the name of the provider and will be showed in the admin console as an option. * @@ -67,19 +59,4 @@ public interface CredentialProviderFactory extends } - @Override - default String getHelpText() { - return ""; - } - - @Override - default List getConfigProperties() { - return Collections.EMPTY_LIST; - } - - @Override - default void validateConfiguration(KeycloakSession session, ComponentModel config) throws ComponentValidationException { - - } - } diff --git a/server-spi/src/main/java/org/keycloak/credential/CredentialSpi.java b/server-spi/src/main/java/org/keycloak/credential/CredentialSpi.java new file mode 100644 index 0000000000..34bd43f1b1 --- /dev/null +++ b/server-spi/src/main/java/org/keycloak/credential/CredentialSpi.java @@ -0,0 +1,50 @@ +/* + * Copyright 2016 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.credential.hash.PasswordHashProvider; +import org.keycloak.credential.hash.PasswordHashProviderFactory; +import org.keycloak.provider.Provider; +import org.keycloak.provider.ProviderFactory; +import org.keycloak.provider.Spi; + +/** + * @author Kunal Kerkar + */ +public class CredentialSpi implements Spi { + + @Override + public boolean isInternal() { + return false; + } + + @Override + public String getName() { + return "credential"; + } + + @Override + public Class getProviderClass() { + return CredentialProvider.class; + } + + @Override + public Class getProviderFactoryClass() { + return CredentialProviderFactory.class; + } +} diff --git a/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashProvider.java b/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashProvider.java new file mode 100644 index 0000000000..74fe7cd00c --- /dev/null +++ b/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashProvider.java @@ -0,0 +1,35 @@ +/* + * Copyright 2016 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.hash; + +import org.keycloak.credential.CredentialModel; +import org.keycloak.models.PasswordPolicy; +import org.keycloak.models.UserCredentialValueModel; +import org.keycloak.provider.Provider; + +/** + * @author Kunal Kerkar + */ +public interface PasswordHashProvider extends Provider { + boolean policyCheck(PasswordPolicy policy, CredentialModel credentia); + + void encode(String rawPassword, PasswordPolicy policy, CredentialModel credential); + + boolean verify(String rawPassword, CredentialModel credential); + +} diff --git a/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashProviderFactory.java b/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashProviderFactory.java new file mode 100644 index 0000000000..795bf789f4 --- /dev/null +++ b/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashProviderFactory.java @@ -0,0 +1,27 @@ +/* + * Copyright 2016 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.hash; + +import org.keycloak.provider.ProviderFactory; + +/** + * @author Kunal Kerkar + */ +public interface PasswordHashProviderFactory extends ProviderFactory { + +} diff --git a/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashSpi.java b/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashSpi.java new file mode 100644 index 0000000000..bdee135d6f --- /dev/null +++ b/server-spi/src/main/java/org/keycloak/credential/hash/PasswordHashSpi.java @@ -0,0 +1,48 @@ +/* + * Copyright 2016 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.hash; + +import org.keycloak.provider.Provider; +import org.keycloak.provider.ProviderFactory; +import org.keycloak.provider.Spi; + +/** + * @author Kunal Kerkar + */ +public class PasswordHashSpi implements Spi { + + @Override + public boolean isInternal() { + return false; + } + + @Override + public String getName() { + return "password-hashing"; + } + + @Override + public Class getProviderClass() { + return PasswordHashProvider.class; + } + + @Override + public Class getProviderFactoryClass() { + return PasswordHashProviderFactory.class; + } +} diff --git a/server-spi/src/main/java/org/keycloak/models/UserCredentialManager.java b/server-spi/src/main/java/org/keycloak/models/UserCredentialManager.java index 2da5716f92..0dd1aae40e 100644 --- a/server-spi/src/main/java/org/keycloak/models/UserCredentialManager.java +++ b/server-spi/src/main/java/org/keycloak/models/UserCredentialManager.java @@ -27,11 +27,68 @@ import java.util.Set; * @version $Revision: 1 $ */ public interface UserCredentialManager extends UserCredentialStore { + + /** + * Validates list of credentials. Will call UserStorageProvider and UserFederationProviders first, then loop through + * each CredentialProvider. + * + * @param realm + * @param user + * @param inputs + * @return + */ boolean isValid(RealmModel realm, UserModel user, List inputs); + /** + * Validates list of credentials. Will call UserStorageProvider and UserFederationProviders first, then loop through + * each CredentialProvider. + * + * @param realm + * @param user + * @param inputs + * @return + */ + boolean isValid(RealmModel realm, UserModel user, CredentialInput... inputs); + + /** + * Updates a credential. Will call UserStorageProvider and UserFederationProviders first, then loop through + * each CredentialProvider. Update is finished whenever any one provider returns true. + * + * @param realm + * @param user + * @return + */ void updateCredential(RealmModel realm, UserModel user, CredentialInput input); + + /** + * Calls disableCredential on UserStorageProvider and UserFederationProviders first, then loop through + * each CredentialProvider. + * + * @param realm + * @param user + * @param credentialType + */ void disableCredential(RealmModel realm, UserModel user, String credentialType); + /** + * Checks to see if user has credential type configured. Looks in UserStorageProvider or UserFederationProvider first, + * then loops through each CredentialProvider. + * + * @param realm + * @param user + * @param type + * @return + */ boolean isConfiguredFor(RealmModel realm, UserModel user, String type); + /** + * Only loops through each CredentialProvider to see if credential type is configured for the user. + * This allows UserStorageProvider and UserFederationProvider to look to abort isValid + * + * @param realm + * @param user + * @param type + * @return + */ + boolean isConfiguredLocally(RealmModel realm, UserModel user, String type); } diff --git a/server-spi/src/main/java/org/keycloak/models/UserFederationManager.java b/server-spi/src/main/java/org/keycloak/models/UserFederationManager.java index e1037053fc..42f112d15b 100755 --- a/server-spi/src/main/java/org/keycloak/models/UserFederationManager.java +++ b/server-spi/src/main/java/org/keycloak/models/UserFederationManager.java @@ -58,10 +58,6 @@ public class UserFederationManager implements UserProvider { return registerWithFederation(realm, user); } - protected UserFederationProvider getFederationProvider(UserFederationProviderModel model) { - return KeycloakModelUtils.getFederationProviderInstance(session, model); - } - @Override public UserModel addUser(RealmModel realm, String username) { UserModel user = session.userStorage().addUser(realm, username.toLowerCase()); @@ -81,7 +77,11 @@ public class UserFederationManager implements UserProvider { return user; } - protected UserFederationProvider getFederationLink(RealmModel realm, UserModel user) { + protected UserFederationProvider getFederationProvider(UserFederationProviderModel model) { + return KeycloakModelUtils.getFederationProviderInstance(session, model); + } + + public UserFederationProvider getFederationLink(RealmModel realm, UserModel user) { if (user.getFederationLink() == null) return null; for (UserFederationProviderModel fed : realm.getUserFederationProviders()) { if (fed.getId().equals(user.getFederationLink())) { @@ -112,7 +112,7 @@ public class UserFederationManager implements UserProvider { } - protected void validateUser(RealmModel realm, UserModel user) { + public void validateUser(RealmModel realm, UserModel user) { if (managedUsers.containsKey(user.getId())) { return; } @@ -488,84 +488,6 @@ public class UserFederationManager implements UserProvider { session.userStorage().preRemove(protocolMapper); } - public void updateCredential(RealmModel realm, UserModel user, UserCredentialModel credential) { - if (credential.getType().equals(UserCredentialModel.PASSWORD)) { - if (realm.getPasswordPolicy() != null) { - PolicyError error = session.getProvider(PasswordPolicyManagerProvider.class).validate(user, credential.getValue()); - if (error != null) throw new ModelException(error.getMessage(), error.getParameters()); - } - } - user.updateCredential(credential); - } - - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List input) { - UserFederationProvider link = getFederationLink(realm, user); - if (link != null) { - validateUser(realm, user); - Set supportedCredentialTypes = link.getSupportedCredentialTypes(user); - if (supportedCredentialTypes.size() > 0) { - List fedCreds = new ArrayList(); - List localCreds = new ArrayList(); - for (UserCredentialModel cred : input) { - if (supportedCredentialTypes.contains(cred.getType())) { - fedCreds.add(cred); - } else { - localCreds.add(cred); - } - } - if (!link.validCredentials(realm, user, fedCreds)) { - return false; - } - return session.userStorage().validCredentials(session, realm, user, localCreds); - } - } - return session.userStorage().validCredentials(session, realm, user, input); - } - - /** - * Is the user configured to use this credential type - * - * @return - */ - public boolean configuredForCredentialType(String type, RealmModel realm, UserModel user) { - UserFederationProvider link = getFederationLink(realm, user); - if (link != null) { - Set supportedCredentialTypes = link.getSupportedCredentialTypes(user); - if (supportedCredentialTypes.contains(type)) return true; - } - if (UserCredentialModel.isOtp(type)) { - if (!user.isOtpEnabled()) return false; - } - - List creds = user.getCredentialsDirectly(); - for (UserCredentialValueModel cred : creds) { - if (cred.getType().equals(type)) { - if (UserCredentialModel.isOtp(type)) { - OTPPolicy otpPolicy = realm.getOTPPolicy(); - if (!cred.getAlgorithm().equals(otpPolicy.getAlgorithm()) - || cred.getDigits() != otpPolicy.getDigits()) { - return false; - } - if (type.equals(UserCredentialModel.TOTP) && cred.getPeriod() != otpPolicy.getPeriod()) { - return false; - } - } - return true; - } - } - return false; - } - - - - - - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, UserCredentialModel... input) { - return validCredentials(session, realm, user, Arrays.asList(input)); - } - @Override public CredentialValidationOutput validCredentials(KeycloakSession session, RealmModel realm, UserCredentialModel... input) { List fedProviderModels = realm.getUserFederationProviders(); diff --git a/server-spi/src/main/java/org/keycloak/models/UserFederationProvider.java b/server-spi/src/main/java/org/keycloak/models/UserFederationProvider.java index 66683176d5..69d17ec174 100755 --- a/server-spi/src/main/java/org/keycloak/models/UserFederationProvider.java +++ b/server-spi/src/main/java/org/keycloak/models/UserFederationProvider.java @@ -17,6 +17,8 @@ package org.keycloak.models; +import org.keycloak.credential.CredentialInputUpdater; +import org.keycloak.credential.CredentialInputValidator; import org.keycloak.provider.Provider; import java.util.List; @@ -30,7 +32,8 @@ import java.util.Set; * @author Bill Burke * @version $Revision: 1 $ */ -public interface UserFederationProvider extends Provider { +@Deprecated +public interface UserFederationProvider extends Provider, CredentialInputValidator, CredentialInputUpdater { public static final String USERNAME = UserModel.USERNAME; public static final String EMAIL = UserModel.EMAIL; @@ -166,14 +169,6 @@ public interface UserFederationProvider extends Provider { */ boolean isValid(RealmModel realm, UserModel local); - /** - * What UserCredentialModel types should be handled by this provider for this user? Keycloak will only call - * validCredentials() with the credential types specified in this method. - * - * @return - */ - Set getSupportedCredentialTypes(UserModel user); - /** * What UserCredentialModel types should be handled by this provider? This is called in scenarios when we don't know user, * who is going to authenticate (For example Kerberos authentication). @@ -182,18 +177,6 @@ public interface UserFederationProvider extends Provider { */ Set getSupportedCredentialTypes(); - /** - * Validate credentials for this user. This method will only be called with credential parameters supported - * by this provider - * - * @param realm - * @param user - * @param input - * @return - */ - boolean validCredentials(RealmModel realm, UserModel user, List input); - boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input); - /** * Validate credentials of unknown user. The authenticated user is recognized based on provided credentials and returned back in CredentialValidationOutput * @param realm diff --git a/server-spi/src/main/java/org/keycloak/models/UserModel.java b/server-spi/src/main/java/org/keycloak/models/UserModel.java index 28c35ab426..6bc80c3179 100755 --- a/server-spi/src/main/java/org/keycloak/models/UserModel.java +++ b/server-spi/src/main/java/org/keycloak/models/UserModel.java @@ -54,8 +54,6 @@ public interface UserModel extends RoleMapperModel { boolean isEnabled(); - boolean isOtpEnabled(); - void setEnabled(boolean enabled); /** @@ -110,14 +108,6 @@ public interface UserModel extends RoleMapperModel { void setEmailVerified(boolean verified); - void setOtpEnabled(boolean totp); - - void updateCredential(UserCredentialModel cred); - - List getCredentialsDirectly(); - - void updateCredentialDirectly(UserCredentialValueModel cred); - Set getGroups(); void joinGroup(GroupModel group); void leaveGroup(GroupModel group); diff --git a/server-spi/src/main/java/org/keycloak/models/UserProvider.java b/server-spi/src/main/java/org/keycloak/models/UserProvider.java index 642131b518..e1b64fa927 100755 --- a/server-spi/src/main/java/org/keycloak/models/UserProvider.java +++ b/server-spi/src/main/java/org/keycloak/models/UserProvider.java @@ -18,9 +18,7 @@ package org.keycloak.models; import org.keycloak.component.ComponentModel; -import org.keycloak.credential.CredentialInput; import org.keycloak.provider.Provider; -import org.keycloak.storage.user.UserCredentialValidatorProvider; import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.storage.user.UserQueryProvider; import org.keycloak.storage.user.UserRegistrationProvider; @@ -35,7 +33,6 @@ import java.util.Set; public interface UserProvider extends Provider, UserLookupProvider, UserQueryProvider, - UserCredentialValidatorProvider, UserRegistrationProvider { // Note: The reason there are so many query methods here is for layering a cache on top of an persistent KeycloakSession @@ -79,7 +76,6 @@ public interface UserProvider extends Provider, void preRemove(ProtocolMapperModel protocolMapper); - boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, UserCredentialModel... input); CredentialValidationOutput validCredentials(KeycloakSession session, RealmModel realm, UserCredentialModel... input); diff --git a/server-spi/src/main/java/org/keycloak/models/cache/CachedUserModel.java b/server-spi/src/main/java/org/keycloak/models/cache/CachedUserModel.java index 5d9c7cd278..9ee5a6a090 100644 --- a/server-spi/src/main/java/org/keycloak/models/cache/CachedUserModel.java +++ b/server-spi/src/main/java/org/keycloak/models/cache/CachedUserModel.java @@ -21,10 +21,24 @@ import org.keycloak.models.UserModel; import java.util.concurrent.ConcurrentHashMap; /** + * Cached users will implement this interface + * * @author Bill Burke * @version $Revision: 1 $ */ public interface CachedUserModel extends UserModel { + + /** + * Invalidates the cache for this user and returns a delegate that represents the actual data provider + * + * @return + */ + UserModel getDelegateForUpdate(); + + /** + * Invalidate the cache for this user + * + */ void invalidate(); /** diff --git a/server-spi/src/main/java/org/keycloak/models/cache/OnUserCache.java b/server-spi/src/main/java/org/keycloak/models/cache/OnUserCache.java index e676ce14e6..319b5c55db 100644 --- a/server-spi/src/main/java/org/keycloak/models/cache/OnUserCache.java +++ b/server-spi/src/main/java/org/keycloak/models/cache/OnUserCache.java @@ -17,11 +17,12 @@ package org.keycloak.models.cache; import org.keycloak.models.RealmModel; +import org.keycloak.models.UserModel; /** * @author Bill Burke * @version $Revision: 1 $ */ public interface OnUserCache { - void onCache(RealmModel realm, CachedUserModel user); + void onCache(RealmModel realm, CachedUserModel user, UserModel delegate); } diff --git a/server-spi/src/main/java/org/keycloak/models/entities/UserEntity.java b/server-spi/src/main/java/org/keycloak/models/entities/UserEntity.java index 04757150b5..95bdc0d9bf 100755 --- a/server-spi/src/main/java/org/keycloak/models/entities/UserEntity.java +++ b/server-spi/src/main/java/org/keycloak/models/entities/UserEntity.java @@ -32,7 +32,6 @@ public class UserEntity extends AbstractIdentifiableEntity { private String lastName; private String email; private boolean emailVerified; - private boolean totp; private boolean enabled; private String realmId; @@ -96,14 +95,6 @@ public class UserEntity extends AbstractIdentifiableEntity { this.emailVerified = emailVerified; } - public boolean isTotp() { - return totp; - } - - public void setTotp(boolean totp) { - this.totp = totp; - } - public boolean isEnabled() { return enabled; } diff --git a/server-spi/src/main/java/org/keycloak/models/utils/CredentialValidation.java b/server-spi/src/main/java/org/keycloak/models/utils/CredentialValidation.java index 85d52c002c..4bbb2ab192 100755 --- a/server-spi/src/main/java/org/keycloak/models/utils/CredentialValidation.java +++ b/server-spi/src/main/java/org/keycloak/models/utils/CredentialValidation.java @@ -38,45 +38,6 @@ import java.util.List; */ public class CredentialValidation { - /** - * Will update password if hash iteration policy has changed - * - * @param realm - * @param user - * @param password - * @return - */ - public static boolean validPassword(KeycloakSession session, RealmModel realm, UserModel user, String password) { - UserCredentialValueModel passwordCred = null; - for (UserCredentialValueModel cred : user.getCredentialsDirectly()) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - passwordCred = cred; - } - } - if (passwordCred == null) return false; - - return validateHashedCredential(session, realm, user, password, passwordCred); - - } - - - public static boolean validateHashedCredential(KeycloakSession session, RealmModel realm, UserModel user, String unhashedCredValue, UserCredentialValueModel credential) { - if (unhashedCredValue == null || unhashedCredValue.isEmpty()) { - return false; - } - - boolean validated = PasswordHashManager.verify(session, realm, unhashedCredValue, credential); - - if (validated) { - if (realm.getPasswordPolicy().getHashIterations() != credential.getHashIterations()) { - - UserCredentialValueModel newCred = PasswordHashManager.encode(session, realm, unhashedCredValue); - user.updateCredentialDirectly(newCred); - } - - } - return validated; - } public static boolean validPasswordToken(RealmModel realm, UserModel user, String encodedPasswordToken) { try { @@ -100,23 +61,6 @@ public class CredentialValidation { } } - public static boolean validHOTP(RealmModel realm, UserModel user, String otp) { - UserCredentialValueModel passwordCred = null; - OTPPolicy policy = realm.getOTPPolicy(); - HmacOTP validator = new HmacOTP(policy.getDigits(), policy.getAlgorithm(), policy.getLookAheadWindow()); - for (UserCredentialValueModel cred : user.getCredentialsDirectly()) { - if (cred.getType().equals(UserCredentialModel.HOTP)) { - int counter = validator.validateHOTP(otp, cred.getValue(), cred.getCounter()); - if (counter < 0) return false; - cred.setCounter(counter); - user.updateCredentialDirectly(cred); - return true; - } - } - return false; - - } - public static boolean validOTP(RealmModel realm, String token, String secret) { OTPPolicy policy = realm.getOTPPolicy(); if (policy.getType().equals(UserCredentialModel.TOTP)) { @@ -130,84 +74,5 @@ public class CredentialValidation { } - public static boolean validTOTP(RealmModel realm, UserModel user, String otp) { - UserCredentialValueModel passwordCred = null; - OTPPolicy policy = realm.getOTPPolicy(); - TimeBasedOTP validator = new TimeBasedOTP(policy.getAlgorithm(), policy.getDigits(), policy.getPeriod(), policy.getLookAheadWindow()); - for (UserCredentialValueModel cred : user.getCredentialsDirectly()) { - if (cred.getType().equals(UserCredentialModel.TOTP)) { - if (validator.validateTOTP(otp, cred.getValue().getBytes())) { - return true; - } - } - } - return false; - } - public static boolean validSecret(RealmModel realm, UserModel user, String secret) { - for (UserCredentialValueModel cred : user.getCredentialsDirectly()) { - if (cred.getType().equals(UserCredentialModel.SECRET)) { - if (cred.getValue().equals(secret)) return true; - } - } - return false; - - } - - /** - * Must validate all credentials. FYI, password hashes may be rehashed and updated based on realm hash password policies. - * - * @param realm - * @param user - * @param credentials - * @return - */ - public static boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List credentials) { - for (UserCredentialModel credential : credentials) { - if (!validCredential(session, realm, user, credential)) return false; - } - return true; - } - - /** - * Must validate all credentials. FYI, password hashes may be rehashed and updated based on realm hash password policies. - * - * @param realm - * @param user - * @param credentials - * @return - */ - public static boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, UserCredentialModel... credentials) { - for (UserCredentialModel credential : credentials) { - if (!validCredential(session, realm, user, credential)) return false; - } - return true; - } - - public static boolean validCredential(KeycloakSession session, RealmModel realm, UserModel user, UserCredentialModel credential) { - if (credential.getType().equals(UserCredentialModel.PASSWORD)) { - if (!validPassword(session, realm, user, credential.getValue())) { - return false; - } - } else if (credential.getType().equals(UserCredentialModel.PASSWORD_TOKEN)) { - if (!validPasswordToken(realm, user, credential.getValue())) { - return false; - } - } else if (credential.getType().equals(UserCredentialModel.TOTP)) { - if (!validTOTP(realm, user, credential.getValue())) { - return false; - } - } else if (credential.getType().equals(UserCredentialModel.HOTP)) { - if (!validHOTP(realm, user, credential.getValue())) { - return false; - } - } else if (credential.getType().equals(UserCredentialModel.SECRET)) { - if (!validSecret(realm, user, credential.getValue())) { - return false; - } - } else { - return false; - } - return true; - } } diff --git a/server-spi/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java b/server-spi/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java index 2d75c547e6..659c116419 100755 --- a/server-spi/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java +++ b/server-spi/src/main/java/org/keycloak/models/utils/ModelToRepresentation.java @@ -26,6 +26,7 @@ import org.keycloak.authorization.store.PolicyStore; import org.keycloak.authorization.store.ResourceStore; import org.keycloak.authorization.store.StoreFactory; import org.keycloak.component.ComponentModel; +import org.keycloak.credential.CredentialModel; import org.keycloak.events.Event; import org.keycloak.events.admin.AdminEvent; import org.keycloak.events.admin.AuthDetails; @@ -174,7 +175,7 @@ public class ModelToRepresentation { } - public static UserRepresentation toRepresentation(UserModel user) { + public static UserRepresentation toRepresentation(KeycloakSession session, RealmModel realm, UserModel user) { UserRepresentation rep = new UserRepresentation(); rep.setId(user.getId()); rep.setUsername(user.getUsername()); @@ -184,7 +185,7 @@ public class ModelToRepresentation { rep.setEmail(user.getEmail()); rep.setEnabled(user.isEnabled()); rep.setEmailVerified(user.isEmailVerified()); - rep.setTotp(user.isOtpEnabled()); + rep.setTotp(session.userCredentialManager().isConfiguredFor(realm, user, CredentialModel.OTP)); rep.setFederationLink(user.getFederationLink()); List reqActions = new ArrayList(); diff --git a/server-spi/src/main/java/org/keycloak/models/utils/RepresentationToModel.java b/server-spi/src/main/java/org/keycloak/models/utils/RepresentationToModel.java index 8ea1e970d4..f228bc7631 100755 --- a/server-spi/src/main/java/org/keycloak/models/utils/RepresentationToModel.java +++ b/server-spi/src/main/java/org/keycloak/models/utils/RepresentationToModel.java @@ -30,6 +30,7 @@ import org.keycloak.authorization.store.ScopeStore; import org.keycloak.authorization.store.StoreFactory; import org.keycloak.common.util.MultivaluedHashMap; import org.keycloak.component.ComponentModel; +import org.keycloak.credential.CredentialModel; import org.keycloak.hash.Pbkdf2PasswordHashProvider; import org.keycloak.migration.migrators.MigrationUtils; import org.keycloak.models.ClientTemplateModel; @@ -1348,7 +1349,6 @@ public class RepresentationToModel { user.setFirstName(userRep.getFirstName()); user.setLastName(userRep.getLastName()); user.setFederationLink(userRep.getFederationLink()); - if (userRep.isTotp() != null) user.setOtpEnabled(userRep.isTotp()); if (userRep.getAttributes() != null) { for (Map.Entry entry : userRep.getAttributes().entrySet()) { Object value = entry.getValue(); @@ -1368,7 +1368,7 @@ public class RepresentationToModel { user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction)); } } - createCredentials(userRep, user); + createCredentials(userRep, session, newRealm, user); if (userRep.getFederatedIdentities() != null) { for (FederatedIdentityRepresentation identity : userRep.getFederatedIdentities()) { FederatedIdentityModel mappingModel = new FederatedIdentityModel(identity.getIdentityProvider(), identity.getUserId(), identity.getUserName()); @@ -1403,21 +1403,21 @@ public class RepresentationToModel { return user; } - public static void createCredentials(UserRepresentation userRep, UserModel user) { + public static void createCredentials(UserRepresentation userRep, KeycloakSession session, RealmModel realm,UserModel user) { if (userRep.getCredentials() != null) { for (CredentialRepresentation cred : userRep.getCredentials()) { - updateCredential(user, cred); + updateCredential(session, realm, user, cred); } } } // Detect if it is "plain-text" or "hashed" representation and update model according to it - private static void updateCredential(UserModel user, CredentialRepresentation cred) { + private static void updateCredential(KeycloakSession session, RealmModel realm, UserModel user, CredentialRepresentation cred) { if (cred.getValue() != null) { UserCredentialModel plainTextCred = convertCredential(cred); - user.updateCredential(plainTextCred); + session.userCredentialManager().updateCredential(realm, user, plainTextCred); } else { - UserCredentialValueModel hashedCred = new UserCredentialValueModel(); + CredentialModel hashedCred = new CredentialModel(); hashedCred.setType(cred.getType()); hashedCred.setDevice(cred.getDevice()); if (cred.getHashIterations() != null) hashedCred.setHashIterations(cred.getHashIterations()); @@ -1456,7 +1456,7 @@ public class RepresentationToModel { hashedCred.setPeriod(30); } hashedCred.setCreatedDate(cred.getCreatedDate()); - user.updateCredentialDirectly(hashedCred); + session.userCredentialManager().createCredential(realm, user, hashedCred); } } diff --git a/server-spi/src/main/java/org/keycloak/models/utils/UserModelDelegate.java b/server-spi/src/main/java/org/keycloak/models/utils/UserModelDelegate.java index 9a8e4abcc7..9efdfad282 100755 --- a/server-spi/src/main/java/org/keycloak/models/utils/UserModelDelegate.java +++ b/server-spi/src/main/java/org/keycloak/models/utils/UserModelDelegate.java @@ -60,11 +60,6 @@ public class UserModelDelegate implements UserModel { return delegate.isEnabled(); } - @Override - public boolean isOtpEnabled() { - return delegate.isOtpEnabled(); - } - @Override public void setEnabled(boolean enabled) { delegate.setEnabled(enabled); @@ -165,26 +160,6 @@ public class UserModelDelegate implements UserModel { delegate.setEmailVerified(verified); } - @Override - public void setOtpEnabled(boolean totp) { - delegate.setOtpEnabled(totp); - } - - @Override - public void updateCredential(UserCredentialModel cred) { - delegate.updateCredential(cred); - } - - @Override - public List getCredentialsDirectly() { - return delegate.getCredentialsDirectly(); - } - - @Override - public void updateCredentialDirectly(UserCredentialValueModel cred) { - delegate.updateCredentialDirectly(cred); - } - @Override public Set getRealmRoleMappings() { return delegate.getRealmRoleMappings(); diff --git a/server-spi/src/main/java/org/keycloak/policy/DefaultPasswordPolicyManagerProvider.java b/server-spi/src/main/java/org/keycloak/policy/DefaultPasswordPolicyManagerProvider.java index c380f804d3..b1bfc0c1ab 100644 --- a/server-spi/src/main/java/org/keycloak/policy/DefaultPasswordPolicyManagerProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/DefaultPasswordPolicyManagerProvider.java @@ -19,6 +19,7 @@ package org.keycloak.policy; import org.keycloak.models.KeycloakSession; import org.keycloak.models.PasswordPolicy; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import java.util.LinkedList; @@ -36,9 +37,9 @@ public class DefaultPasswordPolicyManagerProvider implements PasswordPolicyManag } @Override - public PolicyError validate(UserModel user, String password) { - for (PasswordPolicyProvider p : getProviders(session)) { - PolicyError policyError = p.validate(user, password); + public PolicyError validate(RealmModel realm, UserModel user, String password) { + for (PasswordPolicyProvider p : getProviders(realm, session)) { + PolicyError policyError = p.validate(realm, user, password); if (policyError != null) { return policyError; } @@ -62,8 +63,13 @@ public class DefaultPasswordPolicyManagerProvider implements PasswordPolicyManag } private List getProviders(KeycloakSession session) { + return getProviders(session.getContext().getRealm(), session); + + } + + private List getProviders(RealmModel realm, KeycloakSession session) { LinkedList list = new LinkedList<>(); - PasswordPolicy policy = session.getContext().getRealm().getPasswordPolicy(); + PasswordPolicy policy = realm.getPasswordPolicy(); for (String id : policy.getPolicies()) { PasswordPolicyProvider provider = session.getProvider(PasswordPolicyProvider.class, id); list.add(provider); diff --git a/server-spi/src/main/java/org/keycloak/policy/DigitsPasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/DigitsPasswordPolicyProvider.java index d3ca22dea7..391317ed9b 100644 --- a/server-spi/src/main/java/org/keycloak/policy/DigitsPasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/DigitsPasswordPolicyProvider.java @@ -18,6 +18,7 @@ package org.keycloak.policy; import org.keycloak.models.KeycloakContext; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -46,7 +47,7 @@ public class DigitsPasswordPolicyProvider implements PasswordPolicyProvider { } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return validate(user.getUsername(), password); } diff --git a/server-spi/src/main/java/org/keycloak/policy/ForceExpiredPasswordPolicyProviderFactory.java b/server-spi/src/main/java/org/keycloak/policy/ForceExpiredPasswordPolicyProviderFactory.java index ecefffb3be..114447834d 100644 --- a/server-spi/src/main/java/org/keycloak/policy/ForceExpiredPasswordPolicyProviderFactory.java +++ b/server-spi/src/main/java/org/keycloak/policy/ForceExpiredPasswordPolicyProviderFactory.java @@ -20,6 +20,7 @@ package org.keycloak.policy; import org.keycloak.Config; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -53,7 +54,7 @@ public class ForceExpiredPasswordPolicyProviderFactory implements PasswordPolicy } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return null; } diff --git a/server-spi/src/main/java/org/keycloak/policy/HashAlgorithmPasswordPolicyProviderFactory.java b/server-spi/src/main/java/org/keycloak/policy/HashAlgorithmPasswordPolicyProviderFactory.java index add3b03cf2..e7daaabba0 100644 --- a/server-spi/src/main/java/org/keycloak/policy/HashAlgorithmPasswordPolicyProviderFactory.java +++ b/server-spi/src/main/java/org/keycloak/policy/HashAlgorithmPasswordPolicyProviderFactory.java @@ -20,6 +20,7 @@ package org.keycloak.policy; import org.keycloak.Config; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -54,7 +55,7 @@ public class HashAlgorithmPasswordPolicyProviderFactory implements PasswordPolic } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return null; } diff --git a/server-spi/src/main/java/org/keycloak/policy/HashIterationsPasswordPolicyProviderFactory.java b/server-spi/src/main/java/org/keycloak/policy/HashIterationsPasswordPolicyProviderFactory.java index 64a77d5440..ae9d497e23 100644 --- a/server-spi/src/main/java/org/keycloak/policy/HashIterationsPasswordPolicyProviderFactory.java +++ b/server-spi/src/main/java/org/keycloak/policy/HashIterationsPasswordPolicyProviderFactory.java @@ -20,6 +20,7 @@ package org.keycloak.policy; import org.keycloak.Config; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -50,7 +51,7 @@ public class HashIterationsPasswordPolicyProviderFactory implements PasswordPoli } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return null; } diff --git a/server-spi/src/main/java/org/keycloak/policy/HistoryPasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/HistoryPasswordPolicyProvider.java index 3cfe5fb6ce..b65aff216c 100644 --- a/server-spi/src/main/java/org/keycloak/policy/HistoryPasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/HistoryPasswordPolicyProvider.java @@ -17,9 +17,13 @@ package org.keycloak.policy; +import org.jboss.logging.Logger; +import org.keycloak.credential.CredentialModel; +import org.keycloak.credential.hash.PasswordHashProvider; import org.keycloak.hash.PasswordHashManager; import org.keycloak.models.KeycloakSession; import org.keycloak.models.PasswordPolicy; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserCredentialModel; import org.keycloak.models.UserCredentialValueModel; import org.keycloak.models.UserModel; @@ -34,6 +38,7 @@ import java.util.List; */ public class HistoryPasswordPolicyProvider implements PasswordPolicyProvider { + private static final Logger logger = Logger.getLogger(HistoryPasswordPolicyProvider.class); private static final String ERROR_MESSAGE = "invalidPasswordHistoryMessage"; private KeycloakSession session; @@ -48,63 +53,30 @@ public class HistoryPasswordPolicyProvider implements PasswordPolicyProvider { } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { PasswordPolicy policy = session.getContext().getRealm().getPasswordPolicy(); int passwordHistoryPolicyValue = policy.getPolicyConfig(HistoryPasswordPolicyProviderFactory.ID); if (passwordHistoryPolicyValue != -1) { - UserCredentialValueModel cred = getCredentialValueModel(user, UserCredentialModel.PASSWORD); - if (cred != null) { - if(PasswordHashManager.verify(session, policy, password, cred)) { + List storedPasswords = session.userCredentialManager().getStoredCredentialsByType(realm, user, CredentialModel.PASSWORD); + for (CredentialModel cred : storedPasswords) { + PasswordHashProvider hash = session.getProvider(PasswordHashProvider.class, cred.getAlgorithm()); + if (hash == null) continue; + if (hash.verify(password, cred)) { return new PolicyError(ERROR_MESSAGE, passwordHistoryPolicyValue); } } - - List passwordExpiredCredentials = getCredentialValueModels(user, passwordHistoryPolicyValue - 1, - UserCredentialModel.PASSWORD_HISTORY); - for (UserCredentialValueModel credential : passwordExpiredCredentials) { - if (PasswordHashManager.verify(session, policy, password, credential)) { + List passwordHistory = session.userCredentialManager().getStoredCredentialsByType(realm, user, CredentialModel.PASSWORD_HISTORY); + for (CredentialModel cred : passwordHistory) { + PasswordHashProvider hash = session.getProvider(PasswordHashProvider.class, cred.getAlgorithm()); + if (hash.verify(password, cred)) { return new PolicyError(ERROR_MESSAGE, passwordHistoryPolicyValue); } + } } return null; } - private UserCredentialValueModel getCredentialValueModel(UserModel user, String credType) { - for (UserCredentialValueModel model : user.getCredentialsDirectly()) { - if (model.getType().equals(credType)) { - return model; - } - } - return null; - } - - private List getCredentialValueModels(UserModel user, int expiredPasswordsPolicyValue, String credType) { - List credentialModels = new ArrayList(); - for (UserCredentialValueModel model : user.getCredentialsDirectly()) { - if (model.getType().equals(credType)) { - credentialModels.add(model); - } - } - - Collections.sort(credentialModels, new Comparator() { - public int compare(UserCredentialValueModel credFirst, UserCredentialValueModel credSecond) { - if (credFirst.getCreatedDate() > credSecond.getCreatedDate()) { - return -1; - } else if (credFirst.getCreatedDate() < credSecond.getCreatedDate()) { - return 1; - } else { - return 0; - } - } - }); - - if (credentialModels.size() > expiredPasswordsPolicyValue) { - return credentialModels.subList(0, expiredPasswordsPolicyValue); - } - return credentialModels; - } - @Override public Object parseConfig(String value) { return value != null ? Integer.parseInt(value) : HistoryPasswordPolicyProviderFactory.DEFAULT_VALUE; diff --git a/server-spi/src/main/java/org/keycloak/policy/LengthPasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/LengthPasswordPolicyProvider.java index bdafdc9293..5ba71fee45 100644 --- a/server-spi/src/main/java/org/keycloak/policy/LengthPasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/LengthPasswordPolicyProvider.java @@ -18,6 +18,7 @@ package org.keycloak.policy; import org.keycloak.models.KeycloakContext; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -40,7 +41,7 @@ public class LengthPasswordPolicyProvider implements PasswordPolicyProvider { } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return validate(user.getUsername(), password); } diff --git a/server-spi/src/main/java/org/keycloak/policy/LowerCasePasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/LowerCasePasswordPolicyProvider.java index 3312e2d2c0..f080d00594 100644 --- a/server-spi/src/main/java/org/keycloak/policy/LowerCasePasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/LowerCasePasswordPolicyProvider.java @@ -18,6 +18,7 @@ package org.keycloak.policy; import org.keycloak.models.KeycloakContext; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -46,7 +47,7 @@ public class LowerCasePasswordPolicyProvider implements PasswordPolicyProvider { } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return validate(user.getUsername(), password); } diff --git a/server-spi/src/main/java/org/keycloak/policy/NotUsernamePasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/NotUsernamePasswordPolicyProvider.java index 54634e670c..f08edab0d6 100644 --- a/server-spi/src/main/java/org/keycloak/policy/NotUsernamePasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/NotUsernamePasswordPolicyProvider.java @@ -18,6 +18,7 @@ package org.keycloak.policy; import org.keycloak.models.KeycloakContext; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -42,7 +43,7 @@ public class NotUsernamePasswordPolicyProvider implements PasswordPolicyProvider } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return validate(user.getUsername(), password); } diff --git a/server-spi/src/main/java/org/keycloak/policy/PasswordPolicyManagerProvider.java b/server-spi/src/main/java/org/keycloak/policy/PasswordPolicyManagerProvider.java index 3039c95e09..e5e8497763 100644 --- a/server-spi/src/main/java/org/keycloak/policy/PasswordPolicyManagerProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/PasswordPolicyManagerProvider.java @@ -17,6 +17,7 @@ package org.keycloak.policy; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.provider.Provider; @@ -25,7 +26,7 @@ import org.keycloak.provider.Provider; */ public interface PasswordPolicyManagerProvider extends Provider { - PolicyError validate(UserModel user, String password); + PolicyError validate(RealmModel realm, UserModel user, String password); PolicyError validate(String user, String password); } diff --git a/server-spi/src/main/java/org/keycloak/policy/PasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/PasswordPolicyProvider.java index 96b1803b09..3f7c3ea869 100644 --- a/server-spi/src/main/java/org/keycloak/policy/PasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/PasswordPolicyProvider.java @@ -17,6 +17,7 @@ package org.keycloak.policy; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.provider.Provider; @@ -28,7 +29,7 @@ public interface PasswordPolicyProvider extends Provider { String STRING_CONFIG_TYPE = "String"; String INT_CONFIG_TYPE = "int"; - PolicyError validate(UserModel user, String password); + PolicyError validate(RealmModel realm, UserModel user, String password); PolicyError validate(String user, String password); Object parseConfig(String value); diff --git a/server-spi/src/main/java/org/keycloak/policy/RegexPatternsPasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/RegexPatternsPasswordPolicyProvider.java index 7d4dbccf87..52c83b86e8 100644 --- a/server-spi/src/main/java/org/keycloak/policy/RegexPatternsPasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/RegexPatternsPasswordPolicyProvider.java @@ -18,6 +18,7 @@ package org.keycloak.policy; import org.keycloak.models.KeycloakContext; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import java.util.regex.Matcher; @@ -47,7 +48,7 @@ public class RegexPatternsPasswordPolicyProvider implements PasswordPolicyProvid } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return validate(user.getUsername(), password); } diff --git a/server-spi/src/main/java/org/keycloak/policy/SpecialCharsPasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/SpecialCharsPasswordPolicyProvider.java index 694d81e23a..fa851372a9 100644 --- a/server-spi/src/main/java/org/keycloak/policy/SpecialCharsPasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/SpecialCharsPasswordPolicyProvider.java @@ -18,6 +18,7 @@ package org.keycloak.policy; import org.keycloak.models.KeycloakContext; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -46,7 +47,7 @@ public class SpecialCharsPasswordPolicyProvider implements PasswordPolicyProvide } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return validate(user.getUsername(), password); } diff --git a/server-spi/src/main/java/org/keycloak/policy/UpperCasePasswordPolicyProvider.java b/server-spi/src/main/java/org/keycloak/policy/UpperCasePasswordPolicyProvider.java index d8a570b6df..16ac1eff58 100644 --- a/server-spi/src/main/java/org/keycloak/policy/UpperCasePasswordPolicyProvider.java +++ b/server-spi/src/main/java/org/keycloak/policy/UpperCasePasswordPolicyProvider.java @@ -18,6 +18,7 @@ package org.keycloak.policy; import org.keycloak.models.KeycloakContext; +import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; /** @@ -46,7 +47,7 @@ public class UpperCasePasswordPolicyProvider implements PasswordPolicyProvider { } @Override - public PolicyError validate(UserModel user, String password) { + public PolicyError validate(RealmModel realm, UserModel user, String password) { return validate(user.getUsername(), password); } diff --git a/server-spi/src/main/java/org/keycloak/storage/adapter/AbstractUserAdapter.java b/server-spi/src/main/java/org/keycloak/storage/adapter/AbstractUserAdapter.java index 6a4e7d2be8..157f9ddba2 100644 --- a/server-spi/src/main/java/org/keycloak/storage/adapter/AbstractUserAdapter.java +++ b/server-spi/src/main/java/org/keycloak/storage/adapter/AbstractUserAdapter.java @@ -223,17 +223,6 @@ public abstract class AbstractUserAdapter implements UserModel { throw new ReadOnlyException("user is read only for this update"); } - @Override - public boolean isOtpEnabled() { - return false; - } - - @Override - public void setOtpEnabled(boolean totp) { - throw new ReadOnlyException("user is read only for this update"); - - } - /** * This method should not be overriden * @@ -386,23 +375,6 @@ public abstract class AbstractUserAdapter implements UserModel { } - @Override - public void updateCredential(UserCredentialModel cred) { - throw new ReadOnlyException("user is read only for this update"); - - } - - @Override - public List getCredentialsDirectly() { - return Collections.EMPTY_LIST; - } - - @Override - public void updateCredentialDirectly(UserCredentialValueModel cred) { - throw new ReadOnlyException("user is read only for this update"); - - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/server-spi/src/main/java/org/keycloak/storage/adapter/AbstractUserAdapterFederatedStorage.java b/server-spi/src/main/java/org/keycloak/storage/adapter/AbstractUserAdapterFederatedStorage.java index bfe0b95f6e..705a87265d 100644 --- a/server-spi/src/main/java/org/keycloak/storage/adapter/AbstractUserAdapterFederatedStorage.java +++ b/server-spi/src/main/java/org/keycloak/storage/adapter/AbstractUserAdapterFederatedStorage.java @@ -54,7 +54,6 @@ public abstract class AbstractUserAdapterFederatedStorage implements UserModel { public static String EMAIL_VERIFIED_ATTRIBUTE = "EMAIL_VERIFIED"; public static String CREATED_TIMESTAMP_ATTRIBUTE = "CREATED_TIMESTAMP"; public static String ENABLED_ATTRIBUTE = "ENABLED"; - public static String OTP_ENABLED_ATTRIBUTE = "OTP_ENABLED"; protected KeycloakSession session; @@ -235,19 +234,6 @@ public abstract class AbstractUserAdapterFederatedStorage implements UserModel { setSingleAttribute(ENABLED_ATTRIBUTE, Boolean.toString(enabled)); } - @Override - public boolean isOtpEnabled() { - String val = getFirstAttribute(OTP_ENABLED_ATTRIBUTE); - if (val == null) return false; - else return Boolean.valueOf(val); - } - - @Override - public void setOtpEnabled(boolean totp) { - setSingleAttribute(OTP_ENABLED_ATTRIBUTE, Boolean.toString(totp)); - - } - /** * This method should not be overriden * @@ -399,23 +385,6 @@ public abstract class AbstractUserAdapterFederatedStorage implements UserModel { } - @Override - public void updateCredential(UserCredentialModel cred) { - getFederatedStorage().updateCredential(realm, this, cred); - - } - - @Override - public List getCredentialsDirectly() { - return getFederatedStorage().getCredentials(realm, this); - } - - @Override - public void updateCredentialDirectly(UserCredentialValueModel cred) { - getFederatedStorage().updateCredential(realm, this, cred); - - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/server-spi/src/main/java/org/keycloak/storage/federated/UserFederatedStorageProvider.java b/server-spi/src/main/java/org/keycloak/storage/federated/UserFederatedStorageProvider.java index b60499199c..4a45301967 100755 --- a/server-spi/src/main/java/org/keycloak/storage/federated/UserFederatedStorageProvider.java +++ b/server-spi/src/main/java/org/keycloak/storage/federated/UserFederatedStorageProvider.java @@ -27,6 +27,9 @@ import org.keycloak.models.UserFederationProviderModel; import org.keycloak.models.UserModel; import org.keycloak.provider.Provider; +import java.util.List; +import java.util.Set; + /** * @author Bill Burke * @version $Revision: 1 $ @@ -40,6 +43,8 @@ public interface UserFederatedStorageProvider extends Provider, UserRequiredActionsFederatedStorage, UserRoleMappingsFederatedStorage { + List getStoredUsers(RealmModel realm, int first, int max); + void preRemove(RealmModel realm); void preRemove(RealmModel realm, UserFederationProviderModel link); diff --git a/server-spi/src/main/resources/META-INF/services/org.keycloak.provider.Spi b/server-spi/src/main/resources/META-INF/services/org.keycloak.provider.Spi index 5ab0346aa3..889c7a48cf 100755 --- a/server-spi/src/main/resources/META-INF/services/org.keycloak.provider.Spi +++ b/server-spi/src/main/resources/META-INF/services/org.keycloak.provider.Spi @@ -63,3 +63,5 @@ org.keycloak.protocol.oidc.TokenIntrospectionSpi org.keycloak.policy.PasswordPolicySpi org.keycloak.policy.PasswordPolicyManagerSpi org.keycloak.transaction.TransactionManagerLookupSpi +org.keycloak.credential.hash.PasswordHashSpi +org.keycloak.credential.CredentialSpi diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java b/services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java index ad4bb0bc6c..52491012f0 100755 --- a/services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java @@ -20,6 +20,7 @@ package org.keycloak.authentication.authenticators.browser; import org.keycloak.authentication.AbstractFormAuthenticator; import org.keycloak.authentication.AuthenticationFlowError; import org.keycloak.authentication.AuthenticationFlowContext; +import org.keycloak.credential.CredentialInput; import org.keycloak.events.Details; import org.keycloak.events.Errors; import org.keycloak.models.ModelDuplicateException; @@ -167,10 +168,10 @@ public abstract class AbstractUsernameFormAuthenticator extends AbstractFormAuth } public boolean validatePassword(AuthenticationFlowContext context, UserModel user, MultivaluedMap inputData) { - List credentials = new LinkedList<>(); + List credentials = new LinkedList<>(); String password = inputData.getFirst(CredentialRepresentation.PASSWORD); credentials.add(UserCredentialModel.password(password)); - boolean valid = context.getSession().users().validCredentials(context.getSession(), context.getRealm(), user, credentials); + boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), user, credentials); if (!valid) { context.getEvent().user(user); context.getEvent().error(Errors.INVALID_USER_CREDENTIALS); diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/browser/OTPFormAuthenticator.java b/services/src/main/java/org/keycloak/authentication/authenticators/browser/OTPFormAuthenticator.java index 4f3dde072b..543aa967c5 100755 --- a/services/src/main/java/org/keycloak/authentication/authenticators/browser/OTPFormAuthenticator.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/browser/OTPFormAuthenticator.java @@ -58,15 +58,14 @@ public class OTPFormAuthenticator extends AbstractUsernameFormAuthenticator impl context.resetFlow(); return; } - List credentials = new LinkedList<>(); String password = inputData.getFirst(CredentialRepresentation.TOTP); if (password == null) { Response challengeResponse = challenge(context, null); context.challenge(challengeResponse); return; } - credentials.add(UserCredentialModel.otp(context.getRealm().getOTPPolicy().getType(), password)); - boolean valid = context.getSession().users().validCredentials(context.getSession(), context.getRealm(), context.getUser(), credentials); + boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), + UserCredentialModel.otp(context.getRealm().getOTPPolicy().getType(), password)); if (!valid) { context.getEvent().user(context.getUser()) .error(Errors.INVALID_USER_CREDENTIALS); @@ -91,7 +90,7 @@ public class OTPFormAuthenticator extends AbstractUsernameFormAuthenticator impl @Override public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { - return session.users().configuredForCredentialType(realm.getOTPPolicy().getType(), realm, user); + return session.userCredentialManager().isConfiguredFor(realm, user, realm.getOTPPolicy().getType()); } @Override diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidateOTP.java b/services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidateOTP.java index cb91956c2e..fd3736cf6a 100755 --- a/services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidateOTP.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidateOTP.java @@ -65,8 +65,7 @@ public class ValidateOTP extends AbstractDirectGrantAuthenticator { context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse); return; } - credentials.add(UserCredentialModel.otp(context.getRealm().getOTPPolicy().getType(), otp)); - boolean valid = context.getSession().users().validCredentials(context.getSession(), context.getRealm(), context.getUser(), credentials); + boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), UserCredentialModel.otp(context.getRealm().getOTPPolicy().getType(), otp)); if (!valid) { context.getEvent().user(context.getUser()); context.getEvent().error(Errors.INVALID_USER_CREDENTIALS); @@ -89,7 +88,7 @@ public class ValidateOTP extends AbstractDirectGrantAuthenticator { } private boolean isConfigured(KeycloakSession session, RealmModel realm, UserModel user) { - return session.users().configuredForCredentialType(realm.getOTPPolicy().getType(), realm, user); + return session.userCredentialManager().isConfiguredFor(realm, user, realm.getOTPPolicy().getType()); } @Override diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidatePassword.java b/services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidatePassword.java index fd9af689f4..033972b902 100755 --- a/services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidatePassword.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/directgrant/ValidatePassword.java @@ -46,8 +46,7 @@ public class ValidatePassword extends AbstractDirectGrantAuthenticator { MultivaluedMap inputData = context.getHttpRequest().getDecodedFormParameters(); List credentials = new LinkedList<>(); String password = inputData.getFirst(CredentialRepresentation.PASSWORD); - credentials.add(UserCredentialModel.password(password)); - boolean valid = context.getSession().users().validCredentials(context.getSession(), context.getRealm(), context.getUser(), credentials); + boolean valid = context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), UserCredentialModel.password(password)); if (!valid) { context.getEvent().user(context.getUser()); context.getEvent().error(Errors.INVALID_USER_CREDENTIALS); diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetOTP.java b/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetOTP.java index b3b0200677..40c703b988 100755 --- a/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetOTP.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetOTP.java @@ -39,7 +39,7 @@ public class ResetOTP extends AbstractSetRequiredActionAuthenticator { } protected boolean configuredFor(AuthenticationFlowContext context) { - return context.getSession().users().configuredForCredentialType(context.getRealm().getOTPPolicy().getType(), context.getRealm(), context.getUser()); + return context.getSession().userCredentialManager().isConfiguredFor(context.getRealm(), context.getUser(), context.getRealm().getOTPPolicy().getType()); } @Override diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetPassword.java b/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetPassword.java index 795c4ecbbe..5ec467d95e 100755 --- a/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetPassword.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/resetcred/ResetPassword.java @@ -40,7 +40,7 @@ public class ResetPassword extends AbstractSetRequiredActionAuthenticator { } protected boolean configuredFor(AuthenticationFlowContext context) { - return context.getSession().users().configuredForCredentialType(UserCredentialModel.PASSWORD, context.getRealm(), context.getUser()); + return context.getSession().userCredentialManager().isConfiguredFor(context.getRealm(), context.getUser(), UserCredentialModel.PASSWORD); } @Override diff --git a/services/src/main/java/org/keycloak/authentication/forms/RegistrationPassword.java b/services/src/main/java/org/keycloak/authentication/forms/RegistrationPassword.java index a42a0735eb..d44e3944f9 100755 --- a/services/src/main/java/org/keycloak/authentication/forms/RegistrationPassword.java +++ b/services/src/main/java/org/keycloak/authentication/forms/RegistrationPassword.java @@ -97,7 +97,7 @@ public class RegistrationPassword implements FormAction, FormActionFactory { credentials.setValue(password); UserModel user = context.getUser(); try { - context.getSession().users().updateCredential(context.getRealm(), user, UserCredentialModel.password(formData.getFirst("password"))); + context.getSession().userCredentialManager().updateCredential(context.getRealm(), user, UserCredentialModel.password(formData.getFirst("password"))); } catch (Exception me) { user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); } diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdatePassword.java b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdatePassword.java index 7918815eec..9393d3eefa 100755 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdatePassword.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdatePassword.java @@ -21,6 +21,10 @@ import org.keycloak.Config; import org.keycloak.authentication.RequiredActionContext; import org.keycloak.authentication.RequiredActionFactory; import org.keycloak.authentication.RequiredActionProvider; +import org.keycloak.credential.CredentialModel; +import org.keycloak.credential.CredentialProvider; +import org.keycloak.credential.PasswordCredentialProvider; +import org.keycloak.credential.PasswordCredentialProviderFactory; import org.keycloak.events.Details; import org.keycloak.events.Errors; import org.keycloak.events.EventBuilder; @@ -50,22 +54,20 @@ public class UpdatePassword implements RequiredActionProvider, RequiredActionFac public void evaluateTriggers(RequiredActionContext context) { int daysToExpirePassword = context.getRealm().getPasswordPolicy().getDaysToExpirePassword(); if(daysToExpirePassword != -1) { - for (UserCredentialValueModel entity : context.getUser().getCredentialsDirectly()) { - if (entity.getType().equals(UserCredentialModel.PASSWORD)) { + PasswordCredentialProvider passwordProvider = (PasswordCredentialProvider)context.getSession().getProvider(CredentialProvider.class, PasswordCredentialProviderFactory.PROVIDER_ID); + CredentialModel password = passwordProvider.getPassword(context.getRealm(), context.getUser()); + if (password != null) { + if(password.getCreatedDate() == null) { + context.getUser().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); + logger.debug("User is required to update password"); + } else { + long timeElapsed = Time.toMillis(Time.currentTime()) - password.getCreatedDate(); + long timeToExpire = TimeUnit.DAYS.toMillis(daysToExpirePassword); - if(entity.getCreatedDate() == null) { + if(timeElapsed > timeToExpire) { context.getUser().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); logger.debug("User is required to update password"); - } else { - long timeElapsed = Time.toMillis(Time.currentTime()) - entity.getCreatedDate(); - long timeToExpire = TimeUnit.DAYS.toMillis(daysToExpirePassword); - - if(timeElapsed > timeToExpire) { - context.getUser().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD); - logger.debug("User is required to update password"); - } } - break; } } } @@ -107,7 +109,7 @@ public class UpdatePassword implements RequiredActionProvider, RequiredActionFac } try { - context.getSession().users().updateCredential(context.getRealm(), context.getUser(), UserCredentialModel.password(passwordNew)); + context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), UserCredentialModel.password(passwordNew)); context.success(); } catch (ModelException me) { errorEvent.detail(Details.REASON, me.getMessage()).error(Errors.PASSWORD_REJECTED); diff --git a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateTotp.java b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateTotp.java index 9ba9922ac3..62344bdf5a 100644 --- a/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateTotp.java +++ b/services/src/main/java/org/keycloak/authentication/requiredactions/UpdateTotp.java @@ -77,16 +77,15 @@ public class UpdateTotp implements RequiredActionProvider, RequiredActionFactory UserCredentialModel credentials = new UserCredentialModel(); credentials.setType(context.getRealm().getOTPPolicy().getType()); credentials.setValue(totpSecret); - context.getSession().users().updateCredential(context.getRealm(), context.getUser(), credentials); + context.getSession().userCredentialManager().updateCredential(context.getRealm(), context.getUser(), credentials); // if type is HOTP, to update counter we execute validation based on supplied token UserCredentialModel cred = new UserCredentialModel(); cred.setType(context.getRealm().getOTPPolicy().getType()); cred.setValue(totp); - context.getSession().users().validCredentials(context.getSession(), context.getRealm(), context.getUser(), cred); + context.getSession().userCredentialManager().isValid(context.getRealm(), context.getUser(), cred); - context.getUser().setOtpEnabled(true); context.success(); } diff --git a/services/src/main/java/org/keycloak/credential/LocalOTPCredentialManager.java b/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java similarity index 92% rename from services/src/main/java/org/keycloak/credential/LocalOTPCredentialManager.java rename to services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java index 6d9baf0345..f5c973ad45 100644 --- a/services/src/main/java/org/keycloak/credential/LocalOTPCredentialManager.java +++ b/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java @@ -17,6 +17,7 @@ package org.keycloak.credential; import org.jboss.logging.Logger; +import org.keycloak.common.util.Time; import org.keycloak.models.KeycloakSession; import org.keycloak.models.OTPPolicy; import org.keycloak.models.RealmModel; @@ -34,15 +35,15 @@ import java.util.List; * @author Bill Burke * @version $Revision: 1 $ */ -public class LocalOTPCredentialManager implements CredentialInputValidator, CredentialInputUpdater, OnUserCache { - private static final Logger logger = Logger.getLogger(LocalOTPCredentialManager.class); +public class OTPCredentialProvider implements CredentialProvider, CredentialInputValidator, CredentialInputUpdater, OnUserCache { + private static final Logger logger = Logger.getLogger(OTPCredentialProvider.class); protected KeycloakSession session; protected List getCachedCredentials(UserModel user, String type) { if (!(user instanceof CachedUserModel)) return Collections.EMPTY_LIST; CachedUserModel cached = (CachedUserModel)user; - List rtn = (List)cached.getCachedWith().get(LocalOTPCredentialManager.class.getName() + "." + type); + List rtn = (List)cached.getCachedWith().get(OTPCredentialProvider.class.getName() + "." + type); if (rtn == null) return Collections.EMPTY_LIST; return rtn; } @@ -52,13 +53,13 @@ public class LocalOTPCredentialManager implements CredentialInputValidator, Cred } @Override - public void onCache(RealmModel realm, CachedUserModel user) { + public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) { List creds = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.TOTP); - user.getCachedWith().put(LocalOTPCredentialManager.class.getName() + "." + CredentialModel.TOTP, creds); + user.getCachedWith().put(OTPCredentialProvider.class.getName() + "." + CredentialModel.TOTP, creds); } - public LocalOTPCredentialManager(KeycloakSession session) { + public OTPCredentialProvider(KeycloakSession session) { this.session = session; } @@ -88,10 +89,11 @@ public class LocalOTPCredentialManager implements CredentialInputValidator, Cred model.setDigits(policy.getDigits()); model.setCounter(policy.getInitialCounter()); model.setAlgorithm(policy.getAlgorithm()); - model.setType(policy.getType()); + model.setType(input.getType()); model.setValue(inputModel.getValue()); model.setDevice(inputModel.getDevice()); model.setPeriod(policy.getPeriod()); + model.setCreatedDate(Time.currentTimeMillis()); if (model.getId() == null) { getCredentialStore().createCredential(realm, user, model); } else { @@ -194,6 +196,10 @@ public class LocalOTPCredentialManager implements CredentialInputValidator, Cred } String token = ((UserCredentialModel)input).getValue(); + if (token == null) { + return false; + } + OTPPolicy policy = realm.getOTPPolicy(); if (realm.getOTPPolicy().getType().equals(CredentialModel.HOTP)) { HmacOTP validator = new HmacOTP(policy.getDigits(), policy.getAlgorithm(), policy.getLookAheadWindow()); diff --git a/services/src/main/java/org/keycloak/credential/OTPCredentialProviderFactory.java b/services/src/main/java/org/keycloak/credential/OTPCredentialProviderFactory.java new file mode 100644 index 0000000000..c4c6cd5edd --- /dev/null +++ b/services/src/main/java/org/keycloak/credential/OTPCredentialProviderFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright 2016 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; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class OTPCredentialProviderFactory implements CredentialProviderFactory { + public static final String PROVIDER_ID="keycloak-otp"; + @Override + public OTPCredentialProvider create(KeycloakSession session) { + return new OTPCredentialProvider(session); + } + + @Override + public String getId() { + return PROVIDER_ID; + } + +} diff --git a/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java b/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java new file mode 100644 index 0000000000..4fc58569d6 --- /dev/null +++ b/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java @@ -0,0 +1,216 @@ +/* + * Copyright 2016 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.jboss.logging.Logger; +import org.keycloak.common.util.Time; +import org.keycloak.credential.hash.PasswordHashProvider; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.ModelException; +import org.keycloak.models.PasswordPolicy; +import org.keycloak.models.RealmModel; +import org.keycloak.models.UserCredentialModel; +import org.keycloak.models.UserModel; +import org.keycloak.models.cache.CachedUserModel; +import org.keycloak.models.cache.OnUserCache; +import org.keycloak.policy.HashAlgorithmPasswordPolicyProviderFactory; +import org.keycloak.policy.PasswordPolicyManagerProvider; +import org.keycloak.policy.PolicyError; + +import java.util.Collections; +import java.util.Comparator; +import java.util.LinkedList; +import java.util.List; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class PasswordCredentialProvider implements CredentialProvider, CredentialInputValidator, CredentialInputUpdater, OnUserCache { + + public static final String PASSWORD_CACHE_KEY = PasswordCredentialProvider.class.getName() + "." + CredentialModel.PASSWORD; + private static final Logger logger = Logger.getLogger(PasswordCredentialProvider.class); + + protected KeycloakSession session; + + public PasswordCredentialProvider(KeycloakSession session) { + this.session = session; + } + + protected UserCredentialStore getCredentialStore() { + return session.userCredentialManager(); + } + + public CredentialModel getPassword(RealmModel realm, UserModel user) { + List passwords = null; + if (user instanceof CachedUserModel) { + CachedUserModel cached = (CachedUserModel)user; + passwords = (List)cached.getCachedWith().get(PASSWORD_CACHE_KEY); + + } else { + passwords = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.PASSWORD); + } + if (passwords == null || passwords.isEmpty()) return null; + return passwords.get(0); + } + + + @Override + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + if (!supportsCredentialType(input.getType())) return false; + + if (!(input instanceof UserCredentialModel)) { + logger.debug("Expected instance of UserCredentialModel for CredentialInput"); + return false; + } + UserCredentialModel cred = (UserCredentialModel)input; + PasswordPolicy policy = realm.getPasswordPolicy(); + + PolicyError error = session.getProvider(PasswordPolicyManagerProvider.class).validate(realm, user, cred.getValue()); + if (error != null) throw new ModelException(error.getMessage(), error.getParameters()); + + + PasswordHashProvider hash = getHashProvider(policy); + if (hash == null) { + return false; + } + CredentialModel oldPassword = getPassword(realm, user); + + expirePassword(realm, user, policy); + CredentialModel newPassword = new CredentialModel(); + newPassword.setType(CredentialModel.PASSWORD); + long createdDate = Time.currentTimeMillis(); + newPassword.setCreatedDate(createdDate); + hash.encode(cred.getValue(), policy, newPassword); + getCredentialStore().createCredential(realm, user, newPassword); + session.getUserCache().evict(realm, user); + return true; + } + + protected void expirePassword(RealmModel realm, UserModel user, PasswordPolicy policy) { + + CredentialModel oldPassword = getPassword(realm, user); + if (oldPassword == null) return; + int expiredPasswordsPolicyValue = policy.getExpiredPasswords(); + if (expiredPasswordsPolicyValue > -1) { + List list = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.PASSWORD_HISTORY); + List history = new LinkedList<>(); + history.addAll(list); + if (history.size() + 1 >= expiredPasswordsPolicyValue) { + Collections.sort(history, new Comparator() { + @Override + public int compare(CredentialModel o1, CredentialModel o2) { + long o1Date = o1.getCreatedDate() == null ? 0 : o1.getCreatedDate().longValue(); + long o2Date = o2.getCreatedDate() == null ? 0 : o2.getCreatedDate().longValue(); + if (o1Date > o2Date) return 1; + else if (o1Date < o2Date) return -1; + else return 0; + } + }); + for (int i = 0; i < history.size() + 2 - expiredPasswordsPolicyValue; i++) { + getCredentialStore().removeStoredCredential(realm, user, history.get(i).getId()); + } + + } + oldPassword.setType(CredentialModel.PASSWORD_HISTORY); + getCredentialStore().updateCredential(realm, user, oldPassword); + } else { + session.userCredentialManager().removeStoredCredential(realm, user, oldPassword.getId()); + } + + } + + protected PasswordHashProvider getHashProvider(PasswordPolicy policy) { + PasswordHashProvider hash = session.getProvider(PasswordHashProvider.class, policy.getHashAlgorithm()); + if (hash == null) { + logger.warnv("Realm PasswordPolicy PasswordHashProvider {0} not found", policy.getHashAlgorithm()); + return session.getProvider(PasswordHashProvider.class, HashAlgorithmPasswordPolicyProviderFactory.DEFAULT_VALUE); + } + return hash; + } + + @Override + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + if (!supportsCredentialType(credentialType)) return; + PasswordPolicy policy = realm.getPasswordPolicy(); + expirePassword(realm, user, policy); + } + + @Override + public boolean supportsCredentialType(String credentialType) { + return credentialType.equals(CredentialModel.PASSWORD); + } + + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + return getPassword(realm, user) != null; + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (! (input instanceof UserCredentialModel)) { + logger.debug("Expected instance of UserCredentialModel for CredentialInput"); + return false; + + } + UserCredentialModel cred = (UserCredentialModel)input; + if (cred.getValue() == null) { + logger.debugv("Input password was null for user {0} ", user.getUsername()); + return false; + } + CredentialModel password = getPassword(realm, user); + if (password == null) { + logger.debugv("No password cached or stored for user {0} ", user.getUsername()); + return false; + } + PasswordHashProvider hash = session.getProvider(PasswordHashProvider.class, password.getAlgorithm()); + if (hash == null) { + logger.debugv("PasswordHashProvider {0} not found for user {1} ", password.getAlgorithm(), user.getUsername()); + return false; + } + if (!hash.verify(cred.getValue(), password)) { + logger.debugv("Failed password validation for user {0} ", user.getUsername()); + return false; + } + PasswordPolicy policy = realm.getPasswordPolicy(); + if (policy == null) { + return true; + } + hash = getHashProvider(policy); + if (hash == null) { + return true; + } + if (hash.policyCheck(policy, password)) { + return true; + } + + hash.encode(cred.getValue(), policy, password); + getCredentialStore().updateCredential(realm, user, password); + session.getUserCache().evict(realm, user); + + return true; + } + + @Override + public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) { + List passwords = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.PASSWORD); + if (passwords != null) { + user.getCachedWith().put(PASSWORD_CACHE_KEY, passwords); + } + + } +} diff --git a/services/src/main/java/org/keycloak/credential/PasswordCredentialProviderFactory.java b/services/src/main/java/org/keycloak/credential/PasswordCredentialProviderFactory.java new file mode 100644 index 0000000000..b9aace8c57 --- /dev/null +++ b/services/src/main/java/org/keycloak/credential/PasswordCredentialProviderFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright 2016 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; + +/** + * @author Bill Burke + * @version $Revision: 1 $ + */ +public class PasswordCredentialProviderFactory implements CredentialProviderFactory { + public static final String PROVIDER_ID="keycloak-password"; + @Override + public PasswordCredentialProvider create(KeycloakSession session) { + return new PasswordCredentialProvider(session); + } + + @Override + public String getId() { + return PROVIDER_ID; + } + +} diff --git a/services/src/main/java/org/keycloak/credential/UserCredentialStoreManager.java b/services/src/main/java/org/keycloak/credential/UserCredentialStoreManager.java index 5f67768378..fab312774a 100644 --- a/services/src/main/java/org/keycloak/credential/UserCredentialStoreManager.java +++ b/services/src/main/java/org/keycloak/credential/UserCredentialStoreManager.java @@ -22,17 +22,24 @@ import org.keycloak.component.PrioritizedComponentModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserCredentialManager; +import org.keycloak.models.UserCredentialModel; +import org.keycloak.models.UserFederationProvider; +import org.keycloak.models.UserFederationProviderModel; import org.keycloak.models.UserModel; import org.keycloak.models.cache.CachedUserModel; import org.keycloak.models.cache.OnUserCache; +import org.keycloak.models.utils.KeycloakModelUtils; +import org.keycloak.provider.ProviderFactory; import org.keycloak.storage.StorageId; import org.keycloak.storage.UserStorageManager; import org.keycloak.storage.UserStorageProvider; +import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; +import java.util.Set; /** * @author Bill Burke @@ -89,6 +96,10 @@ public class UserCredentialStoreManager implements UserCredentialManager, OnUser return getStoreForUser(user).getStoredCredentialByNameAndType(realm, user, name, type); } + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput... inputs) { + return isValid(realm, user, Arrays.asList(inputs)); + } @Override public boolean isValid(RealmModel realm, UserModel user, List inputs) { @@ -108,38 +119,47 @@ public class UserCredentialStoreManager implements UserCredentialManager, OnUser } } } + } else { + // + UserFederationProvider link = session.users().getFederationLink(realm, user); + if (link != null) { + session.users().validateUser(realm, user); + Iterator it = toValidate.iterator(); + while (it.hasNext()) { + CredentialInput input = it.next(); + if (link.supportsCredentialType(input.getType()) + && link.isValid(realm, user, input)) { + it.remove(); + } + } + } + // } if (toValidate.isEmpty()) return true; - List components = getCredentialProviderComponents(realm); - for (ComponentModel component : components) { - CredentialProviderFactory factory = (CredentialProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(CredentialProvider.class, component.getProviderId()); - if (!Types.supports(CredentialInputValidator.class, factory, CredentialProviderFactory.class)) continue; + List credentialProviders = getCredentialProviders(realm, CredentialInputValidator.class); + for (CredentialInputValidator validator : credentialProviders) { Iterator it = toValidate.iterator(); while (it.hasNext()) { CredentialInput input = it.next(); - CredentialInputValidator validator = (CredentialInputValidator)session.getAttribute(component.getId()); - if (validator == null) { - validator = (CredentialInputValidator)factory.create(session, component); - session.setAttribute(component.getId(), validator); - } if (validator.supportsCredentialType(input.getType()) && validator.isValid(realm, user, input)) { it.remove(); } } - } + } return toValidate.isEmpty(); } - protected List getCredentialProviderComponents(RealmModel realm) { - List components = realm.getComponents(realm.getId(), CredentialProvider.class.getName()); - if (components.isEmpty()) return components; - List copy = new LinkedList<>(); - copy.addAll(components); - Collections.sort(copy, PrioritizedComponentModel.comparator); - return copy; + protected List getCredentialProviders(RealmModel realm, Class type) { + List list = new LinkedList(); + for (ProviderFactory f : session.getKeycloakSessionFactory().getProviderFactories(CredentialProvider.class)) { + if (!Types.supports(CredentialInputUpdater.class, f, CredentialProviderFactory.class)) continue; + list.add((T)session.getProvider(CredentialProvider.class, f.getId())); + } + return list; + } @Override @@ -153,21 +173,21 @@ public class UserCredentialStoreManager implements UserCredentialManager, OnUser if (updater.updateCredential(realm, user, input)) return; } } + } else { + // + UserFederationProvider link = session.users().getFederationLink(realm, user); + if (link != null) { + if (link.updateCredential(realm, user, input)) return; + } + // } - List components = getCredentialProviderComponents(realm); - for (ComponentModel component : components) { - CredentialProviderFactory factory = (CredentialProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(CredentialProvider.class, component.getProviderId()); - if (!Types.supports(CredentialInputUpdater.class, factory, CredentialProviderFactory.class)) continue; - CredentialInputUpdater updater = (CredentialInputUpdater)session.getAttribute(component.getId()); - if (updater == null) { - updater = (CredentialInputUpdater)factory.create(session, component); - session.setAttribute(component.getId(), updater); - } + List credentialProviders = getCredentialProviders(realm, CredentialInputUpdater.class); + for (CredentialInputUpdater updater : credentialProviders) { if (!updater.supportsCredentialType(input.getType())) continue; if (updater.updateCredential(realm, user, input)) return; - } + } } @Override public void disableCredential(RealmModel realm, UserModel user, String credentialType) { @@ -180,21 +200,22 @@ public class UserCredentialStoreManager implements UserCredentialManager, OnUser updater.disableCredentialType(realm, user, credentialType); } } + } else { + UserFederationProvider link = session.users().getFederationLink(realm, user); + if (link != null && link.getSupportedCredentialTypes().contains(credentialType)) { + link.disableCredentialType(realm, user, credentialType); + } + } - List components = getCredentialProviderComponents(realm); - for (ComponentModel component : components) { - CredentialProviderFactory factory = (CredentialProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(CredentialProvider.class, component.getProviderId()); - if (!Types.supports(CredentialInputUpdater.class, factory, CredentialProviderFactory.class)) continue; - CredentialInputUpdater updater = (CredentialInputUpdater)session.getAttribute(component.getId()); - if (updater == null) { - updater = (CredentialInputUpdater)factory.create(session, component); - session.setAttribute(component.getId(), updater); - } + List credentialProviders = getCredentialProviders(realm, CredentialInputUpdater.class); + for (CredentialInputUpdater updater : credentialProviders) { if (!updater.supportsCredentialType(credentialType)) continue; updater.disableCredentialType(realm, user, credentialType); + } + } @Override public boolean isConfiguredFor(RealmModel realm, UserModel user, String type) { @@ -207,39 +228,37 @@ public class UserCredentialStoreManager implements UserCredentialManager, OnUser return true; } } + } else { + // + UserFederationProvider link = session.users().getFederationLink(realm, user); + if (link != null) { + if (link.isConfiguredFor(realm, user, type)) return true; + } + // + } - List components = getCredentialProviderComponents(realm); - for (ComponentModel component : components) { - CredentialProviderFactory factory = (CredentialProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(CredentialProvider.class, component.getProviderId()); - if (!Types.supports(CredentialInputUpdater.class, factory, CredentialProviderFactory.class)) continue; - CredentialInputValidator validator = (CredentialInputValidator)session.getAttribute(component.getId()); - if (validator == null) { - validator = (CredentialInputValidator)factory.create(session, component); - session.setAttribute(component.getId(), validator); - } - if (validator.supportsCredentialType(type) && validator.isConfiguredFor(realm, user, type)) { - return true; - } - } - return false; - + return isConfiguredLocally(realm, user, type); } @Override - public void onCache(RealmModel realm, CachedUserModel user) { - List components = getCredentialProviderComponents(realm); - for (ComponentModel component : components) { - CredentialProviderFactory factory = (CredentialProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(CredentialProvider.class, component.getProviderId()); - if (!Types.supports(OnUserCache.class, factory, CredentialProviderFactory.class)) continue; - OnUserCache validator = (OnUserCache)session.getAttribute(component.getId()); - if (validator == null) { - validator = (OnUserCache)factory.create(session, component); - session.setAttribute(component.getId(), validator); + public boolean isConfiguredLocally(RealmModel realm, UserModel user, String type) { + List credentialProviders = getCredentialProviders(realm, CredentialInputValidator.class); + for (CredentialInputValidator validator : credentialProviders) { + if (validator.supportsCredentialType(type) && validator.isConfiguredFor(realm, user, type)) { + return true; } - validator.onCache(realm, user); - } + } + return false; + } + + @Override + public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) { + List credentialProviders = getCredentialProviders(realm, OnUserCache.class); + for (OnUserCache validator : credentialProviders) { + validator.onCache(realm, user, delegate); + } } @Override diff --git a/services/src/main/java/org/keycloak/credential/hash/Pbkdf2PasswordHashProvider.java b/services/src/main/java/org/keycloak/credential/hash/Pbkdf2PasswordHashProvider.java new file mode 100644 index 0000000000..d3d9b60fe0 --- /dev/null +++ b/services/src/main/java/org/keycloak/credential/hash/Pbkdf2PasswordHashProvider.java @@ -0,0 +1,138 @@ +/* + * Copyright 2016 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.hash; + +import org.keycloak.Config; +import org.keycloak.common.util.Base64; +import org.keycloak.credential.CredentialModel; +import org.keycloak.credential.hash.PasswordHashProvider; +import org.keycloak.credential.hash.PasswordHashProviderFactory; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.models.PasswordPolicy; +import org.keycloak.models.UserCredentialModel; +import org.keycloak.models.UserCredentialValueModel; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; + +/** + * @author Kunal Kerkar + */ +public class Pbkdf2PasswordHashProvider implements PasswordHashProviderFactory, PasswordHashProvider { + + public static final String ID = "pbkdf2"; + + private static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1"; + private static final int DERIVED_KEY_SIZE = 512; + + public UserCredentialValueModel encode(String rawPassword, int iterations) { + byte[] salt = getSalt(); + String encodedPassword = encode(rawPassword, iterations, salt); + + UserCredentialValueModel credentials = new UserCredentialValueModel(); + credentials.setAlgorithm(ID); + credentials.setType(UserCredentialModel.PASSWORD); + credentials.setSalt(salt); + credentials.setHashIterations(iterations); + credentials.setValue(encodedPassword); + return credentials; + } + + public boolean verify(String rawPassword, UserCredentialValueModel credential) { + return encode(rawPassword, credential.getHashIterations(), credential.getSalt()).equals(credential.getValue()); + } + + @Override + public boolean policyCheck(PasswordPolicy policy, CredentialModel credential) { + return credential.getHashIterations() == policy.getHashIterations() && ID.equals(credential.getAlgorithm()); + } + + @Override + public void encode(String rawPassword, PasswordPolicy policy, CredentialModel credential) { + byte[] salt = getSalt(); + String encodedPassword = encode(rawPassword, policy.getHashIterations(), salt); + + credential.setAlgorithm(ID); + credential.setType(UserCredentialModel.PASSWORD); + credential.setSalt(salt); + credential.setHashIterations(policy.getHashIterations()); + credential.setValue(encodedPassword); + + } + + @Override + public boolean verify(String rawPassword, CredentialModel credential) { + return encode(rawPassword, credential.getHashIterations(), credential.getSalt()).equals(credential.getValue()); + } + + @Override + public PasswordHashProvider create(KeycloakSession session) { + return this; + } + + @Override + public void init(Config.Scope config) { + } + + @Override + public void postInit(KeycloakSessionFactory factory) { + } + + public void close() { + } + + @Override + public String getId() { + return ID; + } + + private String encode(String rawPassword, int iterations, byte[] salt) { + KeySpec spec = new PBEKeySpec(rawPassword.toCharArray(), salt, iterations, DERIVED_KEY_SIZE); + + try { + byte[] key = getSecretKeyFactory().generateSecret(spec).getEncoded(); + return Base64.encodeBytes(key); + } catch (InvalidKeySpecException e) { + throw new RuntimeException("Credential could not be encoded", e); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + private byte[] getSalt() { + byte[] buffer = new byte[16]; + SecureRandom secureRandom = new SecureRandom(); + secureRandom.nextBytes(buffer); + return buffer; + } + + private SecretKeyFactory getSecretKeyFactory() { + try { + return SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("PBKDF2 algorithm not found", e); + } + } + +} diff --git a/services/src/main/java/org/keycloak/exportimport/util/ExportUtils.java b/services/src/main/java/org/keycloak/exportimport/util/ExportUtils.java index 1b2caf946e..598b8e21fa 100755 --- a/services/src/main/java/org/keycloak/exportimport/util/ExportUtils.java +++ b/services/src/main/java/org/keycloak/exportimport/util/ExportUtils.java @@ -34,6 +34,7 @@ import org.keycloak.common.Version; import org.keycloak.common.util.Base64; import org.keycloak.common.util.MultivaluedHashMap; import org.keycloak.component.ComponentModel; +import org.keycloak.credential.CredentialModel; import org.keycloak.models.ClientModel; import org.keycloak.models.ClientTemplateModel; import org.keycloak.models.FederatedIdentityModel; @@ -458,7 +459,7 @@ public class ExportUtils { * @return fully exported user representation */ public static UserRepresentation exportUser(KeycloakSession session, RealmModel realm, UserModel user) { - UserRepresentation userRep = ModelToRepresentation.toRepresentation(user); + UserRepresentation userRep = ModelToRepresentation.toRepresentation(session, realm, user); // Social links Set socialLinks = session.users().getFederatedIdentities(user, realm); @@ -499,9 +500,9 @@ public class ExportUtils { } // Credentials - List creds = user.getCredentialsDirectly(); + List creds = session.userCredentialManager().getStoredCredentials(realm, user); List credReps = new ArrayList(); - for (UserCredentialValueModel cred : creds) { + for (CredentialModel cred : creds) { CredentialRepresentation credRep = exportCredential(cred); credReps.add(credRep); } @@ -545,7 +546,7 @@ public class ExportUtils { return socialLinkRep; } - public static CredentialRepresentation exportCredential(UserCredentialValueModel userCred) { + public static CredentialRepresentation exportCredential(CredentialModel userCred) { CredentialRepresentation credRep = new CredentialRepresentation(); credRep.setType(userCred.getType()); credRep.setDevice(userCred.getDevice()); @@ -556,6 +557,7 @@ public class ExportUtils { credRep.setAlgorithm(userCred.getAlgorithm()); credRep.setDigits(userCred.getDigits()); credRep.setCreatedDate(userCred.getCreatedDate()); + credRep.setConfig(userCred.getConfig()); return credRep; } diff --git a/services/src/main/java/org/keycloak/forms/account/freemarker/model/TotpBean.java b/services/src/main/java/org/keycloak/forms/account/freemarker/model/TotpBean.java index 197f98558e..d90f21e89c 100644 --- a/services/src/main/java/org/keycloak/forms/account/freemarker/model/TotpBean.java +++ b/services/src/main/java/org/keycloak/forms/account/freemarker/model/TotpBean.java @@ -41,7 +41,7 @@ public class TotpBean { private final boolean enabled; public TotpBean(KeycloakSession session, RealmModel realm, UserModel user) { - this.enabled = session.users().configuredForCredentialType(realm.getOTPPolicy().getType(), realm, user); + this.enabled = session.userCredentialManager().isConfiguredFor(realm, user, realm.getOTPPolicy().getType()); this.totpSecret = HmacOTP.generateSecret(20); this.totpSecretEncoded = TotpUtils.encode(totpSecret); diff --git a/services/src/main/java/org/keycloak/forms/login/freemarker/FreeMarkerLoginFormsProvider.java b/services/src/main/java/org/keycloak/forms/login/freemarker/FreeMarkerLoginFormsProvider.java index 44ee44d77d..631ff5792e 100755 --- a/services/src/main/java/org/keycloak/forms/login/freemarker/FreeMarkerLoginFormsProvider.java +++ b/services/src/main/java/org/keycloak/forms/login/freemarker/FreeMarkerLoginFormsProvider.java @@ -279,7 +279,7 @@ public class FreeMarkerLoginFormsProvider implements LoginFormsProvider { switch (page) { case LOGIN_CONFIG_TOTP: - attributes.put("totp", new TotpBean(realm, user)); + attributes.put("totp", new TotpBean(session, realm, user)); break; case LOGIN_UPDATE_PROFILE: UpdateProfileContext userCtx = (UpdateProfileContext) attributes.get(LoginFormsProvider.UPDATE_PROFILE_CONTEXT_ATTR); diff --git a/services/src/main/java/org/keycloak/forms/login/freemarker/model/TotpBean.java b/services/src/main/java/org/keycloak/forms/login/freemarker/model/TotpBean.java index d1e1d9ce45..c302533d18 100755 --- a/services/src/main/java/org/keycloak/forms/login/freemarker/model/TotpBean.java +++ b/services/src/main/java/org/keycloak/forms/login/freemarker/model/TotpBean.java @@ -16,6 +16,8 @@ */ package org.keycloak.forms.login.freemarker.model; +import org.keycloak.credential.CredentialModel; +import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.models.utils.Base32; @@ -36,9 +38,8 @@ public class TotpBean { private final String totpSecretQrCode; private final boolean enabled; - public TotpBean(RealmModel realm, UserModel user) { - this.enabled = user.isOtpEnabled(); - + public TotpBean(KeycloakSession session, RealmModel realm, UserModel user) { + this.enabled = session.userCredentialManager().isConfiguredFor(realm, user, CredentialModel.OTP); this.totpSecret = HmacOTP.generateSecret(20); this.totpSecretEncoded = TotpUtils.encode(totpSecret); this.totpSecretQrCode = TotpUtils.qrCode(totpSecret, realm, user); diff --git a/services/src/main/java/org/keycloak/protocol/saml/profile/ecp/authenticator/HttpBasicAuthenticator.java b/services/src/main/java/org/keycloak/protocol/saml/profile/ecp/authenticator/HttpBasicAuthenticator.java index 7daf470e4a..d1404c2b95 100755 --- a/services/src/main/java/org/keycloak/protocol/saml/profile/ecp/authenticator/HttpBasicAuthenticator.java +++ b/services/src/main/java/org/keycloak/protocol/saml/profile/ecp/authenticator/HttpBasicAuthenticator.java @@ -97,7 +97,7 @@ public class HttpBasicAuthenticator implements AuthenticatorFactory { if (user != null) { String password = usernameAndPassword[1]; - boolean valid = context.getSession().users().validCredentials(context.getSession(), realm, user, UserCredentialModel.password(password)); + boolean valid = context.getSession().userCredentialManager().isValid(realm, user, UserCredentialModel.password(password)); if (valid) { context.getClientSession().setAuthenticatedUser(user); diff --git a/services/src/main/java/org/keycloak/services/DefaultKeycloakSessionFactory.java b/services/src/main/java/org/keycloak/services/DefaultKeycloakSessionFactory.java index 36f9b7f163..808b4133cc 100755 --- a/services/src/main/java/org/keycloak/services/DefaultKeycloakSessionFactory.java +++ b/services/src/main/java/org/keycloak/services/DefaultKeycloakSessionFactory.java @@ -136,6 +136,7 @@ public class DefaultKeycloakSessionFactory implements KeycloakSessionFactory, Pr @Override public void undeploy(ProviderManager pm) { + logger.debug("undeploy"); // we make a copy to avoid concurrent access exceptions Map, Map> copy = getFactoriesCopy(); MultivaluedHashMap, ProviderFactory> factories = pm.getLoadedFactories(); @@ -144,6 +145,7 @@ public class DefaultKeycloakSessionFactory implements KeycloakSessionFactory, Pr Map registered = copy.get(entry.getKey()); for (ProviderFactory factory : entry.getValue()) { undeployed.add(factory); + logger.debugv("undeploying {0} of id {1}", factory.getClass().getName(), factory.getId()); if (registered != null) { registered.remove(factory.getId()); } diff --git a/services/src/main/java/org/keycloak/services/ServicesLogger.java b/services/src/main/java/org/keycloak/services/ServicesLogger.java index 0595abbcce..0d58f2da06 100644 --- a/services/src/main/java/org/keycloak/services/ServicesLogger.java +++ b/services/src/main/java/org/keycloak/services/ServicesLogger.java @@ -97,7 +97,7 @@ public interface ServicesLogger extends BasicLogger { @Message(id=12, value="Failed to delete '%s'") void failedToDeleteFile(String fileName); - @LogMessage(level = DEBUG) + @LogMessage(level = WARN) @Message(id=13, value="Failed authentication") void failedAuthentication(@Cause Throwable t); diff --git a/services/src/main/java/org/keycloak/services/managers/ApplianceBootstrap.java b/services/src/main/java/org/keycloak/services/managers/ApplianceBootstrap.java index 356922e430..9d374a2416 100755 --- a/services/src/main/java/org/keycloak/services/managers/ApplianceBootstrap.java +++ b/services/src/main/java/org/keycloak/services/managers/ApplianceBootstrap.java @@ -96,7 +96,7 @@ public class ApplianceBootstrap { UserCredentialModel usrCredModel = new UserCredentialModel(); usrCredModel.setType(UserCredentialModel.PASSWORD); usrCredModel.setValue(password); - session.users().updateCredential(realm, adminUser, usrCredModel); + session.userCredentialManager().updateCredential(realm, adminUser, usrCredModel); RoleModel adminRole = realm.getRole(AdminRoles.ADMIN); adminUser.grantRole(adminRole); diff --git a/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java b/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java index aa536f5fca..b188501d7c 100755 --- a/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java +++ b/services/src/main/java/org/keycloak/services/managers/AuthenticationManager.java @@ -570,6 +570,10 @@ public class AuthenticationManager { Set requiredActions) { for (String action : requiredActions) { RequiredActionProviderModel model = realm.getRequiredActionProviderByAlias(action); + if (model == null) { + logger.warnv("Could not find configuration for Required Action {0}, did you forget to register it?", action); + continue; + } if (!model.isEnabled()) { continue; } diff --git a/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtector.java b/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtector.java index 28fc29d308..2e809d1b12 100644 --- a/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtector.java +++ b/services/src/main/java/org/keycloak/services/managers/DefaultBruteForceProtector.java @@ -18,6 +18,7 @@ package org.keycloak.services.managers; import org.keycloak.common.ClientConnection; +import org.keycloak.common.util.Time; import org.keycloak.models.KeycloakSession; import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.models.RealmModel; @@ -52,7 +53,6 @@ public class DefaultBruteForceProtector implements Runnable, BruteForceProtector protected LinkedBlockingQueue queue = new LinkedBlockingQueue(); public static final int TRANSACTION_SIZE = 20; - protected abstract class LoginEvent implements Comparable { protected final String realmId; protected final String userId; @@ -92,14 +92,16 @@ public class DefaultBruteForceProtector implements Runnable, BruteForceProtector logger.debug("failure"); RealmModel realm = getRealmModel(session, event); logFailure(event); - UserModel user = session.users().getUserById(event.userId, realm); + + String userId = event.userId; + UserModel user = session.users().getUserById(userId, realm); UserLoginFailureModel userLoginFailure = getUserModel(session, event); if (user != null) { if (userLoginFailure == null) { - userLoginFailure = session.sessions().addUserLoginFailure(realm, event.userId); + userLoginFailure = session.sessions().addUserLoginFailure(realm, userId); } userLoginFailure.setLastIPFailure(event.ip); - long currentTime = System.currentTimeMillis(); + long currentTime = Time.currentTimeMillis(); long last = userLoginFailure.getLastFailure(); long deltaTime = 0; if (last > 0) { @@ -115,7 +117,7 @@ public class DefaultBruteForceProtector implements Runnable, BruteForceProtector userLoginFailure.incrementFailures(); logger.debugv("new num failures: {0}", userLoginFailure.getNumFailures()); - int waitSeconds = realm.getWaitIncrementSeconds() * (userLoginFailure.getNumFailures() / realm.getFailureFactor()); + int waitSeconds = realm.getWaitIncrementSeconds() * (userLoginFailure.getNumFailures() / realm.getFailureFactor()); logger.debugv("waitSeconds: {0}", waitSeconds); logger.debugv("deltaTime: {0}", deltaTime); @@ -216,7 +218,7 @@ public class DefaultBruteForceProtector implements Runnable, BruteForceProtector failures++; long delta = 0; if (lastFailure > 0) { - delta = System.currentTimeMillis() - lastFailure; + delta = Time.currentTimeMillis() - lastFailure; if (delta > (long)maxDeltaTimeSeconds * 1000L) { totalTime = 0; @@ -235,9 +237,9 @@ public class DefaultBruteForceProtector implements Runnable, BruteForceProtector // cannot flood with failed logins and overwhelm the queue and not have notBefore updated to block next requests // todo failure HTTP responses should be queued via async HTTP event.latch.await(5, TimeUnit.SECONDS); - } catch (InterruptedException e) { } + logger.trace("sent failure event"); } @Override @@ -245,16 +247,17 @@ public class DefaultBruteForceProtector implements Runnable, BruteForceProtector UserLoginFailureModel failure = session.sessions().getUserLoginFailure(realm, user.getId()); if (failure != null) { - int currTime = (int) (System.currentTimeMillis() / 1000); - if (currTime < failure.getFailedLoginNotBefore()) { - logger.debugv("Current: {0} notBefore: {1}", currTime, failure.getFailedLoginNotBefore()); + int currTime = (int) (Time.currentTimeMillis() / 1000); + int failedLoginNotBefore = failure.getFailedLoginNotBefore(); + if (currTime < failedLoginNotBefore) { + logger.debugv("Current: {0} notBefore: {1}", currTime, failedLoginNotBefore); return true; } } + return false; } - @Override public void close() { diff --git a/services/src/main/java/org/keycloak/services/resources/AccountService.java b/services/src/main/java/org/keycloak/services/resources/AccountService.java index bf6fb885ed..36f643f27c 100755 --- a/services/src/main/java/org/keycloak/services/resources/AccountService.java +++ b/services/src/main/java/org/keycloak/services/resources/AccountService.java @@ -16,6 +16,8 @@ */ package org.keycloak.services.resources; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialModel; import org.keycloak.events.Errors; import org.keycloak.forms.account.AccountPages; import org.keycloak.forms.account.AccountProvider; @@ -81,6 +83,7 @@ import java.lang.reflect.Method; import java.net.URI; import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -270,7 +273,7 @@ public class AccountService extends AbstractSecuredLocalService { } else if (types.contains(MediaType.APPLICATION_JSON_TYPE)) { requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_PROFILE); - UserRepresentation rep = ModelToRepresentation.toRepresentation(auth.getUser()); + UserRepresentation rep = ModelToRepresentation.toRepresentation(session, realm, auth.getUser()); if (rep.getAttributes() != null) { Iterator itr = rep.getAttributes().keySet().iterator(); while (itr.hasNext()) { @@ -444,7 +447,7 @@ public class AccountService extends AbstractSecuredLocalService { csrfCheck(stateChecker); UserModel user = auth.getUser(); - user.setOtpEnabled(false); + session.userCredentialManager().disableCredential(realm, user, CredentialModel.OTP); event.event(EventType.REMOVE_TOTP).client(auth.getClient()).user(auth.getUser()).success(); @@ -564,15 +567,13 @@ public class AccountService extends AbstractSecuredLocalService { UserCredentialModel credentials = new UserCredentialModel(); credentials.setType(realm.getOTPPolicy().getType()); credentials.setValue(totpSecret); - session.users().updateCredential(realm, user, credentials); - - user.setOtpEnabled(true); + session.userCredentialManager().updateCredential(realm, user, credentials); // to update counter UserCredentialModel cred = new UserCredentialModel(); cred.setType(realm.getOTPPolicy().getType()); cred.setValue(totp); - session.users().validCredentials(session, realm, user, cred); + session.userCredentialManager().isValid(realm, user, cred); event.event(EventType.UPDATE_TOTP).client(auth.getClient()).user(auth.getUser()).success(); @@ -624,7 +625,7 @@ public class AccountService extends AbstractSecuredLocalService { } UserCredentialModel cred = UserCredentialModel.password(password); - if (!session.users().validCredentials(session, realm, user, cred)) { + if (!session.userCredentialManager().isValid(realm, user, cred)) { setReferrerOnPage(); errorEvent.error(Errors.INVALID_USER_CREDENTIALS); return account.setError(Messages.INVALID_PASSWORD_EXISTING).createResponse(AccountPages.PASSWORD); @@ -644,7 +645,7 @@ public class AccountService extends AbstractSecuredLocalService { } try { - session.users().updateCredential(realm, user, UserCredentialModel.password(passwordNew)); + session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(passwordNew)); } catch (ModelReadOnlyException mre) { setReferrerOnPage(); errorEvent.error(Errors.NOT_ALLOWED); @@ -774,32 +775,7 @@ public class AccountService extends AbstractSecuredLocalService { } public static boolean isPasswordSet(KeycloakSession session, RealmModel realm, UserModel user) { - boolean passwordSet = false; - - // See if password is set for user on linked UserFederationProvider - if (user.getFederationLink() != null) { - - UserFederationProvider federationProvider = null; - for (UserFederationProviderModel fedProviderModel : realm.getUserFederationProviders()) { - if (fedProviderModel.getId().equals(user.getFederationLink())) { - federationProvider = KeycloakModelUtils.getFederationProviderInstance(session, fedProviderModel); - } - } - - if (federationProvider != null) { - Set supportedCreds = federationProvider.getSupportedCredentialTypes(user); - if (supportedCreds.contains(UserCredentialModel.PASSWORD)) { - passwordSet = true; - } - } - } - - for (UserCredentialValueModel c : user.getCredentialsDirectly()) { - if (c.getType().equals(CredentialRepresentation.PASSWORD)) { - passwordSet = true; - } - } - return passwordSet; + return session.userCredentialManager().isConfiguredFor(realm, user, CredentialModel.PASSWORD); } private String[] getReferrer() { diff --git a/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java b/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java index 68e080663b..1e7c0b7024 100644 --- a/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java +++ b/services/src/main/java/org/keycloak/services/resources/KeycloakApplication.java @@ -405,7 +405,7 @@ public class KeycloakApplication extends Application { } else { UserModel user = session.users().addUser(realm, userRep.getUsername()); user.setEnabled(userRep.isEnabled()); - RepresentationToModel.createCredentials(userRep, user); + RepresentationToModel.createCredentials(userRep, session, realm, user); RepresentationToModel.createRoleMappings(userRep, user, realm); } diff --git a/services/src/main/java/org/keycloak/services/resources/admin/ClientResource.java b/services/src/main/java/org/keycloak/services/resources/admin/ClientResource.java index 955dff0144..5095c394eb 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/ClientResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/ClientResource.java @@ -343,7 +343,7 @@ public class ClientResource { } } - return ModelToRepresentation.toRepresentation(user); + return ModelToRepresentation.toRepresentation(session, realm, user); } /** diff --git a/services/src/main/java/org/keycloak/services/resources/admin/GroupResource.java b/services/src/main/java/org/keycloak/services/resources/admin/GroupResource.java index e3cc87fb8b..11cb56760e 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/GroupResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/GroupResource.java @@ -218,7 +218,7 @@ public class GroupResource { List userModels = session.users().getGroupMembers(realm, group, firstResult, maxResults); for (UserModel user : userModels) { - results.add(ModelToRepresentation.toRepresentation(user)); + results.add(ModelToRepresentation.toRepresentation(session, realm, user)); } return results; } diff --git a/services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java b/services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java index 26daf84019..4b136591ce 100755 --- a/services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java +++ b/services/src/main/java/org/keycloak/services/resources/admin/UsersResource.java @@ -22,6 +22,7 @@ import org.jboss.resteasy.spi.NotFoundException; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.keycloak.common.ClientConnection; import org.keycloak.authentication.RequiredActionProvider; +import org.keycloak.credential.CredentialModel; import org.keycloak.email.EmailException; import org.keycloak.email.EmailTemplateProvider; import org.keycloak.events.Details; @@ -245,7 +246,6 @@ public class UsersResource { if (rep.getLastName() != null) user.setLastName(rep.getLastName()); if (rep.isEnabled() != null) user.setEnabled(rep.isEnabled()); - if (rep.isTotp() != null) user.setOtpEnabled(rep.isTotp()); if (rep.isEmailVerified() != null) user.setEmailVerified(rep.isEmailVerified()); List reqActions = rep.getRequiredActions(); @@ -293,7 +293,7 @@ public class UsersResource { throw new NotFoundException("User not found"); } - UserRepresentation rep = ModelToRepresentation.toRepresentation(user); + UserRepresentation rep = ModelToRepresentation.toRepresentation(session, realm, user); if (realm.isIdentityFederationEnabled()) { List reps = getFederatedIdentities(user); @@ -692,7 +692,7 @@ public class UsersResource { } for (UserModel user : userModels) { - results.add(ModelToRepresentation.toRepresentation(user)); + results.add(ModelToRepresentation.toRepresentation(session, realm, user)); } return results; } @@ -746,7 +746,7 @@ public class UsersResource { UserCredentialModel cred = RepresentationToModel.convertCredential(pass); try { - session.users().updateCredential(realm, user, cred); + session.userCredentialManager().updateCredential(realm, user, cred); } catch (IllegalStateException ise) { throw new BadRequestException("Resetting to N old passwords is not allowed."); } catch (ModelReadOnlyException mre) { @@ -777,7 +777,7 @@ public class UsersResource { throw new NotFoundException("User not found"); } - user.setOtpEnabled(false); + session.userCredentialManager().disableCredential(realm, user, CredentialModel.OTP); adminEvent.operation(OperationType.ACTION).resourcePath(uriInfo).success(); } diff --git a/services/src/main/java/org/keycloak/storage/UserStorageManager.java b/services/src/main/java/org/keycloak/storage/UserStorageManager.java index 226a083fd8..8da231ede5 100755 --- a/services/src/main/java/org/keycloak/storage/UserStorageManager.java +++ b/services/src/main/java/org/keycloak/storage/UserStorageManager.java @@ -34,15 +34,12 @@ import org.keycloak.models.cache.CachedUserModel; import org.keycloak.models.cache.OnUserCache; import org.keycloak.storage.user.UserCredentialAuthenticationProvider; import org.keycloak.models.UserCredentialModel; -import org.keycloak.storage.user.UserCredentialValidatorProvider; -import org.keycloak.models.UserCredentialValueModel; import org.keycloak.models.UserFederationProviderModel; import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.models.UserModel; import org.keycloak.models.UserProvider; import org.keycloak.storage.user.UserQueryProvider; import org.keycloak.storage.user.UserRegistrationProvider; -import org.keycloak.models.utils.CredentialValidation; import org.keycloak.storage.federated.UserFederatedStorageProvider; import java.util.Arrays; @@ -532,52 +529,6 @@ public class UserStorageManager implements UserProvider, OnUserCache { if (getFederatedStorage() != null) getFederatedStorage().preRemove(protocolMapper); } - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List input) { - if (StorageId.isLocalStorage(user)) { - return localStorage().validCredentials(session, realm, user, input); - } - // make sure we hit the cache here! - List userCreds = user.getCredentialsDirectly(); - - LinkedList toValidate = new LinkedList<>(); - toValidate.addAll(input); - Iterator it = toValidate.iterator(); - boolean failedStoredCredential = false; - // we allow for multiple credentials of same type, i.e. multiple OTP devices - while (it.hasNext()) { - UserCredentialModel cred = it.next(); - boolean credValidated = false; - for (UserCredentialValueModel userCred : userCreds) { - if (!userCred.getType().equals(cred.getType())) continue; - if (CredentialValidation.validCredential(session, realm, user, cred)) { - credValidated = true; - break; - } else { - failedStoredCredential = true; - } - } - if (credValidated) { - it.remove(); - } else if (failedStoredCredential) { - return false; - } - } - - if (toValidate.isEmpty()) return true; - - UserStorageProvider provider = getStorageProvider(session, realm, StorageId.resolveProviderId(user)); - if (!(provider instanceof UserCredentialValidatorProvider)) { - return false; - } - return ((UserCredentialValidatorProvider)provider).validCredentials(session, realm, user, toValidate); - } - - @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, UserCredentialModel... input) { - return validCredentials(session, realm, user, Arrays.asList(input)); - } - @Override public CredentialValidationOutput validCredentials(KeycloakSession session, RealmModel realm, UserCredentialModel... input) { List providers = getStorageProviders(session, realm, UserCredentialAuthenticationProvider.class); @@ -615,15 +566,15 @@ public class UserStorageManager implements UserProvider, OnUserCache { } @Override - public void onCache(RealmModel realm, CachedUserModel user) { + public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) { if (StorageId.isLocalStorage(user)) { if (session.userLocalStorage() instanceof OnUserCache) { - ((OnUserCache)session.userLocalStorage()).onCache(realm, user); + ((OnUserCache)session.userLocalStorage()).onCache(realm, user, delegate); } } else { Object provider = getStorageProvider(session, realm, StorageId.resolveProviderId(user)); if (provider != null && provider instanceof OnUserCache) { - ((OnUserCache)provider).onCache(realm, user); + ((OnUserCache)provider).onCache(realm, user, delegate); } } } diff --git a/services/src/main/resources/META-INF/services/org.keycloak.credential.CredentialProviderFactory b/services/src/main/resources/META-INF/services/org.keycloak.credential.CredentialProviderFactory new file mode 100644 index 0000000000..84530ed0fd --- /dev/null +++ b/services/src/main/resources/META-INF/services/org.keycloak.credential.CredentialProviderFactory @@ -0,0 +1,2 @@ +org.keycloak.credential.OTPCredentialProviderFactory +org.keycloak.credential.PasswordCredentialProviderFactory \ No newline at end of file diff --git a/services/src/main/resources/META-INF/services/org.keycloak.credential.hash.PasswordHashProviderFactory b/services/src/main/resources/META-INF/services/org.keycloak.credential.hash.PasswordHashProviderFactory new file mode 100644 index 0000000000..e72e56d77d --- /dev/null +++ b/services/src/main/resources/META-INF/services/org.keycloak.credential.hash.PasswordHashProviderFactory @@ -0,0 +1 @@ +org.keycloak.credential.hash.Pbkdf2PasswordHashProvider \ No newline at end of file diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/DummyUserFederationProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/DummyUserFederationProvider.java index 0ba4816fa8..5a8b6d41fe 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/DummyUserFederationProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/federation/DummyUserFederationProvider.java @@ -17,6 +17,8 @@ package org.keycloak.testsuite.federation; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialModel; import org.keycloak.models.CredentialValidationOutput; import org.keycloak.models.GroupModel; import org.keycloak.models.RealmModel; @@ -105,37 +107,49 @@ public class DummyUserFederationProvider implements UserFederationProvider { return users.containsKey(username); } - @Override - public Set getSupportedCredentialTypes(UserModel user) { - // Just user "test-user" is able to validate password with this federationProvider - if (user.getUsername().equals("test-user")) { - return Collections.singleton(UserCredentialModel.PASSWORD); - } else { - return Collections.emptySet(); - } - } - @Override public Set getSupportedCredentialTypes() { return Collections.singleton(UserCredentialModel.PASSWORD); } @Override - public boolean validCredentials(RealmModel realm, UserModel user, List input) { - if (user.getUsername().equals("test-user") && input.size() == 1) { - UserCredentialModel password = input.get(0); - if (password.getType().equals(UserCredentialModel.PASSWORD)) { - return "secret".equals(password.getValue()); - } - } + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + if (!(input instanceof UserCredentialModel) || !CredentialModel.PASSWORD.equals(input.getType())) return false; + return false; } @Override - public boolean validCredentials(RealmModel realm, UserModel user, UserCredentialModel... input) { - return validCredentials(realm, user, Arrays.asList(input)); + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + } + @Override + public boolean supportsCredentialType(String credentialType) { + return getSupportedCredentialTypes().contains(credentialType); + } + + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + if (!CredentialModel.PASSWORD.equals(credentialType)) return false; + + if (user.getUsername().equals("test-user")) { + return true; + } else { + return false; + } + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (user.getUsername().equals("test-user")) { + UserCredentialModel password = (UserCredentialModel)input; + if (password.getType().equals(UserCredentialModel.PASSWORD)) { + return "secret".equals(password.getValue()); + } + } + return false; } + @Override public CredentialValidationOutput validCredentials(RealmModel realm, UserCredentialModel credential) { return CredentialValidationOutput.failed(); diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java index 2085cfac14..007f3a7bdf 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java @@ -578,7 +578,7 @@ public class TestingResourceProvider implements RealmResourceProvider { if (realm == null) return false; UserProvider userProvider = session.getProvider(UserProvider.class); UserModel user = userProvider.getUserByUsername(userName, realm); - return userProvider.validCredentials(session, realm, user, UserCredentialModel.password(password)); + return session.userCredentialManager().isValid(realm, user, UserCredentialModel.password(password)); } @GET @@ -591,7 +591,7 @@ public class TestingResourceProvider implements RealmResourceProvider { RealmModel realm = getRealmByName(realmName); UserModel foundFederatedUser = session.users().getUserByFederatedIdentity(new FederatedIdentityModel(identityProvider, userId, userName), realm); if (foundFederatedUser == null) return null; - return ModelToRepresentation.toRepresentation(foundFederatedUser); + return ModelToRepresentation.toRepresentation(session, realm, foundFederatedUser); } @GET @@ -603,7 +603,7 @@ public class TestingResourceProvider implements RealmResourceProvider { UserFederationProviderFactory factory = (UserFederationProviderFactory)session.getKeycloakSessionFactory().getProviderFactory(UserFederationProvider.class, "dummy"); UserModel user = factory.getInstance(session, null).getUserByUsername(realm, userName); if (user == null) return null; - return ModelToRepresentation.toRepresentation(user); + return ModelToRepresentation.toRepresentation(session, realm, user); } @GET @@ -634,7 +634,7 @@ public class TestingResourceProvider implements RealmResourceProvider { ClientModel client = realm.getClientByClientId(clientId); UserModel user = session.users().getServiceAccount(client); if (user == null) return null; - return ModelToRepresentation.toRepresentation(user); + return ModelToRepresentation.toRepresentation(session, realm, user); } @Path("/export-import") diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java index 90178a9dab..31c297f9d5 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/BruteForceTest.java @@ -16,6 +16,8 @@ */ package org.keycloak.testsuite.forms; +import com.fasterxml.jackson.jaxrs.json.annotation.JSONP; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; @@ -25,6 +27,7 @@ import org.keycloak.events.Errors; import org.keycloak.models.Constants; import org.keycloak.models.utils.TimeBasedOTP; import org.keycloak.representations.idm.CredentialRepresentation; +import org.keycloak.services.managers.DefaultBruteForceProtector; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.AssertEvents.ExpectedEvent; import org.keycloak.testsuite.pages.AppPage; @@ -34,6 +37,7 @@ import org.keycloak.testsuite.pages.LoginTotpPage; import org.keycloak.testsuite.pages.RegisterPage; import java.net.MalformedURLException; + import org.jboss.arquillian.graphene.page.Page; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.representations.idm.UserRepresentation; @@ -70,6 +74,12 @@ public class BruteForceTest extends TestRealmKeycloakTest { } + @After + public void slowItDown() throws Exception { + Thread.sleep(100); + + } + @Rule public AssertEvents events = new AssertEvents(this); @@ -187,7 +197,7 @@ public class BruteForceTest extends TestRealmKeycloakTest { { String totpSecret = totp.generateTOTP("totpSecret"); OAuthClient.AccessTokenResponse response = getTestToken("password", totpSecret); - Assert.assertNull(response.getAccessToken()); + assertTokenNull(response); Assert.assertNotNull(response.getError()); Assert.assertEquals(response.getError(), "invalid_grant"); Assert.assertEquals(response.getErrorDescription(), "Account temporarily disabled"); @@ -202,8 +212,16 @@ public class BruteForceTest extends TestRealmKeycloakTest { events.clear(); } - } @Test - public void testGrantMissingOtp() throws Exception { + } + + public void assertTokenNull(OAuthClient.AccessTokenResponse response) { + Assert.assertNull(response.getAccessToken()); + } + + + + @Test + public void testGrantMissingOtp() throws Exception { { String totpSecret = totp.generateTOTP("totpSecret"); OAuthClient.AccessTokenResponse response = getTestToken("password", totpSecret); @@ -228,7 +246,7 @@ public class BruteForceTest extends TestRealmKeycloakTest { { String totpSecret = totp.generateTOTP("totpSecret"); OAuthClient.AccessTokenResponse response = getTestToken("password", totpSecret); - Assert.assertNull(response.getAccessToken()); + assertTokenNull(response); Assert.assertNotNull(response.getError()); Assert.assertEquals(response.getError(), "invalid_grant"); Assert.assertEquals(response.getErrorDescription(), "Account temporarily disabled"); @@ -337,7 +355,7 @@ public class BruteForceTest extends TestRealmKeycloakTest { .error(Errors.USER_TEMPORARILY_DISABLED) .detail(Details.USERNAME, username) .removeDetail(Details.CONSENT); - if(userId != null) { + if (userId != null) { event.user(userId); } event.assertEvent(); @@ -416,12 +434,12 @@ public class BruteForceTest extends TestRealmKeycloakTest { events.clear(); } - public void registerUser(String username){ + public void registerUser(String username) { loginPage.open(); loginPage.clickRegister(); registerPage.assertCurrent(); - registerPage.register("user", "name", username + "@localhost", username, "password", "password"); + registerPage.register("user", "name", username + "@localhost", username, "password", "password"); Assert.assertNull(registerPage.getInstruction()); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginHotpTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginHotpTest.java index 43c6153c91..d478f04ccb 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginHotpTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginHotpTest.java @@ -30,6 +30,8 @@ import org.keycloak.testsuite.pages.LoginPage; import org.keycloak.testsuite.pages.LoginTotpPage; import java.net.MalformedURLException; +import java.util.List; + import org.jboss.arquillian.graphene.page.Page; import org.keycloak.models.UserCredentialModel; import org.keycloak.representations.idm.RealmRepresentation; @@ -49,6 +51,9 @@ public class LoginHotpTest extends TestRealmKeycloakTest { @Override public void configureTestRealm(RealmRepresentation testRealm) { + testRealm.setOtpPolicyType(UserCredentialModel.HOTP); + testRealm.setOtpPolicyAlgorithm(HmacOTP.DEFAULT_ALGORITHM); + testRealm.setOtpPolicyLookAheadWindow(2); UserRepresentation user = RealmRepUtil.findUser(testRealm, "test-user@localhost"); UserBuilder.edit(user) .hotpSecret("hotpSecret") @@ -79,9 +84,6 @@ public class LoginHotpTest extends TestRealmKeycloakTest { @Before public void before() throws MalformedURLException { RealmRepresentation testRealm = testRealm().toRepresentation(); - testRealm.setOtpPolicyType(UserCredentialModel.HOTP); - testRealm.setOtpPolicyLookAheadWindow(2); - testRealm().update(testRealm); policy = new OTPPolicy(); policy.setAlgorithm(testRealm.getOtpPolicyAlgorithm()); @@ -137,7 +139,7 @@ public class LoginHotpTest extends TestRealmKeycloakTest { loginPage.open(); loginPage.login("test-user@localhost", "password"); - Assert.assertTrue(loginTotpPage.isCurrent()); + Assert.assertTrue("expecting totpPage got: " + driver.getCurrentUrl(), loginTotpPage.isCurrent()); loginTotpPage.login(otp.generateHOTP("hotpSecret", counter++)); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java index 5bef3d2472..01f585446f 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/forms/LoginTest.java @@ -354,7 +354,9 @@ public class LoginTest extends TestRealmKeycloakTest { events.expectRequiredAction(EventType.UPDATE_PASSWORD).user(userId).detail(Details.USERNAME, "login-test").assertEvent(); - assertEquals(RequestType.AUTH_RESPONSE, appPage.getRequestType()); + String currentUrl = driver.getCurrentUrl(); + String pageSource = driver.getPageSource(); + assertEquals("bad expectation, on page: " + currentUrl, RequestType.AUTH_RESPONSE, appPage.getRequestType()); events.expectLogin().user(userId).detail(Details.USERNAME, "login-test").assertEvent(); diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/KerberosLdapTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/KerberosLdapTest.java index 7ea5c85556..67c5ba891c 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/KerberosLdapTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/KerberosLdapTest.java @@ -114,6 +114,11 @@ public class KerberosLdapTest extends AbstractKerberosTest { assertUser("hnelson", "hnelson@keycloak.org", "Horatio", "Nelson", false); } + @Test + @Override + public void usernamePasswordLoginTest() throws Exception { + super.usernamePasswordLoginTest(); + } @Test public void writableEditModeTest() throws Exception { diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/ldap/FederationTestUtils.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/ldap/FederationTestUtils.java index 81b10461b7..febb327172 100644 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/ldap/FederationTestUtils.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/ldap/FederationTestUtils.java @@ -68,7 +68,7 @@ public class FederationTestUtils { creds.setType(CredentialRepresentation.PASSWORD); creds.setValue(password); - user.updateCredential(creds); + session.userCredentialManager().updateCredential(realm, user, creds); return user; } diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/ldap/base/FederationProvidersIntegrationTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/ldap/base/FederationProvidersIntegrationTest.java index be8c97bd8d..c46938770b 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/ldap/base/FederationProvidersIntegrationTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/ldap/base/FederationProvidersIntegrationTest.java @@ -26,6 +26,7 @@ import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.junit.runners.MethodSorters; import org.keycloak.OAuth2Constants; +import org.keycloak.credential.CredentialModel; import org.keycloak.federation.ldap.LDAPConfig; import org.keycloak.federation.ldap.LDAPFederationProvider; import org.keycloak.federation.ldap.LDAPFederationProviderFactory; @@ -687,7 +688,7 @@ public class FederationProvidersIntegrationTest { } try { UserCredentialModel cred = UserCredentialModel.password("PoopyPoop1"); - user.updateCredential(cred); + session.userCredentialManager().updateCredential(appRealm, user, cred); Assert.fail("should fail"); } catch (ModelReadOnlyException e) { @@ -818,10 +819,10 @@ public class FederationProvidersIntegrationTest { Assert.assertEquals(user.getFederationLink(), ldapModel.getId()); UserCredentialModel cred = UserCredentialModel.password("Candycand1"); - user.updateCredential(cred); - UserCredentialValueModel userCredentialValueModel = user.getCredentialsDirectly().get(0); + session.userCredentialManager().updateCredential(appRealm, user, cred); + CredentialModel userCredentialValueModel = session.userCredentialManager().getStoredCredentialsByType(appRealm, user, CredentialModel.PASSWORD).get(0); Assert.assertEquals(UserCredentialModel.PASSWORD, userCredentialValueModel.getType()); - Assert.assertTrue(session.users().validCredentials(session, appRealm, user, cred)); + Assert.assertTrue(session.userCredentialManager().isValid(appRealm, user, cred)); // LDAP password is still unchanged LDAPFederationProvider ldapProvider = FederationTestUtils.getLdapProvider(session, model); diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserMapStorage.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserMapStorage.java index 7f72e8efab..a9fe9abdc0 100644 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserMapStorage.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserMapStorage.java @@ -17,17 +17,19 @@ package org.keycloak.testsuite.federation.storage; import org.keycloak.component.ComponentModel; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialInputUpdater; +import org.keycloak.credential.CredentialInputValidator; +import org.keycloak.credential.CredentialModel; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.RoleModel; import org.keycloak.models.UserCredentialModel; -import org.keycloak.models.UserCredentialValueModel; import org.keycloak.models.UserModel; import org.keycloak.storage.StorageId; import org.keycloak.storage.UserStorageProvider; import org.keycloak.storage.adapter.AbstractUserAdapterFederatedStorage; -import org.keycloak.storage.user.UserCredentialValidatorProvider; import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.storage.user.UserRegistrationProvider; @@ -40,7 +42,7 @@ import java.util.concurrent.atomic.AtomicInteger; * @author Bill Burke * @version $Revision: 1 $ */ -public class UserMapStorage implements UserLookupProvider, UserStorageProvider, UserRegistrationProvider { +public class UserMapStorage implements UserLookupProvider, UserStorageProvider, UserRegistrationProvider, CredentialInputUpdater, CredentialInputValidator { protected Map userPasswords; protected ComponentModel model; @@ -78,39 +80,47 @@ public class UserMapStorage implements UserLookupProvider, UserStorageProvider, throw new RuntimeException("Unsupported"); } - @Override - public void updateCredential(UserCredentialModel cred) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - userPasswords.put(getUsername(), cred.getValue()); - } else { - super.updateCredential(cred); - } - } - - @Override - public List getCredentialsDirectly() { - UserCredentialValueModel pw = new UserCredentialValueModel(); - pw.setId(getId()); - pw.setType(UserCredentialModel.PASSWORD); - pw.setAlgorithm("text"); - pw.setValue(userPasswords.get(getUsername())); - List creds = new LinkedList<>(); - creds.addAll(super.getCredentialsDirectly()); - creds.add(pw); - return creds; - } - - @Override - public void updateCredentialDirectly(UserCredentialValueModel cred) { - if (cred.getType().equals(UserCredentialModel.PASSWORD)) { - //userPasswords.put(getUsername(), cred.getValue()); - } else { - super.updateCredentialDirectly(cred); - } - } }; } + @Override + public boolean supportsCredentialType(String credentialType) { + return CredentialModel.PASSWORD.equals(credentialType); + } + + @Override + public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) { + if (!(input instanceof UserCredentialModel)) return false; + if (input.getType().equals(UserCredentialModel.PASSWORD)) { + userPasswords.put(user.getUsername(), ((UserCredentialModel)input).getValue()); + return true; + + } else { + return false; + } + } + + @Override + public void disableCredentialType(RealmModel realm, UserModel user, String credentialType) { + + } + + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + return CredentialModel.PASSWORD.equals(credentialType); + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (!(input instanceof UserCredentialModel)) return false; + if (input.getType().equals(UserCredentialModel.PASSWORD)) { + String pw = userPasswords.get(user.getUsername()); + return pw != null && pw.equals( ((UserCredentialModel)input).getValue()); + } else { + return false; + } + } + @Override public UserModel getUserByUsername(String username, RealmModel realm) { if (!userPasswords.containsKey(username)) return null; diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserPropertyFileStorage.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserPropertyFileStorage.java index c297aca807..bab2c4af4b 100644 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserPropertyFileStorage.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserPropertyFileStorage.java @@ -17,6 +17,8 @@ package org.keycloak.testsuite.federation.storage; import org.keycloak.component.ComponentModel; +import org.keycloak.credential.CredentialInput; +import org.keycloak.credential.CredentialInputValidator; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; @@ -27,7 +29,6 @@ import org.keycloak.storage.StorageId; import org.keycloak.storage.UserStorageProvider; import org.keycloak.storage.adapter.AbstractUserAdapter; import org.keycloak.storage.adapter.AbstractUserAdapterFederatedStorage; -import org.keycloak.storage.user.UserCredentialValidatorProvider; import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.storage.user.UserQueryProvider; @@ -41,7 +42,7 @@ import java.util.Properties; * @author Bill Burke * @version $Revision: 1 $ */ -public class UserPropertyFileStorage implements UserLookupProvider, UserStorageProvider, UserCredentialValidatorProvider, UserQueryProvider { +public class UserPropertyFileStorage implements UserLookupProvider, UserStorageProvider, UserQueryProvider, CredentialInputValidator { protected Properties userPasswords; protected ComponentModel model; @@ -116,16 +117,27 @@ public class UserPropertyFileStorage implements UserLookupProvider, UserStorageP } @Override - public boolean validCredentials(KeycloakSession session, RealmModel realm, UserModel user, List input) { - for (UserCredentialModel cred : input) { - if (!cred.getType().equals(UserCredentialModel.PASSWORD)) return false; - String password = (String)userPasswords.get(user.getUsername()); - if (password == null) return false; - if (!password.equals(cred.getValue())) return false; - } - return true; + public boolean supportsCredentialType(String credentialType) { + return credentialType.equals(UserCredentialModel.PASSWORD); } + @Override + public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { + return credentialType.equals(UserCredentialModel.PASSWORD) && userPasswords.get(user.getUsername()) != null; + } + + @Override + public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) { + if (!(input instanceof UserCredentialModel)) return false; + if (input.getType().equals(UserCredentialModel.PASSWORD)) { + String pw = (String)userPasswords.get(user.getUsername()); + return pw != null && pw.equals( ((UserCredentialModel)input).getValue()); + } else { + return false; + } + } + + @Override public int getUsersCount(RealmModel realm) { return userPasswords.size(); diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java index 3c3a6a04a9..2b2d9623a1 100644 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java @@ -159,7 +159,7 @@ public class UserStorageTest { System.out.println("num groups " + groups.size()); Assert.assertTrue(thor.getRequiredActions().iterator().next().equals("POOP")); thor.removeRequiredAction("POOP"); - thor.updateCredential(UserCredentialModel.password("lightning")); + session.userCredentialManager().updateCredential(realm, thor, UserCredentialModel.password("lightning")); keycloakRule.stopSession(session, true); loginSuccessAndLogout("thor", "lightning"); } @@ -254,7 +254,7 @@ public class UserStorageTest { KeycloakSession session = keycloakRule.startSession(); RealmModel realm = session.realms().getRealmByName("test"); UserModel user = session.users().addUser(realm, "memuser"); - user.updateCredential(UserCredentialModel.password("password")); + session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password")); keycloakRule.stopSession(session, true); loginSuccessAndLogout("memuser", "password"); loginSuccessAndLogout("memuser", "password"); @@ -264,7 +264,6 @@ public class UserStorageTest { realm = session.realms().getRealmByName("test"); user = session.users().getUserByUsername("memuser", realm); Assert.assertEquals(memoryProvider.getId(), StorageId.resolveProviderId(user)); - Assert.assertEquals(1, user.getCredentialsDirectly().size()); session.users().removeUser(realm, user); Assert.assertNull(session.users().getUserByUsername("memuser", realm)); keycloakRule.stopSession(session, true); diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/model/AdapterTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/model/AdapterTest.java index 42d190c980..2d57d21bcd 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/model/AdapterTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/model/AdapterTest.java @@ -23,6 +23,7 @@ import org.junit.Test; import org.junit.runners.MethodSorters; import org.keycloak.Config; import org.keycloak.component.ComponentModel; +import org.keycloak.credential.CredentialModel; import org.keycloak.models.ClientModel; import org.keycloak.models.FederatedIdentityModel; import org.keycloak.models.ModelDuplicateException; @@ -164,13 +165,14 @@ public class AdapterTest extends AbstractModelTest { UserCredentialModel cred = new UserCredentialModel(); cred.setType(CredentialRepresentation.PASSWORD); cred.setValue("geheim"); - user.updateCredential(cred); - Assert.assertTrue(userProvider.validCredentials(session, realmModel, user, UserCredentialModel.password("geheim"))); - List creds = user.getCredentialsDirectly(); + realmManager.getSession().userCredentialManager().updateCredential(realmModel, user, cred); + Assert.assertTrue(realmManager.getSession().userCredentialManager().isValid(realmModel, user, UserCredentialModel.password("geheim"))); + List creds = realmManager.getSession().userCredentialManager().getStoredCredentialsByType(realmModel, user, CredentialModel.PASSWORD); + Assert.assertEquals(creds.get(0).getHashIterations(), 20000); realmModel.setPasswordPolicy(PasswordPolicy.parse(realmManager.getSession(), "hashIterations(200)")); - Assert.assertTrue(userProvider.validCredentials(session, realmModel, user, UserCredentialModel.password("geheim"))); - creds = user.getCredentialsDirectly(); + Assert.assertTrue(realmManager.getSession().userCredentialManager().isValid(realmModel, user, UserCredentialModel.password("geheim"))); + creds = realmManager.getSession().userCredentialManager().getStoredCredentialsByType(realmModel, user, CredentialModel.PASSWORD); Assert.assertEquals(creds.get(0).getHashIterations(), 200); realmModel.setPasswordPolicy(PasswordPolicy.parse(realmManager.getSession(), "hashIterations(1)")); } @@ -196,8 +198,7 @@ public class AdapterTest extends AbstractModelTest { UserCredentialModel cred = new UserCredentialModel(); cred.setType(CredentialRepresentation.PASSWORD); cred.setValue("password"); - user.updateCredential(cred); - + realmManager.getSession().userCredentialManager().updateCredential(realmModel, user, cred); commit(); realmModel = model.getRealm("JUGGLER"); @@ -237,7 +238,7 @@ public class AdapterTest extends AbstractModelTest { UserCredentialModel cred = new UserCredentialModel(); cred.setType(CredentialRepresentation.PASSWORD); cred.setValue("password"); - user.updateCredential(cred); + realmManager.getSession().userCredentialManager().updateCredential(realmModel, user, cred); ClientModel client = realmModel.addClient("client"); diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/model/MultipleRealmsTest.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/model/MultipleRealmsTest.java index f91540ebc7..027230eb69 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/model/MultipleRealmsTest.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/model/MultipleRealmsTest.java @@ -53,13 +53,13 @@ public class MultipleRealmsTest extends AbstractModelTest { Assert.assertNotEquals(r1user1.getId(), r2user1.getId()); // Test password - r1user1.updateCredential(UserCredentialModel.password("pass1")); - r2user1.updateCredential(UserCredentialModel.password("pass2")); + session.userCredentialManager().updateCredential(realm1, r1user1, UserCredentialModel.password("pass1")); + session.userCredentialManager().updateCredential(realm2, r2user1, UserCredentialModel.password("pass2")); - Assert.assertTrue(session.users().validCredentials(session, realm1, r1user1, UserCredentialModel.password("pass1"))); - Assert.assertFalse(session.users().validCredentials(session, realm1, r1user1, UserCredentialModel.password("pass2"))); - Assert.assertFalse(session.users().validCredentials(session, realm2, r2user1, UserCredentialModel.password("pass1"))); - Assert.assertTrue(session.users().validCredentials(session, realm2, r2user1, UserCredentialModel.password("pass2"))); + Assert.assertTrue(session.userCredentialManager().isValid(realm1, r1user1, UserCredentialModel.password("pass1"))); + Assert.assertFalse(session.userCredentialManager().isValid(realm1, r1user1, UserCredentialModel.password("pass2"))); + Assert.assertFalse(session.userCredentialManager().isValid(realm2, r2user1, UserCredentialModel.password("pass1"))); + Assert.assertTrue(session.userCredentialManager().isValid(realm2, r2user1, UserCredentialModel.password("pass2"))); // Test searching Assert.assertEquals(2, session.users().searchForUser("user", realm1).size()); diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/rule/AbstractKeycloakRule.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/rule/AbstractKeycloakRule.java index 8315331918..7462a28b33 100755 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/rule/AbstractKeycloakRule.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/rule/AbstractKeycloakRule.java @@ -89,7 +89,7 @@ public abstract class AbstractKeycloakRule extends ExternalResource { try { RealmModel realmByName = session.realms().getRealmByName(realm); UserModel user = session.users().getUserByUsername(name, realmByName); - UserRepresentation userRep = user != null ? ModelToRepresentation.toRepresentation(user) : null; + UserRepresentation userRep = user != null ? ModelToRepresentation.toRepresentation(session, realmByName, user) : null; session.getTransactionManager().commit(); return userRep; } finally { @@ -102,7 +102,7 @@ public abstract class AbstractKeycloakRule extends ExternalResource { session.getTransactionManager().begin(); try { RealmModel realmByName = session.realms().getRealmByName(realm); - UserRepresentation userRep = ModelToRepresentation.toRepresentation(session.users().getUserById(id, realmByName)); + UserRepresentation userRep = ModelToRepresentation.toRepresentation(session, realmByName, session.users().getUserById(id, realmByName)); session.getTransactionManager().commit(); return userRep; } finally { diff --git a/testsuite/integration/src/test/java/org/keycloak/testsuite/util/cli/UserCommands.java b/testsuite/integration/src/test/java/org/keycloak/testsuite/util/cli/UserCommands.java index 9bde85207b..fe556024dc 100644 --- a/testsuite/integration/src/test/java/org/keycloak/testsuite/util/cli/UserCommands.java +++ b/testsuite/integration/src/test/java/org/keycloak/testsuite/util/cli/UserCommands.java @@ -103,7 +103,7 @@ public class UserCommands { user.setEnabled(true); user.setEmail(username + "@keycloak.org"); UserCredentialModel passwordCred = UserCredentialModel.password(password); - user.updateCredential(passwordCred); + session.userCredentialManager().updateCredential(realm, user, passwordCred); for (RoleModel role : roles) { user.grantRole(role); diff --git a/wildfly/server-subsystem/src/main/resources/subsystem-templates/keycloak-datasources.xml b/wildfly/server-subsystem/src/main/resources/subsystem-templates/keycloak-datasources.xml index c823e4f3a3..cd7fc81abd 100755 --- a/wildfly/server-subsystem/src/main/resources/subsystem-templates/keycloak-datasources.xml +++ b/wildfly/server-subsystem/src/main/resources/subsystem-templates/keycloak-datasources.xml @@ -21,22 +21,22 @@ org.jboss.as.connector - - jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE + + jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE h2 sa sa - - - + + + h2 sa sa - + org.h2.jdbcx.JdbcDataSource @@ -46,12 +46,12 @@ - jdbc:h2:${jboss.server.data.dir}/keycloak;AUTO_SERVER=TRUE + jdbc:h2:${jboss.server.data.dir}/keycloak;AUTO_SERVER=TRUE - jdbc:h2:${jboss.server.data.dir}/../../shared-database/keycloak;AUTO_SERVER=TRUE + jdbc:h2:${jboss.server.data.dir}/../../shared-database/keycloak;AUTO_SERVER=TRUE