Search in sources :

Example 86 with AuthServerContainerExclude

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

the class FineGrainAdminUnitTest method testClientsSearch.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testClientsSearch() {
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        session.getContext().setRealm(realm);
        ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
        UserModel regularAdminUser = session.users().addUser(realm, "regular-admin-user");
        session.userCredentialManager().updateCredential(realm, regularAdminUser, UserCredentialModel.password("password"));
        regularAdminUser.grantRole(realmAdminClient.getRole(AdminRoles.QUERY_CLIENTS));
        regularAdminUser.setEnabled(true);
        UserPolicyRepresentation userPolicyRepresentation = new UserPolicyRepresentation();
        userPolicyRepresentation.setName("Only " + regularAdminUser.getUsername());
        userPolicyRepresentation.addUser(regularAdminUser.getId());
        for (int i = 0; i < 30; i++) {
            realm.addClient("client-search-" + (i < 10 ? "0" + i : i));
        }
        AdminPermissionManagement management = AdminPermissions.management(session, realm);
        ClientPermissionManagement clientPermission = management.clients();
        ClientModel clientModel = realm.getClientByClientId("client-search-09");
        clientPermission.setPermissionsEnabled(clientModel, true);
        Policy policy = clientPermission.viewPermission(clientModel);
        AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
        Policy userPolicy = provider.getStoreFactory().getPolicyStore().create(userPolicyRepresentation, management.realmResourceServer());
        policy.addAssociatedPolicy(RepresentationToModel.toModel(userPolicyRepresentation, provider, userPolicy));
    });
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "regular-admin-user", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<ClientRepresentation> result = client.realm("test").clients().findAll("client-search-", true, true, 0, 5);
        Assert.assertEquals(1, result.size());
        Assert.assertEquals("client-search-09", result.get(0).getClientId());
    }
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        session.getContext().setRealm(realm);
        AdminPermissionManagement management = AdminPermissions.management(session, realm);
        ClientPermissionManagement clientPermission = management.clients();
        ClientModel clientModel = realm.getClientByClientId("client-search-10");
        clientPermission.setPermissionsEnabled(clientModel, true);
        Policy policy = clientPermission.viewPermission(clientModel);
        AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
        ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
        policy.addAssociatedPolicy(provider.getStoreFactory().getPolicyStore().findByName("Only regular-admin-user", realmAdminClient.getId()));
    });
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "regular-admin-user", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<ClientRepresentation> result = client.realm("test").clients().findAll("client-search-", true, true, -1, -1);
        Assert.assertEquals(2, result.size());
    }
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "regular-admin-user", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<ClientRepresentation> result = client.realm("test").clients().findAll(null, true, false, 0, 5);
        Assert.assertEquals(2, result.size());
    }
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "regular-admin-user", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<ClientRepresentation> result = client.realm("test").clients().findAll(null, true, false, 0, 1);
        Assert.assertEquals(1, result.size());
        Assert.assertThat(result, Matchers.hasItem(Matchers.hasProperty("clientId", Matchers.is("client-search-09"))));
        result = client.realm("test").clients().findAll(null, true, false, 1, 1);
        Assert.assertThat(result, Matchers.hasItem(Matchers.hasProperty("clientId", Matchers.is("client-search-10"))));
        Assert.assertEquals(1, result.size());
        result = client.realm("test").clients().findAll(null, true, false, 2, 1);
        Assert.assertTrue(result.isEmpty());
    }
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "regular-admin-user", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<ClientRepresentation> result = client.realm("test").clients().findAll(null, true, false, -1, -1);
        Assert.assertEquals(2, result.size());
    }
    testingClient.server().run(session -> {
        RealmModel realm = session.realms().getRealmByName("test");
        session.getContext().setRealm(realm);
        AdminPermissionManagement management = AdminPermissions.management(session, realm);
        ClientPermissionManagement clientPermission = management.clients();
        for (int i = 11; i < 30; i++) {
            ClientModel clientModel = realm.getClientByClientId("client-search-" + i);
            clientPermission.setPermissionsEnabled(clientModel, true);
            Policy policy = clientPermission.viewPermission(clientModel);
            AuthorizationProvider provider = session.getProvider(AuthorizationProvider.class);
            ClientModel realmAdminClient = realm.getClientByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID);
            policy.addAssociatedPolicy(provider.getStoreFactory().getPolicyStore().findByName("Only regular-admin-user", realmAdminClient.getId()));
        }
    });
    try (Keycloak client = Keycloak.getInstance(getAuthServerContextRoot() + "/auth", "test", "regular-admin-user", "password", Constants.ADMIN_CLI_CLIENT_ID, TLSUtils.initializeTLS())) {
        List<ClientRepresentation> clients = new ArrayList<>();
        List<ClientRepresentation> result = client.realm("test").clients().findAll("client-search-", true, true, 0, 10);
        clients.addAll(result);
        Assert.assertEquals(10, result.size());
        Assert.assertThat(result.stream().map(rep -> rep.getClientId()).collect(Collectors.toList()), Matchers.is(Arrays.asList("client-search-09", "client-search-10", "client-search-11", "client-search-12", "client-search-13", "client-search-14", "client-search-15", "client-search-16", "client-search-17", "client-search-18")));
        result = client.realm("test").clients().findAll("client-search-", true, true, 10, 10);
        clients.addAll(result);
        Assert.assertEquals(10, result.size());
        Assert.assertThat(result.stream().map(rep -> rep.getClientId()).collect(Collectors.toList()), Matchers.is(Arrays.asList("client-search-19", "client-search-20", "client-search-21", "client-search-22", "client-search-23", "client-search-24", "client-search-25", "client-search-26", "client-search-27", "client-search-28")));
        result = client.realm("test").clients().findAll("client-search-", true, true, 20, 10);
        clients.addAll(result);
        Assert.assertEquals(1, result.size());
        Assert.assertThat(result, Matchers.hasItems(Matchers.hasProperty("clientId", Matchers.isOneOf("client-search-29"))));
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) ArrayList(java.util.ArrayList) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) ClientPermissionManagement(org.keycloak.services.resources.admin.permissions.ClientPermissionManagement) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation) Keycloak(org.keycloak.admin.client.Keycloak) AdminPermissionManagement(org.keycloak.services.resources.admin.permissions.AdminPermissionManagement) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 87 with AuthServerContainerExclude

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

the class FineGrainAdminUnitTest method testRealmWithComposites.

// KEYCLOAK-5152
@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testRealmWithComposites() throws Exception {
    testingClient.server().run(FineGrainAdminUnitTest::setup5152);
    try (Keycloak realmClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), TEST, "realm-admin", "password", Constants.ADMIN_CLI_CLIENT_ID, null)) {
        RoleRepresentation composite = new RoleRepresentation();
        composite.setName("composite");
        composite.setComposite(true);
        realmClient.realm(TEST).roles().create(composite);
        composite = adminClient.realm(TEST).roles().get("composite").toRepresentation();
        ClientRepresentation client = adminClient.realm(TEST).clients().findByClientId(Constants.REALM_MANAGEMENT_CLIENT_ID).get(0);
        RoleRepresentation viewUsers = adminClient.realm(TEST).clients().get(client.getId()).roles().get(AdminRoles.CREATE_CLIENT).toRepresentation();
        List<RoleRepresentation> composites = new LinkedList<>();
        composites.add(viewUsers);
        realmClient.realm(TEST).rolesById().addComposites(composite.getId(), composites);
    }
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) Keycloak(org.keycloak.admin.client.Keycloak) LinkedList(java.util.LinkedList) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 88 with AuthServerContainerExclude

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

the class UserTest method sendVerifyEmail.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void sendVerifyEmail() throws IOException {
    UserRepresentation userRep = new UserRepresentation();
    userRep.setUsername("user1");
    String id = createUser(userRep);
    UserResource user = realm.users().get(id);
    try {
        user.sendVerifyEmail();
        fail("Expected failure");
    } catch (ClientErrorException e) {
        assertEquals(400, e.getResponse().getStatus());
        ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class);
        Assert.assertEquals("User email missing", error.getErrorMessage());
    }
    try {
        userRep = user.toRepresentation();
        userRep.setEmail("user1@localhost");
        userRep.setEnabled(false);
        updateUser(user, userRep);
        user.sendVerifyEmail();
        fail("Expected failure");
    } catch (ClientErrorException e) {
        assertEquals(400, e.getResponse().getStatus());
        ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class);
        Assert.assertEquals("User is disabled", error.getErrorMessage());
        assertAdminEvents.assertEmpty();
    }
    try {
        userRep.setEnabled(true);
        updateUser(user, userRep);
        user.sendVerifyEmail("invalidClientId");
        fail("Expected failure");
    } catch (ClientErrorException e) {
        assertEquals(400, e.getResponse().getStatus());
        ErrorRepresentation error = e.getResponse().readEntity(ErrorRepresentation.class);
        Assert.assertEquals("Client doesn't exist", error.getErrorMessage());
        assertAdminEvents.assertEmpty();
    }
    user.sendVerifyEmail();
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + "/send-verify-email", ResourceType.USER);
    Assert.assertEquals(1, greenMail.getReceivedMessages().length);
    String link = MailUtils.getPasswordResetEmailLink(greenMail.getReceivedMessages()[0]);
    driver.navigate().to(link);
    proceedPage.assertCurrent();
    assertThat(proceedPage.getInfo(), Matchers.containsString("Verify Email"));
    proceedPage.clickProceedLink();
    Assert.assertEquals("Your account has been updated.", infoPage.getInfo());
    driver.navigate().to("about:blank");
    // It should be possible to use the same action token multiple times
    driver.navigate().to(link);
    proceedPage.assertCurrent();
    assertThat(proceedPage.getInfo(), Matchers.containsString("Verify Email"));
    proceedPage.clickProceedLink();
    Assert.assertEquals("Your account has been updated.", infoPage.getInfo());
}
Also used : ErrorRepresentation(org.keycloak.representations.idm.ErrorRepresentation) UserResource(org.keycloak.admin.client.resource.UserResource) ClientErrorException(javax.ws.rs.ClientErrorException) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) Test(org.junit.Test)

Example 89 with AuthServerContainerExclude

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

the class UserTest method sendResetPasswordEmailSuccessLinkOpenDoesNotExpireWhenOpenedOnly.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void sendResetPasswordEmailSuccessLinkOpenDoesNotExpireWhenOpenedOnly() 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);
    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();
    assertThat(proceedPage.getInfo(), Matchers.containsString("Update Password"));
    proceedPage.clickProceedLink();
    passwordUpdatePage.assertCurrent();
    driver.manage().deleteAllCookies();
    driver.navigate().to("about:blank");
    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.", PageUtils.getPageTitle(driver));
}
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 90 with AuthServerContainerExclude

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

the class UserTest method sendResetPasswordEmailSuccessWithRecycledAuthSession.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void sendResetPasswordEmailSuccessWithRecycledAuthSession() 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());
    // The following block creates a client and requests updating password with redirect to this client.
    // After clicking the link (starting a fresh auth session with client), the user goes away and sends the email
    // with password reset again - now without the client - and attempts to complete the password reset.
    {
        ClientRepresentation client = new ClientRepresentation();
        client.setClientId("myclient2");
        client.setRedirectUris(new LinkedList<>());
        client.getRedirectUris().add("http://myclient.com/*");
        client.setName("myclient2");
        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);
        user.executeActionsEmail("myclient2", "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);
    }
    user.executeActionsEmail(actions);
    assertAdminEvents.assertEvent(realmId, OperationType.ACTION, AdminEventPaths.userResourcePath(id) + "/execute-actions-email", ResourceType.USER);
    Assert.assertEquals(2, greenMail.getReceivedMessages().length);
    MimeMessage message = greenMail.getReceivedMessages()[greenMail.getReceivedMessages().length - 1];
    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", "new-pass");
    assertEquals("Your account has been updated.", PageUtils.getPageTitle(driver));
    driver.navigate().to(link);
    assertEquals("We are sorry...", PageUtils.getPageTitle(driver));
}
Also used : Response(javax.ws.rs.core.Response) MimeMessage(javax.mail.internet.MimeMessage) UserResource(org.keycloak.admin.client.resource.UserResource) LinkedList(java.util.LinkedList) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) 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