Java Code Examples for org.keycloak.admin.client.resource.RealmResource#clients()

The following examples show how to use org.keycloak.admin.client.resource.RealmResource#clients() . 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: ClientRepository.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
public Optional<ClientRepresentation> tryToFindClient(String realm, String clientId) {
    Optional<ClientRepresentation> maybeClient;

    RealmResource realmResource = realmRepository.loadRealm(realm);
    ClientsResource clients = realmResource.clients();

    List<ClientRepresentation> foundClients = clients.findByClientId(clientId);

    if (foundClients.isEmpty()) {
        maybeClient = Optional.empty();
    } else {
        maybeClient = Optional.of(foundClients.get(0));
    }

    return maybeClient;
}
 
Example 2
Source File: ClientRepository.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
public void create(String realm, ClientRepresentation clientToCreate) {
    RealmResource realmResource = realmRepository.loadRealm(realm);
    ClientsResource clientsResource = realmResource.clients();

    Response response = clientsResource.create(clientToCreate);
    ResponseUtil.throwOnError(response);
}
 
Example 3
Source File: ClientRepository.java    From keycloak-config-cli with Apache License 2.0 5 votes vote down vote up
public void update(String realm, ClientRepresentation clientToUpdate) {
    RealmResource realmResource = realmRepository.loadRealm(realm);
    ClientsResource clientsResource = realmResource.clients();
    ClientResource clientResource = clientsResource.get(clientToUpdate.getId());

    clientResource.update(clientToUpdate);
}
 
Example 4
Source File: ClientAttributeUpdater.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@ClientAttributeUpdater} for the given client. The client must exist.
 * @param adminClient
 * @param realm
 * @param clientId
 * @return
 */
public static ClientAttributeUpdater forClient(Keycloak adminClient, String realm, String clientId) {
    RealmResource realmRes = adminClient.realm(realm);
    ClientsResource clients = realmRes.clients();
    List<ClientRepresentation> foundClients = clients.findByClientId(clientId);
    assertThat(foundClients, hasSize(1));
    ClientResource clientRes = clients.get(foundClients.get(0).getId());
    
    return new ClientAttributeUpdater(clientRes, realmRes);
}
 
Example 5
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 6
Source File: ConcurrencyTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void run(int threadIndex, Keycloak keycloak, RealmResource realm) throws Throwable {
    String name = "c-" + clientIndex.getAndIncrement();
    ClientRepresentation c = new ClientRepresentation();
    c.setClientId(name);
    final ClientsResource clients = realm.clients();

    Response response = clients.create(c);
    String id = ApiUtil.getCreatedId(response);
    response.close();
    final ClientResource client = clients.get(id);

    c = client.toRepresentation();
    assertNotNull(c);
    assertTrue("Client " + name + " not found in client list",
      clients.findAll().stream()
        .map(ClientRepresentation::getClientId)
        .filter(Objects::nonNull)
        .anyMatch(name::equals));

    client.remove();
    try {
        client.toRepresentation();
        fail("Client " + name + " should not be found.  Should throw a 404");
    } catch (NotFoundException e) {

    }

    assertFalse("Client " + name + " should now not present in client list",
      clients.findAll().stream()
        .map(ClientRepresentation::getClientId)
        .filter(Objects::nonNull)
        .anyMatch(name::equals));
}
 
Example 7
Source File: KcOidcBrokerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.OIDCBrokerUserPropertyTest
 */
@Test
public void loginFetchingUserFromUserEndpointWithClaimMapper() {
    RealmResource realm = realmsResouce().realm(bc.providerRealmName());
    ClientsResource clients = realm.clients();
    ClientRepresentation brokerApp = clients.findByClientId("brokerapp").get(0);
    IdentityProviderResource identityProviderResource = getIdentityProviderResource();

    clients.get(brokerApp.getId()).getProtocolMappers().createMapper(createHardcodedClaim("hard-coded", "hard-coded", "hard-coded", "String", true, true)).close();

    IdentityProviderMapperRepresentation hardCodedSessionNoteMapper = new IdentityProviderMapperRepresentation();

    hardCodedSessionNoteMapper.setName("hard-coded");
    hardCodedSessionNoteMapper.setIdentityProviderAlias(bc.getIDPAlias());
    hardCodedSessionNoteMapper.setIdentityProviderMapper(UserAttributeMapper.PROVIDER_ID);
    hardCodedSessionNoteMapper.setConfig(ImmutableMap.<String, String>builder()
            .put(IdentityProviderMapperModel.SYNC_MODE, IdentityProviderMapperSyncMode.INHERIT.toString())
            .put(UserAttributeMapper.USER_ATTRIBUTE, "hard-coded")
            .put(UserAttributeMapper.CLAIM, "hard-coded")
            .build());

    identityProviderResource.addMapper(hardCodedSessionNoteMapper).close();

    loginFetchingUserFromUserEndpoint();

    UserRepresentation user = getFederatedIdentity();

    Assert.assertEquals(1, user.getAttributes().size());
    Assert.assertEquals("hard-coded", user.getAttributes().get("hard-coded").get(0));
}
 
Example 8
Source File: KcRegCreateTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateWithAuthorizationServices() throws IOException {
    FileConfigHandler handler = initCustomConfigFile();

    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {

        KcRegExec exe = execute("config credentials -x --config '" + configFile.getName() +
                "' --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm master --user admin --password admin");
        assertExitCodeAndStreamSizes(exe, 0, 0, 3);

        String token = issueInitialAccessToken("test");
        exe = execute("create --config '" + configFile.getName() + "' --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm test -s clientId=authz-client -s authorizationServicesEnabled=true -t " + token);
        assertExitCodeAndStreamSizes(exe, 0, 0, 3);

        RealmResource realm = adminClient.realm("test");
        ClientsResource clients = realm.clients();
        ClientRepresentation clientRep = clients.findByClientId("authz-client").get(0);

        ClientResource client = clients.get(clientRep.getId());

        clientRep = client.toRepresentation();
        Assert.assertTrue(clientRep.getAuthorizationServicesEnabled());

        ResourceServerRepresentation settings = client.authorization().getSettings();

        Assert.assertEquals(PolicyEnforcementMode.ENFORCING, settings.getPolicyEnforcementMode());
        Assert.assertTrue(settings.isAllowRemoteResourceManagement());

        List<RoleRepresentation> roles = client.roles().list();

        Assert.assertEquals(1, roles.size());
        Assert.assertEquals("uma_protection", roles.get(0).getName());

        // create using oidc endpoint - autodetect format
        String content = "        {\n" +
                "            \"redirect_uris\" : [ \"http://localhost:8980/myapp/*\" ],\n" +
                "            \"grant_types\" : [ \"authorization_code\", \"client_credentials\", \"refresh_token\", \"" + OAuth2Constants.UMA_GRANT_TYPE + "\" ],\n" +
                "            \"response_types\" : [ \"code\", \"none\" ],\n" +
                "            \"client_name\" : \"My Reg Authz\",\n" +
                "            \"client_uri\" : \"http://localhost:8980/myapp\"\n" +
                "        }";

        try (TempFileResource tmpFile = new TempFileResource(initTempFile(".json", content))) {

            exe = execute("create --insecure --config '" + configFile.getName() + "' -s 'client_name=My Reg Authz' --realm test -t " + token +
                    " -s 'redirect_uris=[\"http://localhost:8980/myapp5/*\"]' -s client_uri=http://localhost:8980/myapp5" +
                    " -o -f - < '" + tmpFile.getName() + "'");

            assertExitCodeAndStdErrSize(exe, 0, 2);

            OIDCClientRepresentation oidcClient = JsonSerialization.readValue(exe.stdout(), OIDCClientRepresentation.class);

            Assert.assertNotNull("clientId", oidcClient.getClientId());
            Assert.assertEquals("redirect_uris", Arrays.asList("http://localhost:8980/myapp5/*"), oidcClient.getRedirectUris());
            Assert.assertThat("grant_types", oidcClient.getGrantTypes(), Matchers.containsInAnyOrder("authorization_code", "client_credentials", "refresh_token", OAuth2Constants.UMA_GRANT_TYPE));
            Assert.assertEquals("response_types", Arrays.asList("code", "none"), oidcClient.getResponseTypes());
            Assert.assertEquals("client_name", "My Reg Authz", oidcClient.getClientName());
            Assert.assertEquals("client_uri", "http://localhost:8980/myapp5", oidcClient.getClientUri());

            client = clients.get(oidcClient.getClientId());

            clientRep = client.toRepresentation();
            Assert.assertTrue(clientRep.getAuthorizationServicesEnabled());

            settings = client.authorization().getSettings();

            Assert.assertEquals(PolicyEnforcementMode.ENFORCING, settings.getPolicyEnforcementMode());
            Assert.assertTrue(settings.isAllowRemoteResourceManagement());

            roles = client.roles().list();

            Assert.assertEquals(1, roles.size());
            Assert.assertEquals("uma_protection", roles.get(0).getName());

            UserRepresentation serviceAccount = realm.users().search(ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + clientRep.getClientId()).get(0);
            Assert.assertNotNull(serviceAccount);
            List<RoleRepresentation> serviceAccountRoles = realm.users().get(serviceAccount.getId()).roles().clientLevel(clientRep.getId()).listAll();
            Assert.assertTrue(serviceAccountRoles.stream().anyMatch(roleRepresentation -> "uma_protection".equals(roleRepresentation.getName())));
        }
    }
}
 
Example 9
Source File: BrokerTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testLogoutPropagatesToSamlIdentityProvider() throws IOException {
    final RealmResource realm = adminClient.realm(REALM_NAME);
    final ClientsResource clients = realm.clients();

    AuthenticationExecutionInfoRepresentation reviewProfileAuthenticator = null;
    String firstBrokerLoginFlowAlias = null;
    try (IdentityProviderCreator idp = new IdentityProviderCreator(realm, addIdentityProvider("https://saml.idp/saml"))) {
        IdentityProviderRepresentation idpRepresentation = idp.identityProvider().toRepresentation();
        firstBrokerLoginFlowAlias = idpRepresentation.getFirstBrokerLoginFlowAlias();
        List<AuthenticationExecutionInfoRepresentation> executions = realm.flows().getExecutions(firstBrokerLoginFlowAlias);
        reviewProfileAuthenticator = executions.stream()
          .filter(ex -> Objects.equals(ex.getProviderId(), IdpReviewProfileAuthenticatorFactory.PROVIDER_ID))
          .findFirst()
          .orElseGet(() -> { Assert.fail("Could not find update profile in first broker login flow"); return null; });

        reviewProfileAuthenticator.setRequirement(Requirement.DISABLED.name());
        realm.flows().updateExecutions(firstBrokerLoginFlowAlias, reviewProfileAuthenticator);

        SAMLDocumentHolder samlResponse = new SamlClientBuilder()
          .authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, POST)
            .transformObject(ar -> {
                NameIDPolicyType nameIDPolicy = new NameIDPolicyType();
                nameIDPolicy.setAllowCreate(Boolean.TRUE);
                nameIDPolicy.setFormat(JBossSAMLURIConstants.NAMEID_FORMAT_EMAIL.getUri());

                ar.setNameIDPolicy(nameIDPolicy);
                return ar;
            })
            .build()

          .login().idp(SAML_BROKER_ALIAS).build()

          // Virtually perform login at IdP (return artificial SAML response)
          .processSamlResponse(REDIRECT)
            .transformObject(this::createAuthnResponse)
            .targetAttributeSamlResponse()
            .targetUri(getSamlBrokerUrl(REALM_NAME))
            .build()
          .followOneRedirect()  // first-broker-login
          .followOneRedirect()  // after-first-broker-login
          .getSamlResponse(POST);

        assertThat(samlResponse.getSamlObject(), isSamlStatusResponse(
          JBossSAMLURIConstants.STATUS_RESPONDER,
          JBossSAMLURIConstants.STATUS_INVALID_NAMEIDPOLICY
        ));
    } finally {
        reviewProfileAuthenticator.setRequirement(Requirement.REQUIRED.name());
        realm.flows().updateExecutions(firstBrokerLoginFlowAlias, reviewProfileAuthenticator);
    }
}
 
Example 10
Source File: PermissionClaimTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientResource getClient(RealmResource realm) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId("resource-server-test").stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 11
Source File: AbstractResourceServerTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected ClientResource getClient(RealmResource realm) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId("resource-server-test").stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 12
Source File: AuthorizationAPITest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientResource getClient(RealmResource realm, String clientId) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId(clientId).stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 13
Source File: RolePolicyTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientResource getClient(RealmResource realm) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId("resource-server-test").stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 14
Source File: EntitlementAPITest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientResource getClient(RealmResource realm, String clientId) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId(clientId).stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 15
Source File: GroupNamePolicyTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientResource getClient(RealmResource realm) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId("resource-server-test").stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 16
Source File: GroupPathPolicyTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientResource getClient(RealmResource realm) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId("resource-server-test").stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 17
Source File: ConflictingScopePermissionTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientResource getClient(RealmResource realm) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId("resource-server-test").stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 18
Source File: AbstractPolicyManagementTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected ClientResource getClient(RealmResource realm) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId("resource-server-test").stream().map(representation -> clients.get(representation.getId())).findFirst().orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}
 
Example 19
Source File: DeployedScriptPolicyTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private ClientResource getClient(RealmResource realm, String clientId) {
    ClientsResource clients = realm.clients();
    return clients.findByClientId(clientId).stream().map(representation -> clients.get(representation.getId())).findFirst()
            .orElseThrow(() -> new RuntimeException("Expected client [resource-server-test]"));
}