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

The following examples show how to use org.keycloak.representations.idm.UserRepresentation#setLastName() . 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: ConsentsTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
@Before
public void createUser() {
    log.debug("creating user for realm " + providerRealmName());

    UserRepresentation user = new UserRepresentation();
    user.setUsername(getUserLogin());
    user.setEmail(getUserEmail());
    user.setFirstName(getUserFirstName());
    user.setLastName(getUserLastName());
    user.setEmailVerified(true);
    user.setEnabled(true);

    RealmResource realmResource = adminClient.realm(providerRealmName());
    String userId = createUserWithAdminClient(realmResource, user);

    resetUserPassword(realmResource.users().get(userId), getUserPassword(), false);
}
 
Example 3
Source File: UserSetup.java    From keycloak-custom-protocol-mapper-example with Apache License 2.0 5 votes vote down vote up
public String createUser(String name, String firstName, String lastName) {
    UserRepresentation user = new UserRepresentation();
    user.setUsername(name);
    user.setFirstName(firstName);
    user.setLastName(lastName);
    user.setEnabled(true);
    user.setCredentials(Arrays.asList(createPassword(PASSWORD)));
    Response response = users.create(user);
    return getCreatedId(response);
}
 
Example 4
Source File: DockerTestRealmSetup.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void configureUser(final RealmRepresentation dockerRealm, final String username, final String password) {
    final UserRepresentation dockerUser = new UserRepresentation();
    dockerUser.setUsername(username);
    dockerUser.setEnabled(true);
    dockerUser.setEmail("[email protected]");
    dockerUser.setFirstName("docker");
    dockerUser.setLastName("user");

    final CredentialRepresentation dockerUserCreds = new CredentialRepresentation();
    dockerUserCreds.setType(CredentialRepresentation.PASSWORD);
    dockerUserCreds.setValue(password);
    dockerUser.setCredentials(Collections.singletonList(dockerUserCreds));

    dockerRealm.setUsers(Collections.singletonList(dockerUser));
}
 
Example 5
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 6
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 7
Source File: AbstractKeycloakTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static UserRepresentation createUserRepresentation(String username, String email, String firstName, String lastName, boolean enabled) {
    UserRepresentation user = new UserRepresentation();
    user.setUsername(username);
    user.setEmail(email);
    user.setFirstName(firstName);
    user.setLastName(lastName);
    user.setEnabled(enabled);
    return user;
}
 
Example 8
Source File: AbstractUserAttributeMapperTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void testValueMapping(Map<String, List<String>> initialUserAttributes, Map<String, List<String>> modifiedUserAttributes, Map<String, List<String>> assertedModifiedAttributes) {
    String email = bc.getUserEmail();
    createUserInProviderRealm(initialUserAttributes);

    logInAsUserInIDPForFirstTime();
    UserRepresentation userRep = findUser(bc.consumerRealmName(), bc.getUserLogin(), email);

    assertUserAttributes(initialUserAttributes, userRep);

    logoutFromRealm(getConsumerRoot(), bc.consumerRealmName());

    // update user in provider realm
    UserRepresentation userRepProvider = findUser(bc.providerRealmName(), bc.getUserLogin(), email);
    Map<String, List<String>> modifiedWithoutSpecialKeys = modifiedUserAttributes.entrySet().stream()
      .filter(a -> ! PROTECTED_NAMES.contains(a.getKey()))
      .filter(a -> a.getValue() != null)  // Remove empty attributes
      .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
    userRepProvider.setAttributes(modifiedWithoutSpecialKeys);
    if (modifiedUserAttributes.containsKey("email")) {
        userRepProvider.setEmail(modifiedUserAttributes.get("email").get(0));
        email = modifiedUserAttributes.get("email").get(0);
    }
    if (modifiedUserAttributes.containsKey("firstName")) {
        userRepProvider.setFirstName(modifiedUserAttributes.get("firstName").get(0));
    }
    if (modifiedUserAttributes.containsKey("lastName")) {
        userRepProvider.setLastName(modifiedUserAttributes.get("lastName").get(0));
    }
    adminClient.realm(bc.providerRealmName()).users().get(userRepProvider.getId()).update(userRepProvider);

    logInAsUserInIDP();
    userRep = findUser(bc.consumerRealmName(), bc.getUserLogin(), email);

    assertUserAttributes(assertedModifiedAttributes, userRep);
}
 
Example 9
Source File: AccountFormServiceTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void changeProfileEmailAsUsernameAndEditUsernameEnabled() throws Exception {
    setEditUsernameAllowed(true);
    setRegistrationEmailAsUsername(true);

    profilePage.open();
    loginPage.login("test-user@localhost", "password");
    assertFalse(driver.findElements(By.id("username")).size() > 0);

    profilePage.updateProfile("New First", "New Last", "new-email@email");

    Assert.assertEquals("Your account has been updated.", profilePage.getSuccess());
    Assert.assertEquals("New First", profilePage.getFirstName());
    Assert.assertEquals("New Last", profilePage.getLastName());
    Assert.assertEquals("new-email@email", profilePage.getEmail());

    List<UserRepresentation> list = adminClient.realm("test").users().search(null, null, null, "new-email@email", null, null);
    assertEquals(1, list.size());

    UserRepresentation user = list.get(0);

    assertEquals("new-email@email", user.getUsername());

    // Revert

    user.setUsername("test-user@localhost");
    user.setFirstName("Tom");
    user.setLastName("Brady");
    user.setEmail("test-user@localhost");
    adminClient.realm("test").users().get(user.getId()).update(user);

    setRegistrationEmailAsUsername(false);
    setEditUsernameAllowed(false);
}
 
Example 10
Source File: UserInvalidationClusterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected UserRepresentation createTestEntityRepresentation() {
    String firstName = "user";
    String lastName = RandomStringUtils.randomAlphabetic(5);
    UserRepresentation user = new UserRepresentation();
    user.setUsername(firstName + "_" + lastName);
    user.setEmail(user.getUsername() + "@email.test");
    user.setFirstName(firstName);
    user.setLastName(lastName);
    return user;
}
 
Example 11
Source File: PersonalInfoTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void setTestUser() {
    testUser2 = new UserRepresentation();
    testUser2.setUsername("vmuzikar");
    testUser2.setEmail("[email protected]");
    testUser2.setFirstName("Václav");
    testUser2.setLastName("Muzikář");
    ApiUtil.removeUserByUsername(testRealmResource(), testUser2.getUsername());
}
 
Example 12
Source File: TermsAndConditionsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testSelfRegisteredUser() {
    // enable self-registration
    RealmResource realmResource = adminClient.realm(REALM);
    RealmRepresentation realmRepresentation = realmResource.toRepresentation();
    realmRepresentation.setRegistrationAllowed(true);
    realmResource.update(realmRepresentation);
    
    // enable terms
    setRequiredActionEnabled(REALM, RequiredActions.TERMS_AND_CONDITIONS, true, true);
    
    // self-register
    CredentialRepresentation mrBurnsPassword = new CredentialRepresentation();
    mrBurnsPassword.setType(CredentialRepresentation.PASSWORD);
    mrBurnsPassword.setValue("Excellent.");
    
    List<CredentialRepresentation> credentials = new ArrayList<CredentialRepresentation>();
    credentials.add(mrBurnsPassword);
    
    UserRepresentation mrBurns = new UserRepresentation();
    mrBurns.setUsername("mrburns");
    mrBurns.setFirstName("Montgomery");
    mrBurns.setLastName("Burns");
    mrBurns.setEmail("[email protected]");
    mrBurns.setCredentials(credentials);
    
    testRealmAdminConsolePage.navigateTo();
    testRealmLoginPage.form().register();
    
    registrationPage.register(mrBurns);
    
    // test t&c
    Assert.assertTrue(termsAndConditionsPage.isCurrent());
    
    // disable terms
    setRequiredActionEnabled(REALM, RequiredActions.TERMS_AND_CONDITIONS, false, false);
}
 
Example 13
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractFirstBrokerLoginTest#testLinkAccountByReauthenticationWithPassword_browserButtons
 */
@Test
public void testLinkAccountByLogInAsUserUsingBrowserButtons() {
    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    String userId = createUser("consumer");
    UserResource providerUser = adminClient.realm(bc.providerRealmName()).users().get(this.userId);
    UserRepresentation userResource = providerUser.toRepresentation();

    userResource.setEmail(USER_EMAIL);
    userResource.setFirstName("FirstName");
    userResource.setLastName("LastName");

    providerUser.update(userResource);

    driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));

    log.debug("Clicking social " + bc.getIDPAlias());
    loginPage.clickSocial(bc.getIDPAlias());
    waitForPage(driver, "log in to", true);
    Assert.assertTrue("Driver should be on the provider realm page right now",
            driver.getCurrentUrl().contains("/auth/realms/" + bc.providerRealmName() + "/"));
    log.debug("Logging in");

    // we need to force a login failure in order to be able to use back button to go back to login page at the provider
    loginPage.login("invalid", bc.getUserPassword());
    loginPage.login(bc.getUserLogin(), bc.getUserPassword());

    waitForPage(driver, "account already exists", false);

    // Click browser 'back' and then 'forward' and then continue
    driver.navigate().back();
    assertTrue(driver.getPageSource().contains("You are already logged in."));
    driver.navigate().forward(); // here a new execution ID is added to the URL using JS, see below
    idpConfirmLinkPage.assertCurrent();

    // Click browser 'back' on review profile page
    idpConfirmLinkPage.clickReviewProfile();
    waitForPage(driver, "update account information", false);
    updateAccountInformationPage.assertCurrent();
    driver.navigate().back();
    // JS-capable browsers (i.e. all except HtmlUnit) add a new execution ID to the URL which then causes the login expire page to appear (because the old ID and new ID don't match)
    if (!(driver instanceof HtmlUnitDriver)) {
        loginExpiredPage.assertCurrent();
        loginExpiredPage.clickLoginContinueLink();
    }
    waitForPage(driver, "update account information", false);
    updateAccountInformationPage.assertCurrent();
    updateAccountInformationPage.updateAccountInformation(bc.getUserEmail(), "FirstName", "LastName");

    waitForPage(driver, "account already exists", false);
    idpConfirmLinkPage.assertCurrent();
    idpConfirmLinkPage.clickLinkAccount();

    // Login screen shown. Username is prefilled. Registration link and social buttons are not shown
    assertEquals("consumer", loginPage.getUsername());
    assertTrue(loginPage.isUsernameInputEnabled());

    assertEquals("Authenticate to link your account with " + bc.getIDPAlias(), this.loginPage.getInfoMessage());

    try {
        loginPage.findSocialButton(bc.getIDPAlias());
        Assert.fail("Not expected to see social button with " + bc.getIDPAlias());
    } catch (NoSuchElementException expected) {
    }

    // Use correct password now
    loginPage.login("password");
    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();
    assertNumFederatedIdentities(userId, 1);
}
 
Example 14
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractFirstBrokerLoginTest#testLinkAccountByReauthentication_forgetPassword
 */
@Test
public void testLinkAccountByLogInAsUserAfterResettingPassword() throws InterruptedException {
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realm.toRepresentation();

    realmRep.setResetPasswordAllowed(true);

    realm.update(realmRep);

    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    String existingUser = createUser("consumer");
    UserResource providerUser = adminClient.realm(bc.providerRealmName()).users().get(userId);
    UserRepresentation userResource = providerUser.toRepresentation();

    userResource.setEmail(USER_EMAIL);
    userResource.setFirstName("FirstName");
    userResource.setLastName("LastName");

    providerUser.update(userResource);

    driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));

    logInWithBroker(bc);

    waitForPage(driver, "account already exists", false);
    idpConfirmLinkPage.assertCurrent();
    idpConfirmLinkPage.clickLinkAccount();

    configureSMTPServer();

    this.loginPage.resetPassword();
    this.loginPasswordResetPage.assertCurrent();
    this.loginPasswordResetPage.changePassword();
    assertEquals("You should receive an email shortly with further instructions.", this.loginPage.getSuccessMessage());
    assertEquals(1, MailServer.getReceivedMessages().length);
    MimeMessage message = MailServer.getLastReceivedMessage();
    String linkFromMail = assertEmailAndGetUrl(MailServerConfiguration.FROM, USER_EMAIL,
            "credentials", false);

    driver.navigate().to(linkFromMail.trim());

    // Need to update password now
    this.passwordUpdatePage.assertCurrent();
    this.passwordUpdatePage.changePassword("password", "password");

    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();
    assertNumFederatedIdentities(existingUser, 1);
}
 
Example 15
Source File: AbstractFirstBrokerLoginTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractFirstBrokerLoginTest#testLinkAccountByReauthentication_forgetPassword_differentBrowser
 */
@Test
public void testLinkAccountByLogInAsUserAfterResettingPasswordUsingDifferentBrowsers() throws InterruptedException {
    RealmResource realm = adminClient.realm(bc.consumerRealmName());
    RealmRepresentation realmRep = realm.toRepresentation();

    realmRep.setResetPasswordAllowed(true);

    realm.update(realmRep);

    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    String existingUser = createUser("consumer");
    UserResource providerUser = adminClient.realm(bc.providerRealmName()).users().get(userId);
    UserRepresentation userResource = providerUser.toRepresentation();

    userResource.setEmail(USER_EMAIL);
    userResource.setFirstName("FirstName");
    userResource.setLastName("LastName");

    providerUser.update(userResource);

    driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));
    logInWithBroker(bc);

    waitForPage(driver, "account already exists", false);
    idpConfirmLinkPage.assertCurrent();
    idpConfirmLinkPage.clickLinkAccount();

    configureSMTPServer();

    this.loginPage.resetPassword();
    this.loginPasswordResetPage.assertCurrent();
    this.loginPasswordResetPage.changePassword();
    assertEquals("You should receive an email shortly with further instructions.", this.loginPage.getSuccessMessage());
    assertEquals(1, MailServer.getReceivedMessages().length);
    MimeMessage message = MailServer.getLastReceivedMessage();
    String linkFromMail = assertEmailAndGetUrl(MailServerConfiguration.FROM, USER_EMAIL,
            "credentials", false);

    driver2.navigate().to(linkFromMail.trim());
    removeSMTPConfiguration(realm);

    // Need to update password now
    LoginPasswordUpdatePage passwordUpdatePage = PageFactory.initElements(driver2, LoginPasswordUpdatePage.class);
    passwordUpdatePage.changePassword("password", "password");

    assertNumFederatedIdentities(existingUser, 0);

    log.debug("Clicking social " + bc.getIDPAlias());
    loginPage.clickSocial(bc.getIDPAlias());

    try {
        waitForPage(driver, "account already exists", false);
    } catch (Exception e) {
        // this is a workaround to make this test work for both oidc and saml. when doing oidc the browser is redirected to the login page to finish the linking
        loginPage.login(bc.getUserLogin(), bc.getUserPassword());
    }

    waitForPage(driver, "account already exists", false);
    idpConfirmLinkPage.assertCurrent();
    idpConfirmLinkPage.clickLinkAccount();

    loginPage.login("password");
    assertNumFederatedIdentities(existingUser, 1);
}
 
Example 16
Source File: LDAPNoMSADTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultivaluedRDN() {
    testingClient.server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        ComponentModel snMapper = null;

        // Create LDAP user with both "uid" and "sn" attribute in RDN. Something like "uid=johnkeycloak3+sn=Doe3,ou=People,dc=domain,dc=com"
        LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
        LDAPObject john2 = LDAPTestUtils.addLDAPUser(ldapProvider, appRealm, "johnkeycloak3", "John3", "Doe3", "[email protected]", null, "4321");

        john2.addRdnAttributeName("sn");
        ldapProvider.getLdapIdentityStore().update(john2);

        // Assert DN was changed
        String rdnAttrName = ldapProvider.getLdapIdentityStore().getConfig().getRdnLdapAttribute();
        Assert.assertEquals(rdnAttrName + "=johnkeycloak3+sn=Doe3", john2.getDn().getFirstRdn().toString());
    });

    // Update some user attributes not mapped to DN. DN won't be changed
    String userId = testRealm().users().search("johnkeycloak3").get(0).getId();
    UserResource user = testRealm().users().get(userId);

    UserRepresentation userRep = user.toRepresentation();
    assertFirstRDNEndsWith(userRep, "johnkeycloak3", "Doe3");
    userRep.setEmail("[email protected]");
    user.update(userRep);

    userRep = user.toRepresentation();
    Assert.assertEquals("[email protected]", userRep.getEmail());
    assertFirstRDNEndsWith(userRep, "johnkeycloak3", "Doe3");

    // Update some user attributes mapped to DN. DN will be changed
    userRep.setLastName("Doe3Changed");
    user.update(userRep);

    userRep = user.toRepresentation();

    // ApacheDS bug causes that attribute, which was added to DN, is lowercased. Works for other LDAPs (RHDS, OpenLDAP)
    Assert.assertThat("Doe3Changed", equalToIgnoringCase(userRep.getLastName()));
    assertFirstRDNEndsWith(userRep, "johnkeycloak3", "Doe3Changed");

    // Remove user
    user.remove();
}