org.keycloak.representations.idm.ClientRepresentation Java Examples

The following examples show how to use org.keycloak.representations.idm.ClientRepresentation. 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: UserTest.java    From keycloak with Apache License 2.0 7 votes vote down vote up
@Test
public void countUsersNotServiceAccount() {
    createUsers();

    Integer count = realm.users().count();
    assertEquals(9, count.intValue());

    ClientRepresentation client = new ClientRepresentation();

    client.setClientId("test-client");
    client.setPublicClient(false);
    client.setSecret("secret");
    client.setServiceAccountsEnabled(true);
    client.setEnabled(true);
    client.setRedirectUris(Arrays.asList("http://url"));

    getAdminClient().realm(REALM_NAME).clients().create(client);

    // KEYCLOAK-5660, should not consider service accounts
    assertEquals(9, realm.users().count().intValue());
}
 
Example #2
Source File: ClientRegistrationTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void withServiceAccount() throws ClientRegistrationException {
    authManageClients();
    ClientRepresentation clientRep = buildClient();
    clientRep.setServiceAccountsEnabled(true);

    ClientRepresentation rep = registerClient(clientRep);

    UserRepresentation serviceAccountUser = adminClient.realm("test").clients().get(rep.getId()).getServiceAccountUser();

    assertNotNull(serviceAccountUser);

    deleteClient(rep);

    try {
        adminClient.realm("test").users().get(serviceAccountUser.getId()).toRepresentation();
        fail("Expected NotFoundException");
    } catch (NotFoundException e) {
    }
}
 
Example #3
Source File: RealmsConfigurationLoader.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static void readClients(RealmRepresentation r, JsonParser p) throws IOException {
    JsonToken t = p.nextToken();
    if (t != JsonToken.START_ARRAY) {
        throw new RuntimeException("Error reading field 'clients'. Expected array of clients [" + t + "]");
    }

    t = p.nextToken();
    while (t == JsonToken.START_OBJECT) {
        ClientRepresentation u = p.readValueAs(ClientRepresentation.class);
        enqueueCreateClient(r, u);
        t = p.nextToken();
        currentClient += 1;

        // every some users check to see pending errors
        if (currentClient % ERROR_CHECK_INTERVAL == 0) {
            checkPendingErrors(u.getClientId());
        }
    }
}
 
Example #4
Source File: InitialAccessTokenTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void create() throws ClientRegistrationException, InterruptedException {
    ClientInitialAccessPresentation response = resource.create(new ClientInitialAccessCreatePresentation());

    reg.auth(Auth.token(response));

    ClientRepresentation rep = new ClientRepresentation();

    setTimeOffset(10);

    ClientRepresentation created = reg.create(rep);
    Assert.assertNotNull(created);

    try {
        reg.create(rep);
        Assert.fail("Expected exception");
    } catch (ClientRegistrationException e) {
        assertEquals(401, ((HttpErrorException) e.getCause()).getStatusLine().getStatusCode());
    }
}
 
Example #5
Source File: AuthnRequestNameIdFormatTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testRedirectLoginNoNameIdPolicyForcePostBinding() throws Exception {
    ClientsResource clients = adminClient.realm(REALM_NAME).clients();
    List<ClientRepresentation> foundClients = clients.findByClientId(SAML_CLIENT_ID_SALES_POST);
    assertThat(foundClients, hasSize(1));
    ClientResource clientRes = clients.get(foundClients.get(0).getId());
    ClientRepresentation client = clientRes.toRepresentation();
    client.getAttributes().put(SamlConfigAttributes.SAML_FORCE_POST_BINDING, "true");
    clientRes.update(client);

    testLoginWithNameIdPolicy(Binding.REDIRECT, Binding.POST, null, is("bburke"));

    // Revert
    client = clientRes.toRepresentation();
    client.getAttributes().put(SamlConfigAttributes.SAML_FORCE_POST_BINDING, "false");
    clientRes.update(client);
}
 
Example #6
Source File: FineGrainAdminUnitTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testMasterRealmWithComposites() throws Exception {
    RoleRepresentation composite = new RoleRepresentation();
    composite.setName("composite");
    composite.setComposite(true);
    adminClient.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 createClient = adminClient.realm(TEST).clients().get(client.getId()).roles().get(AdminRoles.CREATE_CLIENT).toRepresentation();
    RoleRepresentation queryRealms = adminClient.realm(TEST).clients().get(client.getId()).roles().get(AdminRoles.QUERY_REALMS).toRepresentation();
    List<RoleRepresentation> composites = new LinkedList<>();
    composites.add(createClient);
    composites.add(queryRealms);
    adminClient.realm(TEST).rolesById().addComposites(composite.getId(), composites);
}
 
Example #7
Source File: ResourcesRestServiceTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
    super.configureTestRealm(testRealm);
    RealmRepresentation realmRepresentation = testRealm;

    realmRepresentation.setUserManagedAccessAllowed(true);

    testRealm.getUsers().add(createUser("alice", "password"));
    testRealm.getUsers().add(createUser("jdoe", "password"));
    testRealm.getUsers().add(createUser("bob", "password"));

    ClientRepresentation client = ClientBuilder.create()
            .clientId("my-resource-server")
            .authorizationServicesEnabled(true)
            .serviceAccountsEnabled(true)
            .secret("secret")
            .name("My Resource Server")
            .baseUrl("http://resourceserver.com")
            .directAccessGrants().build();

    testRealm.getClients().add(client);
}
 
Example #8
Source File: ClientRegistrationPoliciesTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void assertFail(ClientRegOp operation, ClientRepresentation client, int expectedStatusCode, String expectedErrorContains) {
    try {
        switch (operation) {
            case CREATE: reg.create(client);
                break;
            case UPDATE: reg.update(client);
                break;
            case DELETE: reg.delete(client);
                break;
        }

        Assert.fail("Not expected to successfuly run operation " + operation.toString() + " on client");
    } catch (ClientRegistrationException expected) {
        HttpErrorException httpEx = (HttpErrorException) expected.getCause();
        Assert.assertEquals(expectedStatusCode, httpEx.getStatusLine().getStatusCode());
        if (expectedErrorContains != null) {
            assertTrue("Error response doesn't contain expected text. The error response text is: " + httpEx.getErrorResponse(), httpEx.getErrorResponse().contains(expectedErrorContains));
        }
    }
}
 
Example #9
Source File: KcSamlSignedDocumentOnlyBrokerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public List<ClientRepresentation> createProviderClients() {
    List<ClientRepresentation> clientRepresentationList = super.createProviderClients();

    for (ClientRepresentation client : clientRepresentationList) {
        client.setClientAuthenticatorType("client-secret");
        client.setSurrogateAuthRequired(false);

        Map<String, String> attributes = client.getAttributes();
        if (attributes == null) {
            attributes = new HashMap<>();
            client.setAttributes(attributes);
        }

        attributes.put("saml.assertion.signature", "false");
        attributes.put("saml.server.signature", "true");
        attributes.put("saml.client.signature", "true");
        attributes.put("saml.signature.algorithm", "RSA_SHA256");
        attributes.put("saml.signing.private.key", IDP_SAML_SIGN_KEY);
        attributes.put("saml.signing.certificate", IDP_SAML_SIGN_CERT);
    }

    return clientRepresentationList;
}
 
Example #10
Source File: OAuthGrantTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void oauthGrantExpiredAuthSession() throws Exception {
    oauth.clientId(THIRD_PARTY_APP);
    oauth.doLoginGrant("test-user@localhost", "password");

    grantPage.assertCurrent();

    // Expire cookies
    driver.manage().deleteAllCookies();

    grantPage.accept();

    // Assert link "back to application" present
    errorPage.assertCurrent();
    String backToAppLink = errorPage.getBackToApplicationLink();
    ClientRepresentation thirdParty = findClientByClientId(adminClient.realm(REALM_NAME), THIRD_PARTY_APP).toRepresentation();
    Assert.assertEquals(backToAppLink, thirdParty.getBaseUrl());
}
 
Example #11
Source File: ApiUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static AuthorizationResource findAuthorizationSettings(RealmResource realm, String clientId) {
    for (ClientRepresentation c : realm.clients().findAll()) {
        if (c.getClientId().equals(clientId)) {
            return realm.clients().get(c.getId()).authorization();
        }
    }
    return null;
}
 
Example #12
Source File: ApiUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ClientResource findClientResourceByName(RealmResource realm, String name) {
    for (ClientRepresentation c : realm.clients().findAll()) {
        if (name.equals(c.getName())) {
            return realm.clients().get(c.getId());
        }
    }
    return null;
}
 
Example #13
Source File: ClientInvalidationClusterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected ClientRepresentation createTestEntityRepresentation() {
    ClientRepresentation client = new ClientRepresentation();
    String s = RandomStringUtils.randomAlphabetic(5);
    client.setClientId("client_" + s);
    client.setName("name_" + s);
    return client;
}
 
Example #14
Source File: ClientRegistrationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ClientRepresentation registerClient(ClientRepresentation client) throws ClientRegistrationException {
    ClientRepresentation createdClient = reg.create(client);
    assertEquals(CLIENT_ID, createdClient.getClientId());

    client = adminClient.realm(REALM_NAME).clients().get(createdClient.getId()).toRepresentation();
    assertEquals(CLIENT_ID, client.getClientId());

    // Remove this client after test
    getCleanup().addClientUuid(createdClient.getId());

    return client;
}
 
Example #15
Source File: ClientSettingsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
@EnableFeature(value = Profile.Feature.ACCOUNT2, skipRestart = true)
public void alwaysDisplayInAccountConsole() {
    refreshPageAndWaitForLoad();

    newClient = createClientRep("always-display-in-console", OIDC);
    createClient(newClient);

    newClient.setRedirectUris(TEST_REDIRECT_URIs);
    newClient.setAlwaysDisplayInConsole(true);

    assertFalse(clientSettingsPage.form().isAlwaysDisplayInConsole());
    clientSettingsPage.form().setAlwaysDisplayInConsole(true);
    clientSettingsPage.form().setRedirectUris(TEST_REDIRECT_URIs);
    clientSettingsPage.form().save();
    assertTrue(clientSettingsPage.form().isAlwaysDisplayInConsole());

    ClientRepresentation found = findClientByClientId(newClient.getClientId());
    assertNotNull("Client " + newClient.getClientId() + " was not found.", found);
    assertClientSettingsEqual(newClient, found);

    clientSettingsPage.form().setAccessType(BEARER_ONLY);
    assertFalse(clientSettingsPage.form().isAlwaysDisplayInConsoleVisible());
    // check if the switch is displayed when change the Client to SAML and bearer-only flag is set to on (bearer-only
    // is not applicable for SAML but it's technically present in the Client representation and therefore can affect
    // the visibility of the switch)
    clientSettingsPage.form().setProtocol(SAML);
    assertTrue(clientSettingsPage.form().isAlwaysDisplayInConsoleVisible());
}
 
Example #16
Source File: Creator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Creator<ClientResource> create(RealmResource realmResource, ClientRepresentation rep) {
    final ClientsResource clients = realmResource.clients();
    try (Response response = clients.create(rep)) {
        String createdId = getCreatedId(response);
        final ClientResource r = clients.get(createdId);
        LOG.debugf("Created client ID %s", createdId);
        return new Creator(createdId, r, r::remove);
    }
}
 
Example #17
Source File: ClientsPartialImport.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void create(RealmModel realm, KeycloakSession session, ClientRepresentation clientRep) {
    clientRep.setId(KeycloakModelUtils.generateId());

    List<ProtocolMapperRepresentation> mappers = clientRep.getProtocolMappers();
    if (mappers != null) {
        for (ProtocolMapperRepresentation mapper : mappers) {
            mapper.setId(KeycloakModelUtils.generateId());
        }
    }

    ClientModel client = RepresentationToModel.createClient(session, realm, clientRep, true);
    RepresentationToModel.importAuthorizationSettings(clientRep, client, session);
}
 
Example #18
Source File: ClientRegistrationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void updateClientProtcolMappers() throws ClientRegistrationException {
    authManageClients();

    ClientRepresentation initialClient = buildClient();
    addProtocolMapper(initialClient, "mapperA");
    registerClient(initialClient);
    ClientRepresentation client = reg.get(CLIENT_ID);
    client.getProtocolMappers().get(0).getConfig().put("claim.name", "updatedClaimName");
    reg.update(client);

    ClientRepresentation updatedClient = reg.get(CLIENT_ID);
    assertThat("Updating protocolMapper failed", updatedClient.getProtocolMappers().get(0).getConfig().get("claim.name"), is("updatedClaimName"));
}
 
Example #19
Source File: ClientRegistrationTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ClientRepresentation buildClient() {
	ClientRepresentation client = new ClientRepresentation();
    client.setClientId(CLIENT_ID);
    client.setSecret(CLIENT_SECRET);
    
    return client;
}
 
Example #20
Source File: RealmTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void renameRealm() {
    RealmRepresentation rep = new RealmRepresentation();
    rep.setId("old");
    rep.setRealm("old");

    try {
        adminClient.realms().create(rep);

        rep.setRealm("new");
        adminClient.realm("old").update(rep);

        // Check client in master realm renamed
        Assert.assertEquals(0, adminClient.realm("master").clients().findByClientId("old-realm").size());
        Assert.assertEquals(1, adminClient.realm("master").clients().findByClientId("new-realm").size());

        ClientRepresentation adminConsoleClient = adminClient.realm("new").clients().findByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID).get(0);
        assertEquals(Constants.AUTH_ADMIN_URL_PROP, adminConsoleClient.getRootUrl());
        assertEquals("/admin/new/console/", adminConsoleClient.getBaseUrl());
        assertEquals("/admin/new/console/*", adminConsoleClient.getRedirectUris().get(0));

        ClientRepresentation accountClient = adminClient.realm("new").clients().findByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).get(0);
        assertEquals(Constants.AUTH_BASE_URL_PROP, accountClient.getRootUrl());
        assertEquals("/realms/new/account/", accountClient.getBaseUrl());
        assertEquals("/realms/new/account/*", accountClient.getRedirectUris().get(0));
    } finally {
        adminClient.realms().realm(rep.getRealm()).remove();
    }
}
 
Example #21
Source File: ClientsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void clientsNavigationTest() {
    //create 100 clients
    create100Clients();
    String firstPageClient = TEST_CLIENT_ID + 0;
    String secondPageClient = TEST_CLIENT_ID + 22;
    String thirdPageClient = TEST_CLIENT_ID + 41;

    //edit on the 2nd page then go back
    clientsPage.navigateTo();
    clientsPage.table().clickNextPage();
    clientsPage.table().editClient(secondPageClient);
    assertEquals(secondPageClient, clientSettingsPage.form().getClientId());

    //go to the main page and delete
    clientsPage.navigateTo();
    clientsPage.table().clickPrevPage();
    clientsPage.table().deleteClient(TEST_CLIENT_ID);
    modalDialog.confirmDeletion();
    ClientRepresentation found = findClientByClientId(TEST_CLIENT_ID);
    assertNull("Deleted client " + TEST_CLIENT_ID + " was found.", found);

    // go forward two pages then main page
    clientsPage.navigateTo();
    clientsPage.table().clickNextPage();
    clientsPage.table().clickNextPage();
    clientsPage.table().editClient(thirdPageClient);
    assertEquals(thirdPageClient, clientSettingsPage.form().getClientId());
    clientsPage.navigateTo();

    clientsPage.table().clickFirstPage();
    clientsPage.table().editClient(firstPageClient);
    assertEquals(firstPageClient, clientSettingsPage.form().getClientId());
    clientsPage.navigateTo();

}
 
Example #22
Source File: AbstractAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void modifySamlMasterURLs(RealmRepresentation realm, String regex, String replacement) {
    if (realm.getClients() != null) {
        for (ClientRepresentation client : realm.getClients()) {
            if (client.getProtocol() != null && client.getProtocol().equals("saml")) {
                log.debug("Modifying master URL of SAML client: " + client.getClientId());
                String masterUrl = client.getAdminUrl();
                if (masterUrl == null) {
                    masterUrl = client.getBaseUrl();
                }
                masterUrl = masterUrl.replaceFirst(regex, replacement);
                client.setAdminUrl(masterUrl + ((!masterUrl.endsWith("/saml")) ? "/saml" : ""));
            }
        }
    }
}
 
Example #23
Source File: ConsentsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void addClients() {
    List<ClientRepresentation> clients = createProviderClients();
    if (clients != null) {
        RealmResource providerRealm = adminClient.realm(providerRealmName());
        for (ClientRepresentation client : clients) {
            log.debug("adding client " + client.getName() + " to realm " + providerRealmName());

            providerRealm.clients().create(client);
        }
    }
}
 
Example #24
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientNotAuthenticatedInClientSecretJwtByAuthnMethodOutOfSync() {
    // JWS Client Assertion in client_secret_jwt
    // http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
    String targetClientId = "client-secret-jwt-secure-portal";
    String expectedErrorString = "invalid_client_credentials";

    ClientResource clientResource = ApiUtil.findClientResourceByClientId(testRealmResource(), targetClientId);
    ClientRepresentation client = clientResource.toRepresentation();
    client.setClientAuthenticatorType("client-secret");
    clientResource.update(client);

    expectResultOfClientNotAuthenticatedInClientSecretJwt(targetClientId, expectedErrorString);
}
 
Example #25
Source File: PairwiseClientValidator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean validate(KeycloakSession session, ClientRepresentation client, ValidationMessages messages) {
    String rootUrl = client.getRootUrl();
    Set<String> redirectUris = new HashSet<>();
    boolean valid = true;

    List<ProtocolMapperRepresentation> foundPairwiseMappers = PairwiseSubMapperUtils.getPairwiseSubMappers(client);

    for (ProtocolMapperRepresentation foundPairwise : foundPairwiseMappers) {
        String sectorIdentifierUri = PairwiseSubMapperHelper.getSectorIdentifierUri(foundPairwise);
        if (client.getRedirectUris() != null) redirectUris.addAll(client.getRedirectUris());
        valid = valid && validate(session, rootUrl, redirectUris, sectorIdentifierUri, messages);
    }

    return true;
}
 
Example #26
Source File: ClientTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * See <a href="https://issues.jboss.org/browse/KEYCLOAK-1918">KEYCLOAK-1918</a>
 */
@Test
public void getClientDescription() {
    String id = createClient().getId();

    ClientRepresentation rep = realm.clients().get(id).toRepresentation();
    assertEquals(id, rep.getId());
    assertEquals("my-app description", rep.getDescription());
}
 
Example #27
Source File: AbstractKeycloakTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void modifyRedirectUrls(ClientRepresentation cr) {
    if (cr.getRedirectUris() != null && cr.getRedirectUris().size() > 0) {
        List<String> redirectUrls = cr.getRedirectUris();
        List<String> fixedRedirectUrls = new ArrayList<>(redirectUrls.size());
        for (String url : redirectUrls) {
            fixedRedirectUrls.add(replaceHttpValuesWithHttps(url));
        }
        cr.setRedirectUris(fixedRedirectUrls);
    }
}
 
Example #28
Source File: ApiUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ClientResource findClientResourceByClientId(RealmResource realm, String clientId) {
    for (ClientRepresentation c : realm.clients().findAll()) {
        if (c.getClientId().equals(clientId)) {
            return realm.clients().get(c.getId());
        }
    }
    return null;
}
 
Example #29
Source File: ClientImportService.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
private void updateClientIfNeeded(String realm, ClientRepresentation clientToUpdate, ClientRepresentation existingClient) {
    ClientRepresentation patchedClient = CloneUtil.patch(existingClient, clientToUpdate, "id", "access");

    if (!isClientEqual(realm, existingClient, patchedClient)) {
        logger.debug("Update client '{}' in realm '{}'", clientToUpdate.getClientId(), realm);
        updateClient(realm, patchedClient);
    } else {
        logger.debug("No need to update client '{}' in realm '{}'", clientToUpdate.getClientId(), realm);
    }
}
 
Example #30
Source File: ClientImportService.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
private void createOrUpdateClients(RealmImport realmImport, List<ClientRepresentation> clients) {
    Consumer<ClientRepresentation> loop = client -> createOrUpdateClient(realmImport, client);
    if (importConfigProperties.isParallel()) {
        clients.parallelStream().forEach(loop);
    } else {
        clients.forEach(loop);
    }
}