Java Code Examples for org.keycloak.representations.idm.GroupRepresentation#setName()

The following examples show how to use org.keycloak.representations.idm.GroupRepresentation#setName() . 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: GroupTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotAllowSameGroupNameAtSameLevel() throws Exception {
    RealmResource realm = adminClient.realms().realm("test");

    GroupRepresentation topGroup = new GroupRepresentation();
    topGroup.setName("top");
    topGroup = createGroup(realm, topGroup);

    GroupRepresentation anotherTopGroup = new GroupRepresentation();
    anotherTopGroup.setName("top");
    Response response = realm.groups().add(anotherTopGroup);
    assertEquals(409, response.getStatus()); // conflict status 409 - same name not allowed

    GroupRepresentation level2Group = new GroupRepresentation();
    level2Group.setName("level2");
    response = realm.groups().group(topGroup.getId()).subGroup(level2Group);
    response.close();
    assertEquals(201, response.getStatus()); // created status

    GroupRepresentation anotherlevel2Group = new GroupRepresentation();
    anotherlevel2Group.setName("level2");
    response = realm.groups().group(topGroup.getId()).subGroup(anotherlevel2Group);
    response.close();
    assertEquals(409, response.getStatus()); // conflict status 409 - same name not allowed
}
 
Example 2
Source File: GroupTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void allowSameGroupNameAtDifferentLevel() throws Exception {
    RealmResource realm = adminClient.realms().realm("test");

    // creating "/test-group"
    GroupRepresentation topGroup = new GroupRepresentation();
    topGroup.setName("test-group");
    topGroup = createGroup(realm, topGroup);
    getCleanup().addGroupId(topGroup.getId());

    // creating "/test-group/test-group"
    GroupRepresentation childGroup = new GroupRepresentation();
    childGroup.setName("test-group");
    try (Response response = realm.groups().group(topGroup.getId()).subGroup(childGroup)) {
        assertEquals(201, response.getStatus());
        getCleanup().addGroupId(ApiUtil.getCreatedId(response));
    }

    assertNotNull(realm.getGroupByPath("/test-group/test-group"));
}
 
Example 3
Source File: GroupTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void doNotAllowSameGroupNameAtTopLevel() throws Exception {
    RealmResource realm = adminClient.realms().realm("test");

    // creating "/test-group"
    GroupRepresentation topGroup = new GroupRepresentation();
    topGroup.setName("test-group");
    topGroup = createGroup(realm, topGroup);
    getCleanup().addGroupId(topGroup.getId());

    GroupRepresentation group2 = new GroupRepresentation();
    group2.setName("test-group");
    try (Response response = realm.groups().add(group2)) {
        assertEquals(Status.CONFLICT.getStatusCode(), response.getStatus());
    }
}
 
Example 4
Source File: UserTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void groupMembershipPaginated() {
    String userId = createUser(UserBuilder.create().username("user-a").build());

    for (int i = 1; i <= 10; i++) {
        GroupRepresentation group = new GroupRepresentation();
        group.setName("group-" + i);
        String groupId = createGroup(realm, group).getId();
        realm.users().get(userId).joinGroup(groupId);
        assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userGroupPath(userId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
    }

    List<GroupRepresentation> groups = realm.users().get(userId).groups(5, 6);
    assertEquals(groups.size(), 5);
    assertNames(groups, "group-5","group-6","group-7","group-8","group-9");
}
 
Example 5
Source File: SAMLServletAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserAttributeStatementMapperUserGroupsAggregate() throws Exception {
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));

    ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
    ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();

    Map<String, String> config = new LinkedHashMap<>();
    config.put("attribute.nameformat", "Basic");
    config.put("user.attribute", "group-value");
    config.put("attribute.name", "group-attribute");
    config.put("aggregate.attrs", "true");

    try (
      AutoCloseable g1 = Creator.create(testRealmResource(), group1);
      AutoCloseable uau = UserAttributeUpdater.forUserByUsername(testRealmResource(), "bburke")
        .setAttribute("group-value", "user-value1")
        .setGroups("/group1")
        .update();
      AutoCloseable c = createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config)) {
        employee2ServletPage.navigateTo();
        assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
        testRealmSAMLPostLoginPage.form().login("bburke", "password");

        driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAttributes").build().toURL());
        waitForPageToLoad();

        String body = driver.findElement(By.xpath("//body")).getText();
        String[] values = parseCommaSeparatedAttributes(body, "group-attribute");
        assertThat(values, arrayContainingInAnyOrder("user-value1", "value1", "value2"));

        employee2ServletPage.logout();
        checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
    }
}
 
Example 6
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupAttributeOneGroupMultiValueAggregate() throws Exception {
    // get the user
    UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
    // create a group1 with two values
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
    adminClient.realm("test").groups().add(group1);
    group1 = adminClient.realm("test").getGroupByPath("/group1");
    userResource.joinGroup(group1.getId());

    // create the attribute mapper
    ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
    protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, true)).close();

    try {
        // test it
        OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");

        IDToken idToken = oauth.verifyIDToken(response.getIdToken());
        assertNotNull(idToken.getOtherClaims());
        assertNotNull(idToken.getOtherClaims().get("group-value"));
        assertTrue(idToken.getOtherClaims().get("group-value") instanceof List);
        assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size());
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value1"));
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value2"));
    } finally {
        // revert
        userResource.leaveGroup(group1.getId());
        adminClient.realm("test").groups().group(group1.getId()).remove();
        deleteMappers(protocolMappers);
    }
}
 
Example 7
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroupAttributeOneGroupMultiValueNoAggregate() throws Exception {
    // get the user
    UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
    // create a group1 with two values
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
    adminClient.realm("test").groups().add(group1);
    group1 = adminClient.realm("test").getGroupByPath("/group1");
    userResource.joinGroup(group1.getId());

    // create the attribute mapper
    ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
    protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, false)).close();

    try {
        // test it
        OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");

        IDToken idToken = oauth.verifyIDToken(response.getIdToken());
        assertNotNull(idToken.getOtherClaims());
        assertNotNull(idToken.getOtherClaims().get("group-value"));
        assertTrue(idToken.getOtherClaims().get("group-value") instanceof List);
        assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size());
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value1"));
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value2"));
    } finally {
        // revert
        userResource.leaveGroup(group1.getId());
        adminClient.realm("test").groups().group(group1.getId()).remove();
        deleteMappers(protocolMappers);
    }
}
 
Example 8
Source File: UserStorageTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void testEntityRemovalHooksCascade() {
    testingClient.server().run(session -> {
        UserMapStorage.realmRemovals.set(0);
        UserMapStorage.groupRemovals.set(0);
        UserMapStorage.roleRemovals.set(0);
    });

    GroupRepresentation g1 = new GroupRepresentation();
    g1.setName("group1");
    GroupRepresentation g2 = new GroupRepresentation();
    g2.setName("group2");
    String gid1 = ApiUtil.getCreatedId(testRealmResource().groups().add(g1));
    String gid2 = ApiUtil.getCreatedId(testRealmResource().groups().add(g2));

    RoleRepresentation role1 = new RoleRepresentation();
    role1.setName("role1");
    RoleRepresentation role2 = new RoleRepresentation();
    role2.setName("role2");
    testRealmResource().roles().create(role1);
    testRealmResource().roles().create(role2);

    // remove realm with groups and roles in it
    testRealmResource().remove();
    testingClient.server().run(session -> {
        Assert.assertEquals(1, UserMapStorage.realmRemovals.get());
        Assert.assertEquals(2, UserMapStorage.groupRemovals.get()); // check if group removal hooks were called
        Assert.assertEquals(2, UserMapStorage.roleRemovals.get()); // check if role removal hooks were called
    });

}
 
Example 9
Source File: UserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void groupMembershipSearch() {
    String userId = createUser(UserBuilder.create().username("user-b").build());

    for (int i = 1; i <= 10; i++) {
        GroupRepresentation group = new GroupRepresentation();
        group.setName("group-" + i);
        String groupId = createGroup(realm, group).getId();
        realm.users().get(userId).joinGroup(groupId);
        assertAdminEvents.assertEvent(realmId, OperationType.CREATE, AdminEventPaths.userGroupPath(userId, groupId), group, ResourceType.GROUP_MEMBERSHIP);
    }

    List<GroupRepresentation> groups = realm.users().get(userId).groups("-3", 0, 10);
    assertEquals(1, groups.size());
    assertNames(groups, "group-3");

    List<GroupRepresentation> groups2 = realm.users().get(userId).groups("1", 0, 10);
    assertEquals(2, groups2.size());
    assertNames(groups2, "group-1", "group-10");

    List<GroupRepresentation> groups3 = realm.users().get(userId).groups("1", 2, 10);
    assertEquals(0, groups3.size());

    List<GroupRepresentation> groups4 = realm.users().get(userId).groups("gr", 2, 10);
    assertEquals(8, groups4.size());

    List<GroupRepresentation> groups5 = realm.users().get(userId).groups("Gr", 2, 10);
    assertEquals(8, groups5.size());
}
 
Example 10
Source File: ManyUsersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setDefaultGroup(String groupName) {
    GroupRepresentation group = new GroupRepresentation();
    group.setName(groupName);
    Response resp = realmResource().groups().add(group);
    String groupId = ApiUtil.getCreatedId(resp);
    resp.close();
    realmResource().addDefaultGroup(groupId);
}
 
Example 11
Source File: SAMLServletAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testUserAttributeStatementMapperUserGroupsNoAggregate() throws Exception {
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));

    ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
    ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();

    Map<String, String> config = new LinkedHashMap<>();
    config.put("attribute.nameformat", "Basic");
    config.put("user.attribute", "group-value");
    config.put("attribute.name", "group-attribute");

    try (
      AutoCloseable g1 = Creator.create(testRealmResource(), group1);
      AutoCloseable uau = UserAttributeUpdater.forUserByUsername(testRealmResource(), "bburke")
        .setAttribute("group-value", "user-value1")
        .setGroups("/group1")
        .update();
      AutoCloseable c = createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config)) {
        employee2ServletPage.navigateTo();
        assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
        testRealmSAMLPostLoginPage.form().login("bburke", "password");

        driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAttributes").build().toURL());
        waitForPageToLoad();

        String body = driver.findElement(By.xpath("//body")).getText();
        String[] values = parseCommaSeparatedAttributes(body, "group-attribute");
        assertThat(values, arrayContaining("user-value1"));

        employee2ServletPage.logout();
        checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
    }
}
 
Example 12
Source File: GroupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void groupMembership() {
    RealmResource realm = adminClient.realms().realm("test");

    GroupRepresentation group = new GroupRepresentation();
    group.setName("group");
    String groupId = createGroup(realm, group).getId();

    Response response = realm.users().create(UserBuilder.create().username("user-a").build());
    String userAId = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userResourcePath(userAId), ResourceType.USER);

    response = realm.users().create(UserBuilder.create().username("user-b").build());
    String userBId = ApiUtil.getCreatedId(response);
    response.close();
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userResourcePath(userBId), ResourceType.USER);

    realm.users().get(userAId).joinGroup(groupId);
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userGroupPath(userAId, groupId), group, ResourceType.GROUP_MEMBERSHIP);

    List<UserRepresentation> members = realm.groups().group(groupId).members(0, 10);
    assertNames(members, "user-a");

    realm.users().get(userBId).joinGroup(groupId);
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.userGroupPath(userBId, groupId), group, ResourceType.GROUP_MEMBERSHIP);

    members = realm.groups().group(groupId).members(0, 10);
    assertNames(members, "user-a", "user-b");

    realm.users().get(userAId).leaveGroup(groupId);
    assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.userGroupPath(userAId, groupId), group, ResourceType.GROUP_MEMBERSHIP);

    members = realm.groups().group(groupId).members(0, 10);
    assertNames(members, "user-b");
}
 
Example 13
Source File: GroupTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * KEYCLOAK-2716
 * @throws Exception
 */
@Test
public void testClientRemoveWithClientRoleGroupMapping() throws Exception {
    RealmResource realm = adminClient.realms().realm("test");

    ClientRepresentation client = new ClientRepresentation();
    client.setClientId("foo");
    client.setRootUrl("http://foo");
    client.setProtocol("openid-connect");
    Response response = realm.clients().create(client);
    response.close();
    String clientUuid = ApiUtil.getCreatedId(response);
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.clientResourcePath(clientUuid), client, ResourceType.CLIENT);
    client = realm.clients().findByClientId("foo").get(0);

    RoleRepresentation role = new RoleRepresentation();
    role.setName("foo-role");
    realm.clients().get(client.getId()).roles().create(role);
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.clientRoleResourcePath(clientUuid, "foo-role"), role, ResourceType.CLIENT_ROLE);
    role = realm.clients().get(client.getId()).roles().get("foo-role").toRepresentation();

    GroupRepresentation group = new GroupRepresentation();
    group.setName("2716");
    group = createGroup(realm, group);

    List<RoleRepresentation> list = new LinkedList<>();
    list.add(role);
    realm.groups().group(group.getId()).roles().clientLevel(client.getId()).add(list);
    assertAdminEvents.assertEvent("test", OperationType.CREATE, AdminEventPaths.groupRolesClientRolesPath(group.getId(), clientUuid), list, ResourceType.CLIENT_ROLE_MAPPING);

    realm.clients().get(client.getId()).remove();
    assertAdminEvents.assertEvent("test", OperationType.DELETE, AdminEventPaths.clientResourcePath(clientUuid), ResourceType.CLIENT);
}
 
Example 14
Source File: UsersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private GroupRepresentation createGroupWithPermissions(String name) {
    GroupRepresentation grp = new GroupRepresentation();
    grp.setName(name);
    realm.groups().add(grp);
    Optional<GroupRepresentation> optional = realm.groups().groups().stream().filter(g -> g.getName().equals(name)).findFirst();
    assertThat(optional.isPresent(), is(true));
    grp = optional.get();
    String id = grp.getId();
    //enable the permissions
    realm.groups().group(id).setPermissions(new ManagementPermissionRepresentation(true));
    assertThat(realm.groups().group(id).getPermissions().isEnabled(), is(true));

    return grp;
}
 
Example 15
Source File: OIDCScopeTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
    UserRepresentation user = UserBuilder.create()
            .id(userId)
            .username("john")
            .enabled(true)
            .email("[email protected]")
            .firstName("John")
            .lastName("Doe")
            .password("password")
            .role("account", "manage-account")
            .role("account", "view-profile")
            .addRoles("role-1", "role-2")
            .build();

    user.setEmailVerified(true);
    MultivaluedHashMap<String, String> attrs = new MultivaluedHashMap<>();
    attrs.add("street", "Elm 5");
    attrs.add("phoneNumber", "111-222-333");
    attrs.add("phoneNumberVerified", "true");
    user.setAttributes(attrs);

    testRealm.getUsers().add(user);


    // Add sample realm roles
    RoleRepresentation role1 = new RoleRepresentation();
    role1.setName("role-1");
    testRealm.getRoles().getRealm().add(role1);
    RoleRepresentation role2 = new RoleRepresentation();
    role2.setName("role-2");
    testRealm.getRoles().getRealm().add(role2);

    RoleRepresentation roleParent = RoleBuilder.create()
            .name("role-parent")
            .realmComposite("role-1")
            .build();
    testRealm.getRoles().getRealm().add(roleParent);

    // Add sample group
    GroupRepresentation group = new GroupRepresentation();
    group.setName("group-role-1");
    group.setRealmRoles(Collections.singletonList("role-1"));
    testRealm.getGroups().add(group);

    // Add more sample users
    user = UserBuilder.create()
            .username("role-1-user")
            .enabled(true)
            .password("password")
            .addRoles("role-1")
            .build();
    testRealm.getUsers().add(user);

    user = UserBuilder.create()
            .username("role-2-user")
            .enabled(true)
            .password("password")
            .addRoles("role-2")
            .build();
    testRealm.getUsers().add(user);

    user = UserBuilder.create()
            .username("role-parent-user")
            .enabled(true)
            .password("password")
            .addRoles("role-parent")
            .build();
    testRealm.getUsers().add(user);

    user = UserBuilder.create()
            .username("group-role-1-user")
            .enabled(true)
            .password("password")
            .addGroups("group-role-1")
            .build();
    testRealm.getUsers().add(user);
}
 
Example 16
Source File: UserStorageTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testEntityRemovalHooks() {
    testingClient.server().run(session -> {
        UserMapStorage.realmRemovals.set(0);
        UserMapStorage.groupRemovals.set(0);
        UserMapStorage.roleRemovals.set(0);
    });

    // remove group
    GroupRepresentation g1 = new GroupRepresentation();
    g1.setName("group1");
    GroupRepresentation g2 = new GroupRepresentation();
    g2.setName("group2");
    String gid1 = ApiUtil.getCreatedId(testRealmResource().groups().add(g1));
    String gid2 = ApiUtil.getCreatedId(testRealmResource().groups().add(g2));
    testRealmResource().groups().group(gid1).remove();
    testRealmResource().groups().group(gid2).remove();
    testingClient.server().run(session -> {
        Assert.assertEquals(2, UserMapStorage.groupRemovals.get());
        UserMapStorage.realmRemovals.set(0);
    });

    // remove role
    RoleRepresentation role1 = new RoleRepresentation();
    role1.setName("role1");
    RoleRepresentation role2 = new RoleRepresentation();
    role2.setName("role2");
    testRealmResource().roles().create(role1);
    testRealmResource().roles().create(role2);
    testRealmResource().roles().get("role1").remove();
    testRealmResource().roles().get("role2").remove();
    testingClient.server().run(session -> {
        Assert.assertEquals(2, UserMapStorage.roleRemovals.get());
        UserMapStorage.realmRemovals.set(0);
    });

    // remove realm
    RealmRepresentation testRealmRepresentation = testRealmResource().toRepresentation();
    testRealmResource().remove();
    testingClient.server().run(session -> {
        Assert.assertEquals(1, UserMapStorage.realmRemovals.get());
        UserMapStorage.realmRemovals.set(0);
    });

    // Re-create realm
    RealmRepresentation repOrig = testContext.getTestRealmReps().get(0);
    adminClient.realms().create(repOrig);
}
 
Example 17
Source File: SAMLServletAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testUserAttributeStatementMapperGroupsNoAggregate() throws Exception {
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));

    GroupRepresentation group2 = new GroupRepresentation();
    group2.setName("group2");
    group2.setAttributes(new HashMap<>());
    group2.getAttributes().put("group-value", Arrays.asList("value2", "value3"));

    ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
    ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();

    Map<String, String> config = new LinkedHashMap<>();
    config.put("attribute.nameformat", "Basic");
    config.put("user.attribute", "group-value");
    config.put("attribute.name", "group-attribute");

    try (
      AutoCloseable g1 = Creator.create(testRealmResource(), group1);
      AutoCloseable g2 = Creator.create(testRealmResource(), group2);
      AutoCloseable uau = UserAttributeUpdater.forUserByUsername(testRealmResource(), "bburke")
        .setGroups("/group1", "/group2")
        .update();
      AutoCloseable c = createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config)) {
        employee2ServletPage.navigateTo();
        assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
        testRealmSAMLPostLoginPage.form().login("bburke", "password");

        driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAttributes").build().toURL());
        waitForPageToLoad();

        String body = driver.findElement(By.xpath("//body")).getText();
        String[] values = parseCommaSeparatedAttributes(body, "group-attribute");
        assertThat(values, anyOf(arrayContainingInAnyOrder("value1", "value2"), arrayContainingInAnyOrder("value2", "value3")));

        employee2ServletPage.logout();
        checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
    }
}
 
Example 18
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testGroupAttributeTwoGroupMultiValueNoAggregate() throws Exception {
    // get the user
    UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
    // create two groups with two values (one is the same value)
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
    adminClient.realm("test").groups().add(group1);
    group1 = adminClient.realm("test").getGroupByPath("/group1");
    userResource.joinGroup(group1.getId());
    GroupRepresentation group2 = new GroupRepresentation();
    group2.setName("group2");
    group2.setAttributes(new HashMap<>());
    group2.getAttributes().put("group-value", Arrays.asList("value2", "value3"));
    adminClient.realm("test").groups().add(group2);
    group2 = adminClient.realm("test").getGroupByPath("/group2");
    userResource.joinGroup(group2.getId());

    // create the attribute mapper
    ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
    protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, false)).close();

    try {
        // test it
        OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");

        IDToken idToken = oauth.verifyIDToken(response.getIdToken());
        assertNotNull(idToken.getOtherClaims());
        assertNotNull(idToken.getOtherClaims().get("group-value"));
        assertTrue(idToken.getOtherClaims().get("group-value") instanceof List);
        assertEquals(2, ((List) idToken.getOtherClaims().get("group-value")).size());
        assertTrue((((List) idToken.getOtherClaims().get("group-value")).contains("value1")
                && ((List) idToken.getOtherClaims().get("group-value")).contains("value2"))
                || (((List) idToken.getOtherClaims().get("group-value")).contains("value2")
                && ((List) idToken.getOtherClaims().get("group-value")).contains("value3")));
    } finally {
        // revert
        userResource.leaveGroup(group1.getId());
        adminClient.realm("test").groups().group(group1.getId()).remove();
        userResource.leaveGroup(group2.getId());
        adminClient.realm("test").groups().group(group2.getId()).remove();
        deleteMappers(protocolMappers);
    }
}
 
Example 19
Source File: OIDCProtocolMappersTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testGroupAttributeTwoGroupMultiValueAggregate() throws Exception {
    // get the user
    UserResource userResource = findUserByUsernameId(adminClient.realm("test"), "test-user@localhost");
    // create two groups with two values (one is the same value)
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));
    adminClient.realm("test").groups().add(group1);
    group1 = adminClient.realm("test").getGroupByPath("/group1");
    userResource.joinGroup(group1.getId());
    GroupRepresentation group2 = new GroupRepresentation();
    group2.setName("group2");
    group2.setAttributes(new HashMap<>());
    group2.getAttributes().put("group-value", Arrays.asList("value2", "value3"));
    adminClient.realm("test").groups().add(group2);
    group2 = adminClient.realm("test").getGroupByPath("/group2");
    userResource.joinGroup(group2.getId());

    // create the attribute mapper
    ProtocolMappersResource protocolMappers = findClientResourceByClientId(adminClient.realm("test"), "test-app").getProtocolMappers();
    protocolMappers.createMapper(createClaimMapper("group-value", "group-value", "group-value", "String", true, true, true, true)).close();

    try {
        // test it
        OAuthClient.AccessTokenResponse response = browserLogin("password", "test-user@localhost", "password");

        IDToken idToken = oauth.verifyIDToken(response.getIdToken());
        assertNotNull(idToken.getOtherClaims());
        assertNotNull(idToken.getOtherClaims().get("group-value"));
        assertTrue(idToken.getOtherClaims().get("group-value") instanceof List);
        assertEquals(3, ((List) idToken.getOtherClaims().get("group-value")).size());
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value1"));
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value2"));
        assertTrue(((List) idToken.getOtherClaims().get("group-value")).contains("value3"));
    } finally {
        // revert
        userResource.leaveGroup(group1.getId());
        adminClient.realm("test").groups().group(group1.getId()).remove();
        userResource.leaveGroup(group2.getId());
        adminClient.realm("test").groups().group(group2.getId()).remove();
        deleteMappers(protocolMappers);
    }
}
 
Example 20
Source File: SAMLServletAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testUserAttributeStatementMapperGroupsAggregate() throws Exception {
    GroupRepresentation group1 = new GroupRepresentation();
    group1.setName("group1");
    group1.setAttributes(new HashMap<>());
    group1.getAttributes().put("group-value", Arrays.asList("value1", "value2"));

    GroupRepresentation group2 = new GroupRepresentation();
    group2.setName("group2");
    group2.setAttributes(new HashMap<>());
    group2.getAttributes().put("group-value", Arrays.asList("value2", "value3"));

    ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), AbstractSamlTest.SAML_CLIENT_ID_EMPLOYEE_2);
    ProtocolMappersResource protocolMappersResource = clientResource.getProtocolMappers();

    Map<String, String> config = new LinkedHashMap<>();
    config.put("attribute.nameformat", "Basic");
    config.put("user.attribute", "group-value");
    config.put("attribute.name", "group-attribute");
    config.put("aggregate.attrs", "true");

    try (
      AutoCloseable g1 = Creator.create(testRealmResource(), group1);
      AutoCloseable g2 = Creator.create(testRealmResource(), group2);
      AutoCloseable uau = UserAttributeUpdater.forUserByUsername(testRealmResource(), "bburke")
        .setGroups("/group1", "/group2")
        .update();
      AutoCloseable c = createProtocolMapper(protocolMappersResource, "group-value", "saml", "saml-user-attribute-mapper", config)) {
        employee2ServletPage.navigateTo();
        assertCurrentUrlStartsWith(testRealmSAMLPostLoginPage);
        testRealmSAMLPostLoginPage.form().login("bburke", "password");

        driver.navigate().to(employee2ServletPage.getUriBuilder().clone().path("getAttributes").build().toURL());
        waitForPageToLoad();

        String body = driver.findElement(By.xpath("//body")).getText();
        String[] values = parseCommaSeparatedAttributes(body, "group-attribute");
        assertThat(values, arrayContainingInAnyOrder("value1", "value2","value3"));

        employee2ServletPage.logout();
        checkLoggedOut(employee2ServletPage, testRealmSAMLPostLoginPage);
    }
}