use of org.keycloak.models.credential.PasswordCredentialModel in project keycloak by keycloak.
the class AddUserTest method addUserTest.
@Test
public void addUserTest() throws Exception {
final String username = "addusertest-admin";
final String realmName = "master";
final String configDir = System.getProperty("auth.server.config.dir");
assertThat("AuthServer config directory is NULL !!", configDir, notNullValue());
String authServerQualifier = suiteContext.getAuthServerInfo().getQualifier();
assertThat("Qualifier of AuthServer is empty or NULL !!", authServerQualifier, not(isEmptyOrNullString()));
assertThat("Controller isn't running.", controller.isStarted(authServerQualifier), is(true));
AddUser.main(new String[] { "-u", username, "-p", "password", "--sc", configDir });
// Read keycloak-add-user.json
List<RealmRepresentation> realms = JsonSerialization.readValue(new FileInputStream(new File(configDir, "keycloak-add-user.json")), new TypeReference<List<RealmRepresentation>>() {
});
assertThat("File 'keycloak-add-user.json' is empty.", realms, not(empty()));
// -----------------Get-Indexes-------------------//
int realmIndex = getRealmIndex(realmName, realms);
assertThat("Realm " + realmName + " not found.", realmIndex, is(not(-1)));
int userIndex = getUserIndex(username, realms.get(realmIndex).getUsers());
assertThat("User " + username + " not found", userIndex, is(not(-1)));
UserRepresentation user = realms.get(realmIndex).getUsers().get(userIndex);
assertThat("Username from Json file is wrong.", user.getUsername(), is(username));
// ------------------Credentials-----------------------------//
assertThat("User Credentials are NULL", user.getCredentials().get(0), notNullValue());
CredentialRepresentation credentials = user.getCredentials().get(0);
PasswordCredentialModel pcm = PasswordCredentialModel.createFromCredentialModel(RepresentationToModel.toModel(credentials));
assertThat("User Credentials have wrong Algorithm.", pcm.getPasswordCredentialData().getAlgorithm(), is(Pbkdf2Sha256PasswordHashProviderFactory.ID));
assertThat("User Credentials have wrong Hash Iterations", pcm.getPasswordCredentialData().getHashIterations(), is(100000));
// ------------------Restart--Container---------------------//
controller.stop(authServerQualifier);
controller.start(authServerQualifier);
RealmResource realmResource = getAdminClient().realm(realmName);
assertThat("Realm resource is NULL !!", realmResource, notNullValue());
user = realmResource.users().search(username).get(0);
assertThat("Username is wrong.", user.getUsername(), is(username));
UserResource userResource = realmResource.users().get(user.getId());
assertThat("User resource is NULL !!", userResource, notNullValue());
// --------------Roles-----------------------//
try {
assertRoles(userResource.roles().realmLevel().listAll(), "admin", Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realmName);
assertRoles(userResource.roles().realmLevel().listEffective(), "create-realm", Constants.AUTHZ_UMA_AUTHORIZATION, Constants.DEFAULT_ROLES_ROLE_PREFIX + "-" + realmName, Constants.OFFLINE_ACCESS_ROLE, "admin");
List<ClientRepresentation> clients = realmResource.clients().findAll();
String accountId = null;
for (ClientRepresentation c : clients) {
if (c.getClientId().equals("account")) {
accountId = c.getId();
}
}
assertTrue(userResource.roles().clientLevel(accountId).listAll().isEmpty());
List<RoleRepresentation> accountRoles = userResource.roles().clientLevel(accountId).listEffective();
assertRoles(accountRoles, "view-profile", "manage-account", "manage-account-links");
} finally {
userResource.remove();
}
}
use of org.keycloak.models.credential.PasswordCredentialModel in project keycloak by keycloak.
the class AddUser method createUser.
private static void createUser(File addUserFile, String realmName, String userName, String password, String rolesString, int iterations) throws Exception {
List<RealmRepresentation> realms;
if (addUserFile.isFile()) {
realms = JsonSerialization.readValue(new FileInputStream(addUserFile), new TypeReference<List<RealmRepresentation>>() {
});
} else {
realms = new LinkedList<>();
}
if (realmName == null) {
realmName = "master";
}
RealmRepresentation realm = null;
for (RealmRepresentation r : realms) {
if (r.getRealm().equals(realmName)) {
realm = r;
}
}
if (realm == null) {
realm = new RealmRepresentation();
realm.setRealm(realmName);
realms.add(realm);
realm.setUsers(new LinkedList<>());
}
for (UserRepresentation u : realm.getUsers()) {
if (u.getUsername().equals(userName)) {
throw new Exception("User with username '" + userName + "' already added to '" + addUserFile + "'");
}
}
UserRepresentation user = new UserRepresentation();
user.setEnabled(true);
user.setUsername(userName);
user.setCredentials(new LinkedList<>());
PasswordHashProviderFactory hashProviderFactory = getHashProviderFactory(DEFAULT_HASH_ALGORITH);
PasswordHashProvider hashProvider = hashProviderFactory.create(null);
PasswordCredentialModel credentialModel = hashProvider.encodedCredential(password, iterations > 0 ? iterations : DEFAULT_HASH_ITERATIONS);
CredentialRepresentation credentials = ModelToRepresentation.toRepresentation(credentialModel);
user.getCredentials().add(credentials);
String[] roles;
if (rolesString != null) {
roles = rolesString.split(",");
} else {
if (realmName.equals("master")) {
roles = new String[] { "admin" };
} else {
roles = new String[] { "realm-management/realm-admin" };
}
}
for (String r : roles) {
if (r.indexOf('/') != -1) {
String[] cr = r.split("/");
String client = cr[0];
String clientRole = cr[1];
if (user.getClientRoles() == null) {
user.setClientRoles(new HashMap<>());
}
if (user.getClientRoles().get(client) == null) {
user.getClientRoles().put(client, new LinkedList<>());
}
user.getClientRoles().get(client).add(clientRole);
} else {
if (user.getRealmRoles() == null) {
user.setRealmRoles(new LinkedList<>());
}
user.getRealmRoles().add(r);
}
}
realm.getUsers().add(user);
JsonSerialization.writeValuePrettyToStream(new FileOutputStream(addUserFile), realms);
System.out.println("Added '" + userName + "' to '" + addUserFile + "', restart server to load user");
}
use of org.keycloak.models.credential.PasswordCredentialModel in project keycloak by keycloak.
the class UserTest method updateUserWithHashedCredentials.
@Test
// TODO remove this (KEYCLOAK-16228)
@DisableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true)
public void updateUserWithHashedCredentials() {
String userId = createUser("user_hashed_creds", "user_hashed_creds@localhost");
byte[] salt = new byte[] { -69, 85, 87, 99, 26, -107, 125, 99, -77, 30, -111, 118, 108, 100, -117, -56 };
PasswordCredentialModel credentialModel = PasswordCredentialModel.createFromValues("pbkdf2-sha256", salt, 27500, "uskEPZWMr83pl2mzNB95SFXfIabe2UH9ClENVx/rrQqOjFEjL2aAOGpWsFNNF3qoll7Qht2mY5KxIDm3Rnve2w==");
credentialModel.setCreatedDate(1001l);
CredentialRepresentation hashedPassword = ModelToRepresentation.toRepresentation(credentialModel);
UserRepresentation userRepresentation = new UserRepresentation();
userRepresentation.setCredentials(Collections.singletonList(hashedPassword));
realm.users().get(userId).update(userRepresentation);
String accountUrl = RealmsResource.accountUrl(UriBuilder.fromUri(getAuthServerRoot())).build(REALM_NAME).toString();
driver.navigate().to(accountUrl);
assertEquals("Sign in to your account", PageUtils.getPageTitle(driver));
loginPage.login("user_hashed_creds", "admin");
assertTrue(driver.getTitle().contains("Account Management"));
}
use of org.keycloak.models.credential.PasswordCredentialModel in project keycloak by keycloak.
the class UserTest method createUserWithHashedCredentials.
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void createUserWithHashedCredentials() {
UserRepresentation user = new UserRepresentation();
user.setUsername("user_creds");
user.setEmail("email@localhost");
PasswordCredentialModel pcm = PasswordCredentialModel.createFromValues("my-algorithm", "theSalt".getBytes(), 22, "ABC");
CredentialRepresentation hashedPassword = ModelToRepresentation.toRepresentation(pcm);
hashedPassword.setCreatedDate(1001L);
hashedPassword.setUserLabel("deviceX");
hashedPassword.setType(CredentialRepresentation.PASSWORD);
user.setCredentials(Arrays.asList(hashedPassword));
createUser(user);
CredentialModel credentialHashed = fetchCredentials("user_creds");
PasswordCredentialModel pcmh = PasswordCredentialModel.createFromCredentialModel(credentialHashed);
assertNotNull("Expecting credential", credentialHashed);
assertEquals("my-algorithm", pcmh.getPasswordCredentialData().getAlgorithm());
assertEquals(Long.valueOf(1001), credentialHashed.getCreatedDate());
assertEquals("deviceX", credentialHashed.getUserLabel());
assertEquals(22, pcmh.getPasswordCredentialData().getHashIterations());
assertEquals("ABC", pcmh.getPasswordSecretData().getValue());
assertEquals("theSalt", new String(pcmh.getPasswordSecretData().getSalt()));
assertEquals(CredentialRepresentation.PASSWORD, credentialHashed.getType());
}
use of org.keycloak.models.credential.PasswordCredentialModel in project keycloak by keycloak.
the class PasswordHashingTest method testPasswordRehashedOnIterationsChanged.
@Test
public void testPasswordRehashedOnIterationsChanged() throws Exception {
setPasswordPolicy("hashIterations(10000)");
String username = "testPasswordRehashedOnIterationsChanged";
createUser(username);
PasswordCredentialModel credential = PasswordCredentialModel.createFromCredentialModel(fetchCredentials(username));
assertEquals(10000, credential.getPasswordCredentialData().getHashIterations());
setPasswordPolicy("hashIterations(1)");
loginPage.open();
loginPage.login(username, "password");
credential = PasswordCredentialModel.createFromCredentialModel(fetchCredentials(username));
assertEquals(1, credential.getPasswordCredentialData().getHashIterations());
assertEncoded(credential, "password", credential.getPasswordSecretData().getSalt(), "PBKDF2WithHmacSHA256", 1);
}
Aggregations