Java Code Examples for org.keycloak.representations.idm.UserRepresentation#setUsername()

The following examples show how to use org.keycloak.representations.idm.UserRepresentation#setUsername() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserInvalidationClusterTest.java    From keycloak with Apache License 2.0 8 votes vote down vote up
@Override
protected UserRepresentation testEntityUpdates(UserRepresentation user, boolean backendFailover) {

    // username
    user.setUsername(user.getUsername() + "_updated");
    user = updateEntityOnCurrentFailNode(user, "username");
    verifyEntityUpdateDuringFailover(user, backendFailover);

    // first+lastName
    user.setFirstName(user.getFirstName() + "_updated");
    user.setLastName(user.getLastName() + "_updated");
    user = updateEntityOnCurrentFailNode(user, "firstName/lastName");
    verifyEntityUpdateDuringFailover(user, backendFailover);

    return user;
}
 
Example 2
Source File: KerberosStandaloneTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
/**
 * KEYCLOAK-4178
 *
 * Assert it's handled when kerberos realm is unreachable
 *
 * @throws Exception
 */
@Test
@UncaughtServerErrorExpected
public void handleUnknownKerberosRealm() throws Exception {
    // Switch kerberos realm to "unavailable"
    List<ComponentRepresentation> reps = testRealmResource().components().query("test", UserStorageProvider.class.getName());
    org.keycloak.testsuite.Assert.assertEquals(1, reps.size());
    ComponentRepresentation kerberosProvider = reps.get(0);
    kerberosProvider.getConfig().putSingle(KerberosConstants.KERBEROS_REALM, "unavailable");
    testRealmResource().components().component(kerberosProvider.getId()).update(kerberosProvider);

    // Try register new user and assert it failed
    UserRepresentation john = new UserRepresentation();
    john.setUsername("john");
    Response response = testRealmResource().users().create(john);
    Assert.assertEquals(500, response.getStatus());
    response.close();
}
 
Example 3
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void createUserWithRawCredentials() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user_rawpw");
    user.setEmail("email.raw@localhost");

    CredentialRepresentation rawPassword = new CredentialRepresentation();
    rawPassword.setValue("ABCD");
    rawPassword.setType(CredentialRepresentation.PASSWORD);
    user.setCredentials(Arrays.asList(rawPassword));

    createUser(user);

    CredentialModel credential = fetchCredentials("user_rawpw");
    assertNotNull("Expecting credential", credential);
    PasswordCredentialModel pcm = PasswordCredentialModel.createFromCredentialModel(credential);
    assertEquals(PasswordPolicy.HASH_ALGORITHM_DEFAULT, pcm.getPasswordCredentialData().getAlgorithm());
    assertEquals(PasswordPolicy.HASH_ITERATIONS_DEFAULT, pcm.getPasswordCredentialData().getHashIterations());
    assertNotEquals("ABCD", pcm.getPasswordSecretData().getValue());
    assertEquals(CredentialRepresentation.PASSWORD, credential.getType());
}
 
Example 4
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void updateUserWithNewUsernameAccessingViaOldUsername() {
    switchEditUsernameAllowedOn(true);
    createUser();

    try {
        UserResource user = realm.users().get("user1");
        UserRepresentation userRep = user.toRepresentation();
        userRep.setUsername("user1");
        updateUser(user, userRep);

        realm.users().get("user11").toRepresentation();
        fail("Expected failure");
    } catch (ClientErrorException e) {
        assertEquals(404, e.getResponse().getStatus());
    } finally {
        switchEditUsernameAllowedOn(false);
    }
}
 
Example 5
Source File: KeycloakDevModeRealmResourceManager.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static UserRepresentation createUser(String username, String... realmRoles) {
    UserRepresentation user = new UserRepresentation();

    user.setUsername(username);
    user.setEnabled(true);
    user.setCredentials(new ArrayList<>());
    user.setRealmRoles(Arrays.asList(realmRoles));

    CredentialRepresentation credential = new CredentialRepresentation();

    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue(username);
    credential.setTemporary(false);

    user.getCredentials().add(credential);

    return user;
}
 
Example 6
Source File: KeycloakTestResource.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static UserRepresentation createUser(String username, String... realmRoles) {
    UserRepresentation user = new UserRepresentation();

    user.setUsername(username);
    user.setEnabled(true);
    user.setCredentials(new ArrayList<>());
    user.setRealmRoles(Arrays.asList(realmRoles));

    CredentialRepresentation credential = new CredentialRepresentation();

    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue(username);
    credential.setTemporary(false);

    user.getCredentials().add(credential);

    return user;
}
 
Example 7
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void createUserWithInvalidPolicyPassword() {
    RealmRepresentation rep = realm.toRepresentation();
    String passwordPolicy = rep.getPasswordPolicy();
    rep.setPasswordPolicy("length(8)");
    realm.update(rep);
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user4");
    user.setEmail("user4@localhost");
    CredentialRepresentation rawPassword = new CredentialRepresentation();
    rawPassword.setValue("ABCD");
    rawPassword.setType(CredentialRepresentation.PASSWORD);
    user.setCredentials(Arrays.asList(rawPassword));
    Response response = realm.users().create(user);
    assertEquals(400, response.getStatus());
    ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
    Assert.assertEquals("Password policy not met", error.getErrorMessage());
    rep.setPasswordPolicy(passwordPolicy);
    realm.update(rep);
    response.close();
}
 
Example 8
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void createDuplicatedUser1() {
    createUser();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    Response response = realm.users().create(user);
    assertEquals(409, response.getStatus());
    assertAdminEvents.assertEmpty();

    // Just to show how to retrieve underlying error message
    ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
    Assert.assertEquals("User exists with same username", error.getErrorMessage());

    response.close();
}
 
Example 9
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void createUserWithFederationLink() {

    // add a dummy federation provider
    ComponentRepresentation dummyFederationProvider = new ComponentRepresentation();
    dummyFederationProvider.setId(DummyUserFederationProviderFactory.PROVIDER_NAME);
    dummyFederationProvider.setName(DummyUserFederationProviderFactory.PROVIDER_NAME);
    dummyFederationProvider.setProviderId(DummyUserFederationProviderFactory.PROVIDER_NAME);
    dummyFederationProvider.setProviderType(UserStorageProvider.class.getName());
    adminClient.realms().realm(REALM_NAME).components().add(dummyFederationProvider);

    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.componentPath(DummyUserFederationProviderFactory.PROVIDER_NAME), dummyFederationProvider, ResourceType.COMPONENT);

    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    user.setEmail("user1@localhost");
    user.setFederationLink(DummyUserFederationProviderFactory.PROVIDER_NAME);

    String userId = createUser(user);

    // fetch user again and see federation link filled in
    UserRepresentation createdUser = realm.users().get(userId).toRepresentation();
    assertNotNull(createdUser);
    assertEquals(user.getFederationLink(), createdUser.getFederationLink());
}
 
Example 10
Source File: TestsHelper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean createTestUser(String username, String password, String realmName) throws IOException {

        Keycloak keycloak = Keycloak.getInstance(
                keycloakBaseUrl,
                "master",
                username,
                password,
                "admin-cli");
        UserRepresentation userRepresentation = new UserRepresentation();
        userRepresentation.setUsername(username);
        userRepresentation.setEnabled(Boolean.TRUE);
        Response response = keycloak.realms().realm(realmName).users().create(userRepresentation);
        String userId = getCreatedId(response);
        response.close();
        CredentialRepresentation rep = new CredentialRepresentation();
        rep.setType(CredentialRepresentation.PASSWORD);
        rep.setValue(password);
        rep.setTemporary(false);
        keycloak.realms().realm(realmName).users().get(userId).resetPassword(rep);
        //add roles
        RoleRepresentation representation = new RoleRepresentation();
        representation.setName("user");

        keycloak.realms().realm(realmName).roles().create(representation);
        RoleRepresentation realmRole =  keycloak.realms().realm(realmName).roles().get("user").toRepresentation();
        keycloak.realms().realm(realmName).users().get(userId).roles().realmLevel().add(Arrays.asList(realmRole));
        return true;

    }
 
Example 11
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void createDuplicatedUser6() {
    createUser();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("user2");
    user.setEmail("user1@LOCALHOST");
    Response response = realm.users().create(user);
    assertEquals(409, response.getStatus());
    response.close();
}
 
Example 12
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void searchByUsernameExactMatch() {
    createUsers();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("username11");
    
    createUser(user);
    
    List<UserRepresentation> users = realm.users().search("username1", true);
    assertEquals(1, users.size());

    users = realm.users().search("user", true);
    assertEquals(0, users.size());
}
 
Example 13
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void searchByLastNameNullForFirstName() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("user1");
    user.setLastName("de Wit");
    user.setRequiredActions(Collections.emptyList());
    user.setEnabled(true);

    createUser(user);

    List<UserRepresentation> users = realm.users().search("wit", null, null);
    assertEquals(1, users.size());
}
 
Example 14
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void updateUserWithExistingUsername() {
    switchEditUsernameAllowedOn(true);
    enableBruteForce(true);
    createUser();

    UserRepresentation userRep = new UserRepresentation();
    userRep.setUsername("user2");

    String createdId = createUser(userRep);

    try {
        UserResource user = realm.users().get(createdId);
        userRep = user.toRepresentation();
        userRep.setUsername("user1");
        user.update(userRep);
        fail("Expected failure");
    } catch (ClientErrorException e) {
        assertEquals(409, e.getResponse().getStatus());

        // TODO adminEvents: Event queue should be empty, but it's not because of bug in UsersResource.updateUser, which sends event earlier than transaction commit.
        // assertAdminEvents.assertEmpty();
        assertAdminEvents.poll();
    } finally {
        enableBruteForce(false);
        switchEditUsernameAllowedOn(false);
    }
}
 
Example 15
Source File: GroupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation testRealmRep = loadTestRealm(testRealms);

    testRealmRep.setEventsEnabled(true);

    List<UserRepresentation> users = testRealmRep.getUsers();

    UserRepresentation user = new UserRepresentation();
    user.setUsername("direct-login");
    user.setEmail("direct-login@localhost");
    user.setEnabled(true);
    List<CredentialRepresentation> credentials = new LinkedList<>();
    CredentialRepresentation credential = new CredentialRepresentation();
    credential.setType(CredentialRepresentation.PASSWORD);
    credential.setValue("password");
    credentials.add(credential);
    user.setCredentials(credentials);
    users.add(user);

    List<ClientRepresentation> clients = testRealmRep.getClients();

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("resource-owner");
    client.setDirectAccessGrantsEnabled(true);
    client.setSecret("secret");
    clients.add(client);
}
 
Example 16
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private List<String> createUsers() {
    List<String> ids = new ArrayList<>();

    for (int i = 1; i < 10; i++) {
        UserRepresentation user = new UserRepresentation();
        user.setUsername("username" + i);
        user.setEmail("user" + i + "@localhost");
        user.setFirstName("First" + i);
        user.setLastName("Last" + i);

        ids.add(createUser(user));
    }

    return ids;
}
 
Example 17
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void createDuplicatedUser7() {
    createUser("user1", "USer1@Localhost");

    UserRepresentation user = new UserRepresentation();
    user.setUsername("user2");
    user.setEmail("user1@localhost");
    Response response = realm.users().create(user);
    assertEquals(409, response.getStatus());
    response.close();

    assertAdminEvents.assertEmpty();

}
 
Example 18
Source File: UserTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void sendResetPasswordEmailSuccessTokenShortLifespan() throws IOException {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setEnabled(true);
    userRep.setUsername("user1");
    userRep.setEmail("[email protected]");

    String id = createUser(userRep);

    final AtomicInteger originalValue = new AtomicInteger();

    RealmRepresentation realmRep = realm.toRepresentation();
    originalValue.set(realmRep.getActionTokenGeneratedByAdminLifespan());
    realmRep.setActionTokenGeneratedByAdminLifespan(60);
    realm.update(realmRep);

    try {
        UserResource user = realm.users().get(id);
        List<String> actions = new LinkedList<>();
        actions.add(UserModel.RequiredAction.UPDATE_PASSWORD.name());
        user.executeActionsEmail(actions);

        Assert.assertEquals(1, greenMail.getReceivedMessages().length);

        MimeMessage message = greenMail.getReceivedMessages()[0];

        String link = MailUtils.getPasswordResetEmailLink(message);

        setTimeOffset(70);

        driver.navigate().to(link);

        errorPage.assertCurrent();
        assertEquals("Action expired.", errorPage.getError());
    } finally {
        setTimeOffset(0);

        realmRep.setActionTokenGeneratedByAdminLifespan(originalValue.get());
        realm.update(realmRep);
    }
}
 
Example 19
Source File: UserTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void sendResetPasswordEmailSuccess() throws IOException {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setEnabled(true);
    userRep.setUsername("user1");
    userRep.setEmail("[email protected]");

    String id = createUser(userRep);

    UserResource user = realm.users().get(id);
    List<String> actions = new LinkedList<>();
    actions.add(UserModel.RequiredAction.UPDATE_PASSWORD.name());
    user.executeActionsEmail(actions);
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + "/execute-actions-email", ResourceType.USER);

    Assert.assertEquals(1, greenMail.getReceivedMessages().length);

    MimeMessage message = greenMail.getReceivedMessages()[0];

    MailUtils.EmailBody body = MailUtils.getBody(message);

    assertTrue(body.getText().contains("Update Password"));
    assertTrue(body.getText().contains("your Admin-client-test account"));
    assertTrue(body.getText().contains("This link will expire within 12 hours"));

    assertTrue(body.getHtml().contains("Update Password"));
    assertTrue(body.getHtml().contains("your Admin-client-test account"));
    assertTrue(body.getHtml().contains("This link will expire within 12 hours"));

    String link = MailUtils.getPasswordResetEmailLink(body);

    driver.navigate().to(link);

    proceedPage.assertCurrent();
    Assert.assertThat(proceedPage.getInfo(), Matchers.containsString("Update Password"));
    proceedPage.clickProceedLink();
    passwordUpdatePage.assertCurrent();

    passwordUpdatePage.changePassword("new-pass", "new-pass");

    assertEquals("Your account has been updated.", PageUtils.getPageTitle(driver));

    driver.navigate().to(link);

    assertEquals("We are sorry...", PageUtils.getPageTitle(driver));
}
 
Example 20
Source File: UserTest.java    From keycloak with Apache License 2.0 3 votes vote down vote up
@Test
public void testAccessUserFromOtherRealm() {
    RealmRepresentation firstRealm = new RealmRepresentation();

    firstRealm.setRealm("first-realm");

    adminClient.realms().create(firstRealm);

    realm = adminClient.realm(firstRealm.getRealm());
    realmId = realm.toRepresentation().getId();

    UserRepresentation firstUser = new UserRepresentation();

    firstUser.setUsername("first");
    firstUser.setEmail("[email protected]");

    firstUser.setId(createUser(firstUser, false));

    RealmRepresentation secondRealm = new RealmRepresentation();

    secondRealm.setRealm("second-realm");

    adminClient.realms().create(secondRealm);

    adminClient.realm(firstRealm.getRealm()).users().get(firstUser.getId()).update(firstUser);

    try {
        adminClient.realm(secondRealm.getRealm()).users().get(firstUser.getId()).toRepresentation();
        fail("Should not have access to firstUser from another realm");
    } catch (NotFoundException nfe) {
        // ignore
    }
}