Search in sources :

Example 1 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource in project ART-TIME by Artezio.

the class KeycloakClient method populateCache.

@Timeout
protected void populateCache() {
    RealmResource realm = getRealm();
    List<UserRepresentation> users = loadUsers(realm);
    Set<String> departments = loadDepartments(users);
    Map<String, List<UserInfo>> groupTeams = loadUserGroups(users, realm);
    this.cache = new Cache(toUserInfo(users), departments, groupTeams);
}
Also used : RealmResource(org.keycloak.admin.client.resource.RealmResource) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) UserRepresentation(org.keycloak.representations.idm.UserRepresentation)

Example 2 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource in project ART-TIME by Artezio.

the class KeycloakClientTest method testLoadUserGroups.

@Test
public void testLoadUserGroups() throws NoSuchFieldException {
    keycloakClient = createMockBuilder(KeycloakClient.class).addMockedMethod("listGroups", UserRepresentation.class, RealmResource.class).createMock();
    setField(keycloakClient, "settings", settings);
    String departmentAttribute = "department";
    settings.setKeycloakUserDepartmentAttribute(departmentAttribute);
    String username1 = "user1";
    String username2 = "user2";
    String username3 = "user3";
    String group1 = "grp1";
    String group2 = "grp2";
    String group3 = "grp3";
    Map<String, List<String>> user1attributes = new HashMap<>();
    Map<String, List<String>> user2attributes = new HashMap<>();
    Map<String, List<String>> user3attributes = new HashMap<>();
    List<String> user1groups = Arrays.asList(group1, group2);
    List<String> user2groups = Arrays.asList(group1, group3);
    List<String> user3groups = Arrays.asList(group3);
    user1attributes.put(departmentAttribute, user1groups);
    user2attributes.put(departmentAttribute, user2groups);
    user3attributes.put(departmentAttribute, user3groups);
    UserRepresentation user1 = new UserRepresentation();
    UserRepresentation user2 = new UserRepresentation();
    UserRepresentation user3 = new UserRepresentation();
    user1.setUsername(username1);
    user2.setUsername(username2);
    user3.setUsername(username3);
    user1.setAttributes(user1attributes);
    user2.setAttributes(user2attributes);
    user3.setAttributes(user3attributes);
    RealmResource mockRealm = mock(RealmResource.class);
    expect(keycloakClient.listGroups(user1, mockRealm)).andReturn(new HashSet<>(user1groups));
    expect(keycloakClient.listGroups(user2, mockRealm)).andReturn(new HashSet<>(user2groups));
    expect(keycloakClient.listGroups(user3, mockRealm)).andReturn(new HashSet<>(user3groups));
    replay(keycloakClient);
    Map<String, List<UserInfo>> actual = keycloakClient.loadUserGroups(Arrays.asList(user1, user2, user3), mockRealm);
    verify(keycloakClient);
    assertTrue(actual.containsKey(group1));
    assertTrue(actual.containsKey(group2));
    assertTrue(actual.containsKey(group3));
    List<UserInfo> userInfosGroup1 = actual.get(group1);
    List<UserInfo> userInfosGroup2 = actual.get(group2);
    List<UserInfo> userInfosGroup3 = actual.get(group3);
    assertTrue(userInfosGroup1.stream().anyMatch(u -> u.getUsername().equals(username1)));
    assertTrue(userInfosGroup1.stream().anyMatch(u -> u.getUsername().equals(username2)));
    assertFalse(userInfosGroup1.stream().anyMatch(u -> u.getUsername().equals(username3)));
    assertTrue(userInfosGroup2.stream().anyMatch(u -> u.getUsername().equals(username1)));
    assertFalse(userInfosGroup2.stream().anyMatch(u -> u.getUsername().equals(username2)));
    assertFalse(userInfosGroup2.stream().anyMatch(u -> u.getUsername().equals(username3)));
    assertFalse(userInfosGroup3.stream().anyMatch(u -> u.getUsername().equals(username1)));
    assertTrue(userInfosGroup3.stream().anyMatch(u -> u.getUsername().equals(username2)));
    assertTrue(userInfosGroup3.stream().anyMatch(u -> u.getUsername().equals(username3)));
}
Also used : TimerService(javax.ejb.TimerService) java.util(java.util) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) Settings(com.artezio.arttime.config.Settings) RunWith(org.junit.runner.RunWith) TimerConfig(javax.ejb.TimerConfig) UsersResource(org.keycloak.admin.client.resource.UsersResource) PrivateAccessor.setField(junitx.util.PrivateAccessor.setField) TestSubject(org.easymock.TestSubject) Test(org.junit.Test) GroupRepresentation(org.keycloak.representations.idm.GroupRepresentation) EasyMock(org.easymock.EasyMock) Setting(com.artezio.arttime.config.Setting) UserInfo(com.artezio.arttime.services.integration.spi.UserInfo) EnvironmentVariables(org.junit.contrib.java.lang.system.EnvironmentVariables) Timer(javax.ejb.Timer) Rule(org.junit.Rule) Duration(java.time.Duration) EasyMockRunner(org.easymock.EasyMockRunner) UserResource(org.keycloak.admin.client.resource.UserResource) Assert(org.junit.Assert) Before(org.junit.Before) RealmResource(org.keycloak.admin.client.resource.RealmResource) UserInfo(com.artezio.arttime.services.integration.spi.UserInfo) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Test(org.junit.Test)

Example 3 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource in project ART-TIME by Artezio.

the class KeycloakClientTest method testPopulateCache.

@Test
public void testPopulateCache() {
    keycloakClient = createMockBuilder(KeycloakClient.class).addMockedMethod("loadUsers", RealmResource.class).addMockedMethod("loadDepartments", List.class).addMockedMethod("loadUserGroups", List.class, RealmResource.class).addMockedMethod("toUserInfo", List.class).addMockedMethod("getRealm").createMock();
    RealmResource mockRealm = createMock(RealmResource.class);
    List<UserRepresentation> usersList = new ArrayList<>();
    Set<String> departments = new HashSet<>();
    expect(keycloakClient.getRealm()).andReturn(mockRealm);
    expect(keycloakClient.loadUsers(mockRealm)).andReturn(usersList);
    expect(keycloakClient.loadDepartments(usersList)).andReturn(departments);
    expect(keycloakClient.loadUserGroups(usersList, mockRealm)).andReturn(Collections.emptyMap());
    UserInfo userInfo = new UserInfo("username", null, null, null, null);
    expect(keycloakClient.toUserInfo(anyObject(List.class))).andReturn(Arrays.asList(userInfo)).anyTimes();
    replay(keycloakClient);
    keycloakClient.populateCache();
    verify(keycloakClient);
}
Also used : RealmResource(org.keycloak.admin.client.resource.RealmResource) UserInfo(com.artezio.arttime.services.integration.spi.UserInfo) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Test(org.junit.Test)

Example 4 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource in project keycloak by keycloak.

the class BrokerLinkAndTokenExchangeTest method testAccountLinkNoTokenStore.

@Test
@UncaughtServerErrorExpected
public void testAccountLinkNoTokenStore() throws Exception {
    testingClient.server().run(BrokerLinkAndTokenExchangeTest::turnOffTokenStore);
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString()).path("link");
    String linkUrl = linkBuilder.clone().queryParam("realm", CHILD_IDP).queryParam("provider", PARENT_IDP).build().toString();
    System.out.println("linkUrl: " + linkUrl);
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
    loginPage.login(PARENT_USERNAME, "password");
    System.out.println("After linking: " + driver.getCurrentUrl());
    System.out.println(driver.getPageSource());
    Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
    Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
    Assert.assertTrue(driver.getPageSource().contains("Exchange token received"));
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    logoutAll();
    realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
}
Also used : RealmResource(org.keycloak.admin.client.resource.RealmResource) UriBuilder(javax.ws.rs.core.UriBuilder) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 5 with RealmResource

use of org.keycloak.admin.client.resource.RealmResource in project keycloak by keycloak.

the class BrokerLinkAndTokenExchangeTest method testAccountLink.

@Test
@UncaughtServerErrorExpected
public void testAccountLink() throws Exception {
    testingClient.server().run(BrokerLinkAndTokenExchangeTest::turnOnTokenStore);
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    String servletUri = appPage.getInjectedUrl().toString();
    UriBuilder linkBuilder = UriBuilder.fromUri(servletUri).path("link");
    String linkUrl = linkBuilder.clone().queryParam("realm", CHILD_IDP).queryParam("provider", PARENT_IDP).build().toString();
    System.out.println("linkUrl: " + linkUrl);
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
    loginPage.login(PARENT_USERNAME, "password");
    System.out.println("After linking: " + driver.getCurrentUrl());
    System.out.println(driver.getPageSource());
    Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
    Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
    Assert.assertTrue(driver.getPageSource().contains("Exchange token received"));
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    // do exchange
    String accessToken = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, ClientApp.DEPLOYMENT_NAME, "password").getAccessToken();
    Client httpClient = AdminClientUtil.createResteasyClient();
    try {
        WebTarget exchangeUrl = childTokenExchangeWebTarget(httpClient);
        System.out.println("Exchange url: " + exchangeUrl.getUri().toString());
        Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(ClientApp.DEPLOYMENT_NAME, "password")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.SUBJECT_TOKEN, accessToken).param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        String externalToken = tokenResponse.getToken();
        Assert.assertNotNull(externalToken);
        Assert.assertTrue(tokenResponse.getExpiresIn() > 0);
        setTimeOffset((int) tokenResponse.getExpiresIn() + 1);
        // test that token refresh happens
        // get access token again because we may have timed out
        accessToken = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, ClientApp.DEPLOYMENT_NAME, "password").getAccessToken();
        response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(ClientApp.DEPLOYMENT_NAME, "password")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.SUBJECT_TOKEN, accessToken).param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        Assert.assertNotEquals(externalToken, tokenResponse.getToken());
        // test direct exchange
        response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("direct-exchanger", "secret")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "child").param(OAuth2Constants.REQUESTED_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        Assert.assertNotEquals(externalToken, tokenResponse.getToken());
        logoutAll();
        realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
        links = realm.users().get(childUserId).getFederatedIdentity();
        Assert.assertTrue(links.isEmpty());
    } finally {
        httpClient.close();
    }
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) RealmResource(org.keycloak.admin.client.resource.RealmResource) WebTarget(javax.ws.rs.client.WebTarget) UriBuilder(javax.ws.rs.core.UriBuilder) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ApiUtil.createUserAndResetPasswordWithAdminClient(org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient) Client(javax.ws.rs.client.Client) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Aggregations

RealmResource (org.keycloak.admin.client.resource.RealmResource)263 Test (org.junit.Test)190 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)67 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)61 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)58 Response (javax.ws.rs.core.Response)55 RealmRepresentation (org.keycloak.representations.idm.RealmRepresentation)48 ClientResource (org.keycloak.admin.client.resource.ClientResource)39 OAuthClient (org.keycloak.testsuite.util.OAuthClient)37 GroupRepresentation (org.keycloak.representations.idm.GroupRepresentation)36 RoleRepresentation (org.keycloak.representations.idm.RoleRepresentation)34 Before (org.junit.Before)31 UserResource (org.keycloak.admin.client.resource.UserResource)30 IdentityProviderRepresentation (org.keycloak.representations.idm.IdentityProviderRepresentation)25 List (java.util.List)19 LinkedList (java.util.LinkedList)16 ClientScopeRepresentation (org.keycloak.representations.idm.ClientScopeRepresentation)16 VerifyProfileTest (org.keycloak.testsuite.forms.VerifyProfileTest)14 ProtocolMapperRepresentation (org.keycloak.representations.idm.ProtocolMapperRepresentation)13 AccessToken (org.keycloak.representations.AccessToken)12