Search in sources :

Example 6 with RealmResource

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

the class BrokerLinkAndTokenExchangeTest method testExternalExchange_extractIdentityFromProfile.

/**
 * KEYCLOAK-14577, see also KEYCLOAK-10932
 */
@Test
public void testExternalExchange_extractIdentityFromProfile() throws Exception {
    RealmResource childRealm = adminClient.realms().realm(CHILD_IDP);
    String accessToken = oauth.doGrantAccessTokenRequest(PARENT_IDP, PARENT3_USERNAME, "password", null, PARENT_CLIENT, "password").getAccessToken();
    Assert.assertEquals(0, adminClient.realm(CHILD_IDP).getClientSessionStats().size());
    Client httpClient = AdminClientUtil.createResteasyClient();
    try {
        WebTarget exchangeUrl = childTokenExchangeWebTarget(httpClient);
        IdentityProviderRepresentation rep = adminClient.realm(CHILD_IDP).identityProviders().get(PARENT_IDP).toRepresentation();
        rep.getConfig().put(OIDCIdentityProviderConfig.VALIDATE_SIGNATURE, String.valueOf(false));
        adminClient.realm(CHILD_IDP).identityProviders().get(PARENT_IDP).update(rep);
        AccessToken token;
        try (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.JWT_TOKEN_TYPE).param(OAuth2Constants.SUBJECT_ISSUER, PARENT_IDP).param(OAuth2Constants.SCOPE, OAuth2Constants.SCOPE_OPENID)))) {
            Assert.assertEquals(200, response.getStatus());
            AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
            JWSInput jws = new JWSInput(tokenResponse.getToken());
            token = jws.readJsonContent(AccessToken.class);
        }
        Assert.assertNotNull(token);
        Assert.assertNotNull(token.getSubject());
        Assert.assertEquals(PARENT3_USERNAME, token.getPreferredUsername());
        Assert.assertEquals("first name", token.getGivenName());
        Assert.assertEquals("last name", token.getFamilyName());
        Assert.assertEquals("email", token.getEmail());
        // cleanup remove the user
        childRealm.users().get(token.getSubject()).remove();
    } 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) AccessToken(org.keycloak.representations.AccessToken) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) WebTarget(javax.ws.rs.client.WebTarget) JWSInput(org.keycloak.jose.jws.JWSInput) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ApiUtil.createUserAndResetPasswordWithAdminClient(org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient) Client(javax.ws.rs.client.Client) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Example 7 with RealmResource

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

the class BrokerLinkAndTokenExchangeTest method addChildUser.

public void addChildUser() {
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    UserRepresentation user = new UserRepresentation();
    user.setUsername("child");
    user.setEnabled(true);
    childUserId = createUserAndResetPasswordWithAdminClient(realm, user, "password");
    UserRepresentation user2 = new UserRepresentation();
    user2.setUsername("child2");
    user2.setEnabled(true);
    String user2Id = createUserAndResetPasswordWithAdminClient(realm, user2, "password");
    // have to add a role as undertow default auth manager doesn't like "*". todo we can remove this eventually as undertow fixes this in later versions
    realm.roles().create(new RoleRepresentation("user", null, false));
    RoleRepresentation role = realm.roles().get("user").toRepresentation();
    List<RoleRepresentation> roles = new LinkedList<>();
    roles.add(role);
    realm.users().get(childUserId).roles().realmLevel().add(roles);
    realm.users().get(user2Id).roles().realmLevel().add(roles);
    ClientRepresentation brokerService = realm.clients().findByClientId(Constants.BROKER_SERVICE_CLIENT_ID).get(0);
    role = realm.clients().get(brokerService.getId()).roles().get(Constants.READ_TOKEN_ROLE).toRepresentation();
    roles.clear();
    roles.add(role);
    realm.users().get(childUserId).roles().clientLevel(brokerService.getId()).add(roles);
    realm.users().get(user2Id).roles().clientLevel(brokerService.getId()).add(roles);
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) LinkedList(java.util.LinkedList) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation)

Example 8 with RealmResource

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

the class DemoServletsAdapterTest method testTokenConcurrentRefresh.

@Test
public void testTokenConcurrentRefresh() {
    RealmResource demoRealm = adminClient.realm("demo");
    RealmRepresentation demo = demoRealm.toRepresentation();
    demo.setAccessTokenLifespan(2);
    demo.setRevokeRefreshToken(true);
    demo.setRefreshTokenMaxReuse(0);
    demoRealm.update(demo);
    // Login
    tokenRefreshPage.navigateTo();
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("bburke@redhat.com", "password");
    assertCurrentUrlEquals(tokenRefreshPage);
    setAdapterAndServerTimeOffset(5, tokenRefreshPage.toString());
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie jsessionid = new BasicClientCookie("JSESSIONID", driver.manage().getCookieNamed("JSESSIONID").getValue());
    jsessionid.setDomain(ServerURLs.APP_SERVER_HOST);
    jsessionid.setPath("/");
    cookieStore.addCookie(jsessionid);
    ExecutorService executor = Executors.newWorkStealingPool();
    CompletableFuture future = CompletableFuture.completedFuture(null);
    try {
        for (int i = 0; i < 5; i++) {
            future = CompletableFuture.allOf(future, CompletableFuture.runAsync(() -> {
                try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build()) {
                    HttpUriRequest request = new HttpGet(tokenRefreshPage.getInjectedUrl().toString());
                    try (CloseableHttpResponse httpResponse = client.execute(request)) {
                        assertTrue("Token not refreshed", EntityUtils.toString(httpResponse.getEntity()).contains("accessToken"));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }, executor));
        }
        future.join();
    } finally {
        executor.shutdownNow();
    }
    // Revert times
    setAdapterAndServerTimeOffset(0, tokenRefreshPage.toString());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RealmResource(org.keycloak.admin.client.resource.RealmResource) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) HttpGet(org.apache.http.client.methods.HttpGet) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Example 9 with RealmResource

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

the class ClientInitiatedAccountLinkTest method testAccountLink.

@Test
public void testAccountLink() throws Exception {
    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"));
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, "client-linking", "password");
    Assert.assertNotNull(response.getAccessToken());
    Assert.assertNull(response.getError());
    Client httpClient = AdminClientUtil.createResteasyClient();
    String firstToken = getToken(response, httpClient);
    Assert.assertNotNull(firstToken);
    navigateTo(linkUrl);
    Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
    String nextToken = getToken(response, httpClient);
    Assert.assertNotNull(nextToken);
    Assert.assertNotEquals(firstToken, nextToken);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    logoutAll();
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) RealmResource(org.keycloak.admin.client.resource.RealmResource) 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) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

Example 10 with RealmResource

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

the class ClientInitiatedAccountLinkTest method testErrorConditions.

@Test
public void testErrorConditions() throws Exception {
    String helloUrl = appPage.getUriBuilder().clone().path("hello").build().toASCIIString();
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    ClientRepresentation client = adminClient.realms().realm(CHILD_IDP).clients().findByClientId("client-linking").get(0);
    UriBuilder redirectUri = UriBuilder.fromUri(appPage.getInjectedUrl().toString()).path("link").queryParam("response", "true");
    UriBuilder directLinking = UriBuilder.fromUri(getAuthServerContextRoot() + "/auth").path("realms/child/broker/{provider}/link").queryParam("client_id", "client-linking").queryParam("redirect_uri", redirectUri.build()).queryParam("hash", Base64Url.encode("crap".getBytes())).queryParam("nonce", UUID.randomUUID().toString());
    String linkUrl = directLinking.build(PARENT_IDP).toString();
    // test not logged in
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_logged_in"));
    logoutAll();
    // now log in
    navigateTo(helloUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().startsWith(helloUrl));
    Assert.assertTrue(driver.getPageSource().contains("Unknown request:"));
    // now test CSRF with bad hash.
    navigateTo(linkUrl);
    Assert.assertTrue(driver.getPageSource().contains("We are sorry..."));
    logoutAll();
    // now log in again with client that does not have scope
    String accountId = adminClient.realms().realm(CHILD_IDP).clients().findByClientId(ACCOUNT_MANAGEMENT_CLIENT_ID).get(0).getId();
    RoleRepresentation manageAccount = adminClient.realms().realm(CHILD_IDP).clients().get(accountId).roles().get(MANAGE_ACCOUNT).toRepresentation();
    RoleRepresentation manageLinks = adminClient.realms().realm(CHILD_IDP).clients().get(accountId).roles().get(MANAGE_ACCOUNT_LINKS).toRepresentation();
    RoleRepresentation userRole = adminClient.realms().realm(CHILD_IDP).roles().get("user").toRepresentation();
    client.setFullScopeAllowed(false);
    ClientResource clientResource = adminClient.realms().realm(CHILD_IDP).clients().get(client.getId());
    clientResource.update(client);
    List<RoleRepresentation> roles = new LinkedList<>();
    roles.add(userRole);
    clientResource.getScopeMappings().realmLevel().add(roles);
    navigateTo(helloUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().startsWith(helloUrl));
    Assert.assertTrue(driver.getPageSource().contains("Unknown request:"));
    UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString()).path("link");
    String clientLinkUrl = linkBuilder.clone().queryParam("realm", CHILD_IDP).queryParam("provider", PARENT_IDP).build().toString();
    navigateTo(clientLinkUrl);
    Assert.assertTrue(driver.getCurrentUrl().contains("error=not_allowed"));
    logoutAll();
    // add MANAGE_ACCOUNT_LINKS scope should pass.
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    roles = new LinkedList<>();
    roles.add(manageLinks);
    clientResource.getScopeMappings().clientLevel(accountId).add(roles);
    navigateTo(clientLinkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
    loginPage.login(PARENT_USERNAME, "password");
    Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
    Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    clientResource.getScopeMappings().clientLevel(accountId).remove(roles);
    logoutAll();
    navigateTo(clientLinkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_allowed"));
    logoutAll();
    // add MANAGE_ACCOUNT scope should pass
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    roles = new LinkedList<>();
    roles.add(manageAccount);
    clientResource.getScopeMappings().clientLevel(accountId).add(roles);
    navigateTo(clientLinkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
    loginPage.login(PARENT_USERNAME, "password");
    Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
    Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    clientResource.getScopeMappings().clientLevel(accountId).remove(roles);
    logoutAll();
    navigateTo(clientLinkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(driver.getCurrentUrl().contains("link_error=not_allowed"));
    logoutAll();
    // undo fullScopeAllowed
    client = adminClient.realms().realm(CHILD_IDP).clients().findByClientId("client-linking").get(0);
    client.setFullScopeAllowed(true);
    clientResource.update(client);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    logoutAll();
}
Also used : RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) ClientResource(org.keycloak.admin.client.resource.ClientResource) UriBuilder(javax.ws.rs.core.UriBuilder) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) LinkedList(java.util.LinkedList) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest)

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