Search in sources :

Example 16 with PasswordCredentialModel

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();
    }
}
Also used : RealmResource(org.keycloak.admin.client.resource.RealmResource) UserResource(org.keycloak.admin.client.resource.UserResource) IsEmptyString.isEmptyOrNullString(org.hamcrest.text.IsEmptyString.isEmptyOrNullString) FileInputStream(java.io.FileInputStream) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) List(java.util.List) File(java.io.File) Test(org.junit.Test) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest)

Example 17 with PasswordCredentialModel

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");
}
Also used : RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) FileInputStream(java.io.FileInputStream) CommandNotFoundException(org.aesh.command.CommandNotFoundException) CommandRegistryException(org.aesh.command.registry.CommandRegistryException) CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) PasswordHashProviderFactory(org.keycloak.credential.hash.PasswordHashProviderFactory) FileOutputStream(java.io.FileOutputStream) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) TypeReference(com.fasterxml.jackson.core.type.TypeReference) PasswordHashProvider(org.keycloak.credential.hash.PasswordHashProvider) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 18 with PasswordCredentialModel

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"));
}
Also used : CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) DisableFeature(org.keycloak.testsuite.arquillian.annotation.DisableFeature) Test(org.junit.Test)

Example 19 with PasswordCredentialModel

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());
}
Also used : CredentialRepresentation(org.keycloak.representations.idm.CredentialRepresentation) CredentialModel(org.keycloak.credential.CredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) OTPCredentialModel(org.keycloak.models.credential.OTPCredentialModel) PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test)

Example 20 with PasswordCredentialModel

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);
}
Also used : PasswordCredentialModel(org.keycloak.models.credential.PasswordCredentialModel) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

PasswordCredentialModel (org.keycloak.models.credential.PasswordCredentialModel)23 Test (org.junit.Test)17 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)8 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)7 CredentialModel (org.keycloak.credential.CredentialModel)6 CredentialRepresentation (org.keycloak.representations.idm.CredentialRepresentation)6 OTPCredentialModel (org.keycloak.models.credential.OTPCredentialModel)4 PasswordHashProvider (org.keycloak.credential.hash.PasswordHashProvider)3 PasswordPolicy (org.keycloak.models.PasswordPolicy)3 UserCredentialModel (org.keycloak.models.UserCredentialModel)3 AuthServerContainerExclude (org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude)3 FileInputStream (java.io.FileInputStream)2 LinkedList (java.util.LinkedList)2 UserResource (org.keycloak.admin.client.resource.UserResource)2 ExportImportManager (org.keycloak.exportimport.ExportImportManager)2 GroupModel (org.keycloak.models.GroupModel)2 RealmModel (org.keycloak.models.RealmModel)2 RoleModel (org.keycloak.models.RoleModel)2 OnUserCache (org.keycloak.models.cache.OnUserCache)2 UserCache (org.keycloak.models.cache.UserCache)2