Search in sources :

Example 81 with AuthServerContainerExclude

use of org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude in project keycloak by keycloak.

the class UserTest method sendResetPasswordEmailSuccessTwoLinksReverse.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void sendResetPasswordEmailSuccessTwoLinksReverse() throws IOException {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setEnabled(true);
    userRep.setUsername("user1");
    userRep.setEmail("user1@test.com");
    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);
    user.executeActionsEmail(actions);
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + "/execute-actions-email", ResourceType.USER);
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + "/execute-actions-email", ResourceType.USER);
    Assert.assertEquals(2, greenMail.getReceivedMessages().length);
    int i = 1;
    for (int j = greenMail.getReceivedMessages().length - 1; j >= 0; j--) {
        MimeMessage message = greenMail.getReceivedMessages()[j];
        String link = MailUtils.getPasswordResetEmailLink(message);
        driver.navigate().to(link);
        proceedPage.assertCurrent();
        assertThat(proceedPage.getInfo(), Matchers.containsString("Update Password"));
        proceedPage.clickProceedLink();
        passwordUpdatePage.assertCurrent();
        passwordUpdatePage.changePassword("new-pass" + i, "new-pass" + i);
        i++;
        assertEquals("Your account has been updated.", PageUtils.getPageTitle(driver));
    }
    for (MimeMessage message : greenMail.getReceivedMessages()) {
        String link = MailUtils.getPasswordResetEmailLink(message);
        driver.navigate().to(link);
        errorPage.assertCurrent();
    }
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) UserResource(org.keycloak.admin.client.resource.UserResource) LinkedList(java.util.LinkedList) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test)

Example 82 with AuthServerContainerExclude

use of org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude in project keycloak by keycloak.

the class UserTest method sendResetPasswordEmailWithRedirectAndCustomLifespan.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void sendResetPasswordEmailWithRedirectAndCustomLifespan() throws IOException {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setEnabled(true);
    userRep.setUsername("user1");
    userRep.setEmail("user1@test.com");
    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());
    final int lifespan = (int) TimeUnit.DAYS.toSeconds(128);
    try {
        // test that an invalid redirect uri is rejected.
        user.executeActionsEmail("myclient", "http://unregistered-uri.com/", lifespan, 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", lifespan, 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("This link will expire within 128 days"));
    assertTrue(body.getHtml().contains("This link will expire within 128 days"));
    String link = MailUtils.getPasswordResetEmailLink(message);
    String token = link.substring(link.indexOf("key=") + "key=".length());
    try {
        final AccessToken accessToken = TokenVerifier.create(token, AccessToken.class).getToken();
        assertEquals(lifespan, accessToken.getExpiration() - accessToken.getIssuedAt());
    } catch (VerificationException e) {
        throw new IOException(e);
    }
    driver.navigate().to(link);
    proceedPage.assertCurrent();
    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));
}
Also used : UserResource(org.keycloak.admin.client.resource.UserResource) IOException(java.io.IOException) LinkedList(java.util.LinkedList) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Response(javax.ws.rs.core.Response) MimeMessage(javax.mail.internet.MimeMessage) ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) AccessToken(org.keycloak.representations.AccessToken) ClientErrorException(javax.ws.rs.ClientErrorException) VerificationException(org.keycloak.common.VerificationException) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) MailUtils(org.keycloak.testsuite.util.MailUtils) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test)

Example 83 with AuthServerContainerExclude

use of org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude in project keycloak by keycloak.

the class FineGrainAdminUnitTest method testWithTokenExchange.

/**
 * KEYCLOAK-7406
 *
 * @throws Exception
 */
@Test
@UncaughtServerErrorExpected
@AuthServerContainerExclude(AuthServer.REMOTE)
@EnableFeature(value = Profile.Feature.TOKEN_EXCHANGE, skipRestart = true)
public void testWithTokenExchange() throws Exception {
    String exchanged = checkTokenExchange(true);
    Assert.assertNotNull(exchanged);
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", AuthRealm.MASTER, Constants.ADMIN_CLI_CLIENT_ID, exchanged, TLSUtils.initializeTLS())) {
        Assert.assertNotNull(client.realm("master").roles().get("offline_access"));
    }
}
Also used : Keycloak(org.keycloak.admin.client.Keycloak) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test) EnableFeature(org.keycloak.testsuite.arquillian.annotation.EnableFeature) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 84 with AuthServerContainerExclude

use of org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude in project keycloak by keycloak.

the class FineGrainAdminUnitTest method testUserPagination.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testUserPagination() {
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        session.getContext().setRealm(realm);
        GroupModel customerAGroup = session.groups().createGroup(realm, "Customer A");
        UserModel customerAManager = session.users().addUser(realm, "customer-a-manager");
        session.userCredentialManager().updateCredential(realm, customerAManager, UserCredentialModel.password("password"));
        ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
        customerAManager.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_USERS));
        customerAManager.setEnabled(true);
        UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user");
        session.userCredentialManager().updateCredential(realm, regularAdminUser, UserCredentialModel.password("password"));
        regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.VIEW_USERS));
        regularAdminUser.setEnabled(true);
        AdminPermissionManagement management = AdminPermissions.management(session, realm);
        GroupPermissionManagement groupPermission = management.groups();
        groupPermission.setPermissionsEnabled(customerAGroup, true);
        UserPolicyRepresentation userPolicyRepresentation = new UserPolicyRepresentation();
        userPolicyRepresentation.setName("Only " + customerAManager.getUsername());
        userPolicyRepresentation.addUser(customerAManager.getId());
        Policy policy = groupPermission.viewMembersPermission(customerAGroup);
        AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
        Policy userPolicy = provider.getStoreFactory().getPolicyStore().create(userPolicyRepresentation, management.realmResourceServer());
        policy.addAssociatedPolicy(RepresentationToModel.toModel(userPolicyRepresentation, provider, userPolicy));
        for (int i = 0; i < 20; i++) {
            UserModel userModel = session.users().addUser(realm, "a" + i);
            userModel.setFirstName("test");
        }
        for (int i = 20; i < 40; i++) {
            UserModel userModel = session.users().addUser(realm, "b" + i);
            userModel.setFirstName("test");
            userModel.joinGroup(customerAGroup);
        }
    });
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "customer-a-manager", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<UserRepresentation> result = client.realm("test").users().search(null, "test", null, null, -1, 20);
        Assert.assertEquals(20, result.size());
        Assert.assertThat(result, Matchers.everyItem(Matchers.hasProperty("username", Matchers.startsWith("b"))));
        result = client.realm("test").users().search(null, "test", null, null, 20, 40);
        Assert.assertEquals(0, result.size());
    }
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "regular-admin-user", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<UserRepresentation> result = client.realm("test").users().search(null, "test", null, null, -1, 20);
        Assert.assertEquals(20, result.size());
        Assert.assertThat(result, Matchers.everyItem(Matchers.hasProperty("username", Matchers.startsWith("a"))));
        client.realm("test").users().search(null, null, null, null, -1, -1);
        Assert.assertEquals(20, result.size());
        Assert.assertThat(result, Matchers.everyItem(Matchers.hasProperty("username", Matchers.startsWith("a"))));
    }
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "customer-a-manager", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<UserRepresentation> result = client.realm("test").users().search(null, null, null, null, -1, 20);
        Assert.assertEquals(20, result.size());
        Assert.assertThat(result, Matchers.everyItem(Matchers.hasProperty("username", Matchers.startsWith("b"))));
        result = client.realm("test").users().search("test", -1, 20, false);
        Assert.assertEquals(20, result.size());
        Assert.assertThat(result, Matchers.everyItem(Matchers.hasProperty("username", Matchers.startsWith("b"))));
        result = client.realm("test").users().search("a", -1, 20, false);
        Assert.assertEquals(0, result.size());
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) GroupModel(org.keycloak.models.GroupModel) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) Keycloak(org.keycloak.admin.client.Keycloak) GroupPermissionManagement(org.keycloak.services.resources.admin.permissions.GroupPermissionManagement) AdminPermissionManagement(org.keycloak.services.resources.admin.permissions.AdminPermissionManagement) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 85 with AuthServerContainerExclude

use of org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude in project keycloak by keycloak.

the class FineGrainAdminUnitTest method testMasterRealm.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testMasterRealm() throws Exception {
    // test that master realm can still perform operations when policies are in place
    // 
    testingClient.server().run(FineGrainAdminUnitTest::setupPolices);
    testingClient.server().run(FineGrainAdminUnitTest::setupUsers);
    UserRepresentation user1 = adminClient.realm(TEST).users().search("user1").get(0);
    RoleRepresentation realmRole = adminClient.realm(TEST).roles().get("realm-role").toRepresentation();
    List<RoleRepresentation> realmRoleSet = new LinkedList<>();
    realmRoleSet.add(realmRole);
    RoleRepresentation realmRole2 = adminClient.realm(TEST).roles().get("realm-role2").toRepresentation();
    List<RoleRepresentation> realmRole2Set = new LinkedList<>();
    realmRole2Set.add(realmRole);
    ClientRepresentation client = adminClient.realm(TEST).clients().findByClientId(CLIENT_NAME).get(0);
    RoleRepresentation clientRole = adminClient.realm(TEST).clients().get(client.getId()).roles().get("client-role").toRepresentation();
    List<RoleRepresentation> clientRoleSet = new LinkedList<>();
    clientRoleSet.add(clientRole);
    {
        try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting())) {
            realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().add(realmRoleSet);
            List<RoleRepresentation> roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll();
            Assert.assertTrue(roles.stream().anyMatch((r) -> {
                return r.getName().equals("realm-role");
            }));
            realmClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().remove(realmRoleSet);
            roles = adminClient.realm(TEST).users().get(user1.getId()).roles().realmLevel().listAll();
            Assert.assertTrue(roles.stream().noneMatch((r) -> {
                return r.getName().equals("realm-role");
            }));
            realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).add(clientRoleSet);
            roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll();
            Assert.assertTrue(roles.stream().anyMatch((r) -> {
                return r.getName().equals("client-role");
            }));
            realmClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).remove(clientRoleSet);
            roles = adminClient.realm(TEST).users().get(user1.getId()).roles().clientLevel(client.getId()).listAll();
            Assert.assertTrue(roles.stream().noneMatch((r) -> {
                return r.getName().equals("client-role");
            }));
        }
    }
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Keycloak(org.keycloak.admin.client.Keycloak) LinkedList(java.util.LinkedList) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)108 AuthServerContainerExclude (org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude)108 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)31 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)30 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)29 Matchers.containsString (org.hamcrest.Matchers.containsString)28 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)27 Response (javax.ws.rs.core.Response)24 UserResource (org.keycloak.admin.client.resource.UserResource)21 AbstractAuthenticationTest (org.keycloak.testsuite.admin.authentication.AbstractAuthenticationTest)21 SocialLoginTest (org.keycloak.testsuite.broker.SocialLoginTest)21 MimeMessage (javax.mail.internet.MimeMessage)14 OAuthClient (org.keycloak.testsuite.util.OAuthClient)14 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)13 ComponentRepresentation (org.keycloak.representations.idm.ComponentRepresentation)12 LinkedList (java.util.LinkedList)11 List (java.util.List)9 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)9 HashMap (java.util.HashMap)8 IOException (java.io.IOException)7