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

The following examples show how to use org.keycloak.representations.idm.UserRepresentation#setEmail() . 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: 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 2
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 3
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 4
Source File: LDAPBinaryAttributesTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void test03WritableMapper() {
    String mapperId = addPhotoMapper(testingClient);

    // Create user joe with jpegPHoto
    UserRepresentation joe = new UserRepresentation();
    joe.setUsername("joephoto");
    joe.setEmail("[email protected]");
    joe.setAttributes(Collections.singletonMap(LDAPConstants.JPEG_PHOTO, Arrays.asList(JPEG_PHOTO_BASE64)));
    Response response = adminClient.realm("test").users().create(joe);
    response.close();


    // Assert he is found including jpegPhoto
    joe = getUserAndAssertPhoto("joephoto", true);


    // Try to update him with some big non-LDAP mapped attribute. It will fail
    try {
        joe.getAttributes().put("someOtherPhoto", Arrays.asList(JPEG_PHOTO_BASE64));
        adminClient.realm("test").users().get(joe.getId()).update(joe);
        Assert.fail("Not expected to successfully update user");
    } catch (ClientErrorException cee) {
        // Expected
    }

    // Remove jpegPhoto attribute and assert it was successfully removed
    joe.getAttributes().remove("someOtherPhoto");
    joe.getAttributes().remove(LDAPConstants.JPEG_PHOTO);
    adminClient.realm("test").users().get(joe.getId()).update(joe);
    getUserAndAssertPhoto("joephoto", false);
}
 
Example 5
Source File: KcOIDCBrokerWithSignatureTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void createUser() {
    log.debug("creating user for realm " + bc.providerRealmName());

    UserRepresentation user = new UserRepresentation();
    user.setUsername(bc.getUserLogin());
    user.setEmail(bc.getUserEmail());
    user.setEmailVerified(true);
    user.setEnabled(true);

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

    resetUserPassword(realmResource.users().get(userId), bc.getUserPassword(), false);
}
 
Example 6
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void createUserWithEmptyUsername() {
    UserRepresentation user = new UserRepresentation();
    user.setUsername("");
    user.setEmail("user2@localhost");
    Response response = realm.users().create(user);
    assertEquals(400, response.getStatus());
    ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
    Assert.assertEquals("User name is missing", error.getErrorMessage());
    response.close();
}
 
Example 7
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void createUserWithoutUsername() {
    UserRepresentation user = new UserRepresentation();
    user.setEmail("user1@localhost");
    Response response = realm.users().create(user);
    assertEquals(400, response.getStatus());
    ErrorRepresentation error = response.readEntity(ErrorRepresentation.class);
    Assert.assertEquals("User name is missing", error.getErrorMessage());
    response.close();
}
 
Example 8
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 9
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 10
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void updateUserWithRawCredentials() {
    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));

    String id = createUser(user);

    PasswordCredentialModel credential = PasswordCredentialModel
            .createFromCredentialModel(fetchCredentials("user_rawpw"));
    assertNotNull("Expecting credential", credential);
    assertEquals(PasswordPolicy.HASH_ALGORITHM_DEFAULT, credential.getPasswordCredentialData().getAlgorithm());
    assertEquals(PasswordPolicy.HASH_ITERATIONS_DEFAULT, credential.getPasswordCredentialData().getHashIterations());
    assertNotEquals("ABCD", credential.getPasswordSecretData().getValue());
    assertEquals(CredentialRepresentation.PASSWORD, credential.getType());

    UserResource userResource = realm.users().get(id);
    UserRepresentation userRep = userResource.toRepresentation();

    CredentialRepresentation rawPasswordForUpdate = new CredentialRepresentation();
    rawPasswordForUpdate.setValue("EFGH");
    rawPasswordForUpdate.setType(CredentialRepresentation.PASSWORD);
    userRep.setCredentials(Arrays.asList(rawPasswordForUpdate));

    updateUser(userResource, userRep);

    PasswordCredentialModel updatedCredential = PasswordCredentialModel
            .createFromCredentialModel(fetchCredentials("user_rawpw"));
    assertNotNull("Expecting credential", updatedCredential);
    assertEquals(PasswordPolicy.HASH_ALGORITHM_DEFAULT, updatedCredential.getPasswordCredentialData().getAlgorithm());
    assertEquals(PasswordPolicy.HASH_ITERATIONS_DEFAULT, updatedCredential.getPasswordCredentialData().getHashIterations());
    assertNotEquals("EFGH", updatedCredential.getPasswordSecretData().getValue());
    assertEquals(CredentialRepresentation.PASSWORD, updatedCredential.getType());
}
 
Example 11
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void createUserWithDeprecatedCredentialsFormat() throws IOException {
    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);
    String deprecatedCredential = "{\n" +
            "      \"type\" : \"password\",\n" +
            "      \"hashedSaltedValue\" : \"" + pcm.getPasswordSecretData().getValue() + "\",\n" +
            "      \"salt\" : \"" + Base64.encodeBytes(pcm.getPasswordSecretData().getSalt()) + "\",\n" +
            "      \"hashIterations\" : " + pcm.getPasswordCredentialData().getHashIterations() + ",\n" +
            "      \"algorithm\" : \"" + pcm.getPasswordCredentialData().getAlgorithm() + "\"\n" +
            "    }";

    CredentialRepresentation deprecatedHashedPassword = JsonSerialization.readValue(deprecatedCredential, CredentialRepresentation.class);
    Assert.assertNotNull(deprecatedHashedPassword.getHashedSaltedValue());
    Assert.assertNull(deprecatedHashedPassword.getCredentialData());

    deprecatedHashedPassword.setCreatedDate(1001l);
    deprecatedHashedPassword.setUserLabel("deviceX");
    deprecatedHashedPassword.setType(CredentialRepresentation.PASSWORD);

    user.setCredentials(Arrays.asList(deprecatedHashedPassword));

    createUser(user, false);

    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());
}
 
Example 12
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 13
Source File: KcOidcBrokerLogoutTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void createUser() {
    log.debug("creating user for realm " + bc.providerRealmName());

    final UserRepresentation user = new UserRepresentation();
    user.setUsername(bc.getUserLogin());
    user.setEmail(bc.getUserEmail());
    user.setEmailVerified(true);
    user.setEnabled(true);

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

    resetUserPassword(realmResource.users().get(userId), bc.getUserPassword(), false);
}
 
Example 14
Source File: PartialImportTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void addClients(boolean withServiceAccounts) throws IOException {
    List<ClientRepresentation> clients = new ArrayList<>();
    List<UserRepresentation> serviceAccounts = new ArrayList<>();

    for (int i = 0; i < NUM_ENTITIES; i++) {
        ClientRepresentation client = new ClientRepresentation();
        client.setClientId(CLIENT_PREFIX + i);
        client.setName(CLIENT_PREFIX + i);
        clients.add(client);
        if (withServiceAccounts) {
            client.setServiceAccountsEnabled(true);
            client.setBearerOnly(false);
            client.setPublicClient(false);
            client.setAuthorizationSettings(resourceServerSampleSettings);
            client.setAuthorizationServicesEnabled(true);
            // create the user service account
            UserRepresentation serviceAccount = new UserRepresentation();
            serviceAccount.setUsername(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + client.getClientId());
            serviceAccount.setEnabled(true);
            serviceAccount.setEmail(serviceAccount.getUsername() + "@placeholder.org");
            serviceAccount.setServiceAccountClientId(client.getClientId());
            serviceAccounts.add(serviceAccount);
        }
    }

    if (withServiceAccounts) {
        if (piRep.getUsers() == null) {
            piRep.setUsers(new ArrayList<>());
        }
        piRep.getUsers().addAll(serviceAccounts);
    }
    piRep.setClients(clients);
}
 
Example 15
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 16
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 17
Source File: UserTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void sendResetPasswordEmailWithRedirect() 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);

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("myclient");
    client.setRedirectUris(new LinkedList<>());
    client.getRedirectUris().add("http://myclient.com/*");
    client.setName("myclient");
    client.setEnabled(true);
    Response response = realm.clients().create(client);
    String createdId = ApiUtil.getCreatedId(response);
    assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.clientResourcePath(createdId), client, ResourceType.CLIENT);


    List<String> actions = new LinkedList<>();
    actions.add(UserModel.RequiredAction.UPDATE_PASSWORD.name());

    try {
        // test that an invalid redirect uri is rejected.
        user.executeActionsEmail("myclient", "http://unregistered-uri.com/", actions);
        fail("Expected failure");
    } catch (ClientErrorException e) {
        assertEquals(400, e.getResponse().getStatus());

        ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class);
        Assert.assertEquals("Invalid redirect uri.", error.getErrorMessage());
    }


    user.executeActionsEmail("myclient", "http://myclient.com/home.html", 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];

    String link = MailUtils.getPasswordResetEmailLink(message);

    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.", driver.findElement(By.id("kc-page-title")).getText());

    String pageSource = driver.getPageSource();

    // check to make sure the back link is set.
    Assert.assertTrue(pageSource.contains("http://myclient.com/home.html"));

    driver.navigate().to(link);

    assertEquals("We are sorry...", PageUtils.getPageTitle(driver));
}
 
Example 18
Source File: AbstractClientRegistrationTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void addTestRealms(List<RealmRepresentation> testRealms) {
    RealmRepresentation rep = new RealmRepresentation();
    rep.setEnabled(true);
    rep.setId(REALM_NAME);
    rep.setRealm(REALM_NAME);
    rep.setUsers(new LinkedList<UserRepresentation>());

    LinkedList<CredentialRepresentation> credentials = new LinkedList<>();
    CredentialRepresentation password = new CredentialRepresentation();
    password.setType(CredentialRepresentation.PASSWORD);
    password.setValue("password");
    credentials.add(password);

    UserRepresentation user = new UserRepresentation();
    user.setEnabled(true);
    user.setUsername("manage-clients");
    user.setCredentials(credentials);
    user.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.MANAGE_CLIENTS)));

    rep.getUsers().add(user);

    UserRepresentation user2 = new UserRepresentation();
    user2.setEnabled(true);
    user2.setUsername("create-clients");
    user2.setCredentials(credentials);
    user2.setClientRoles(Collections.singletonMap(Constants.REALM_MANAGEMENT_CLIENT_ID, Collections.singletonList(AdminRoles.CREATE_CLIENT)));

    rep.getUsers().add(user2);

    UserRepresentation user3 = new UserRepresentation();
    user3.setEnabled(true);
    user3.setUsername("no-access");
    user3.setCredentials(credentials);

    rep.getUsers().add(user3);

    UserRepresentation appUser = new UserRepresentation();
    appUser.setEnabled(true);
    appUser.setUsername("test-user");
    appUser.setEmail("test-user@localhost");
    appUser.setCredentials(credentials);

    rep.getUsers().add(appUser);

    testRealms.add(rep);
}
 
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
    }
}