Search in sources :

Example 1 with ConfigData

use of org.keycloak.client.registration.cli.config.ConfigData in project keycloak by keycloak.

the class UpdateCmd method execute.

@Override
public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
    List<AttributeOperation> attrs = new LinkedList<>();
    try {
        if (printHelp()) {
            return help ? CommandResult.SUCCESS : CommandResult.FAILURE;
        }
        processGlobalOptions();
        String clientId = null;
        if (args != null) {
            Iterator<String> it = args.iterator();
            if (!it.hasNext()) {
                throw new IllegalArgumentException("CLIENT_ID not specified");
            }
            clientId = it.next();
            if (clientId.startsWith("-")) {
                warnfErr(ParseUtil.CLIENT_OPTION_WARN, clientId);
            }
            while (it.hasNext()) {
                String option = it.next();
                switch(option) {
                    case "-s":
                    case "--set":
                        {
                            if (!it.hasNext()) {
                                throw new IllegalArgumentException("Option " + option + " requires a value");
                            }
                            String[] keyVal = parseKeyVal(it.next());
                            attrs.add(new AttributeOperation(SET, keyVal[0], keyVal[1]));
                            break;
                        }
                    case "-d":
                    case "--delete":
                        {
                            attrs.add(new AttributeOperation(DELETE, it.next()));
                            break;
                        }
                    default:
                        {
                            throw new IllegalArgumentException("Unsupported option: " + option);
                        }
                }
            }
        }
        if (file == null && attrs.size() == 0) {
            throw new IllegalArgumentException("No file nor attribute values specified");
        }
        // 
        if (file == null && attrs.size() > 0) {
            mergeMode = true;
        }
        CmdStdinContext ctx = new CmdStdinContext();
        if (file != null) {
            ctx = parseFileOrStdin(file, regType);
            regType = ctx.getEndpointType();
        }
        if (regType == null) {
            regType = DEFAULT;
            ctx.setEndpointType(regType);
        } else if (regType != DEFAULT && regType != OIDC) {
            throw new RuntimeException("Update not supported for endpoint type: " + regType.getEndpoint());
        }
        // initialize config only after reading from stdin,
        // to allow proper operation when piping 'get' - which consumes the old
        // registration access token, and saves the new one to the config
        ConfigData config = loadConfig();
        config = copyWithServerInfo(config);
        final String server = config.getServerUrl();
        final String realm = config.getRealm();
        if (token == null) {
            // if registration access token is not set via --token, see if it's in the body of any input file
            // but first see if it's overridden by --set, or maybe deliberately muted via -d registrationAccessToken
            boolean processed = false;
            for (AttributeOperation op : attrs) {
                if ("registrationAccessToken".equals(op.getKey().toString())) {
                    processed = true;
                    if (op.getType() == AttributeOperation.Type.SET) {
                        token = op.getValue();
                    }
                    // otherwise it's delete - meaning it should stay null
                    break;
                }
            }
            if (!processed) {
                token = ctx.getRegistrationAccessToken();
            }
        }
        if (token == null) {
            // if registration access token is not set, try use the one from configuration
            token = getRegistrationToken(config.sessionRealmConfigData(), clientId);
        }
        setupTruststore(config, commandInvocation);
        String auth = token;
        if (auth == null) {
            config = ensureAuthInfo(config, commandInvocation);
            config = copyWithServerInfo(config);
            if (credentialsAvailable(config)) {
                auth = ensureToken(config);
            }
        }
        auth = auth != null ? "Bearer " + auth : null;
        if (mergeMode) {
            InputStream response = doGet(server + "/realms/" + realm + "/clients-registrations/" + regType.getEndpoint() + "/" + urlencode(clientId), APPLICATION_JSON, auth);
            String json = readFully(response);
            CmdStdinContext ctxremote = new CmdStdinContext();
            ctxremote.setContent(json);
            ctxremote.setEndpointType(regType);
            try {
                if (regType == DEFAULT) {
                    ctxremote.setClient(JsonSerialization.readValue(json, ClientRepresentation.class));
                    token = ctxremote.getClient().getRegistrationAccessToken();
                } else if (regType == OIDC) {
                    ctxremote.setOidcClient(JsonSerialization.readValue(json, OIDCClientRepresentation.class));
                    token = ctxremote.getOidcClient().getRegistrationAccessToken();
                }
            } catch (JsonParseException e) {
                throw new RuntimeException("Not a valid JSON document. " + e.getMessage(), e);
            } catch (IOException e) {
                throw new RuntimeException("Not a valid JSON document", e);
            }
            // that ensures optimistic locking semantics
            if (token != null) {
                // we use auth with doPost later
                auth = "Bearer " + token;
                String newToken = token;
                String clientToUpdate = clientId;
                saveMergeConfig(cfg -> {
                    setRegistrationToken(cfg.ensureRealmConfigData(server, realm), clientToUpdate, newToken);
                });
            }
            // merge local representation over remote one
            if (ctx.getClient() != null) {
                ReflectionUtil.merge(ctx.getClient(), ctxremote.getClient());
            } else if (ctx.getOidcClient() != null) {
                ReflectionUtil.merge(ctx.getOidcClient(), ctxremote.getOidcClient());
            }
            ctx = ctxremote;
        }
        if (attrs.size() > 0) {
            ctx = mergeAttributes(ctx, attrs);
        }
        // now update
        InputStream response = doPut(server + "/realms/" + realm + "/clients-registrations/" + regType.getEndpoint() + "/" + urlencode(clientId), APPLICATION_JSON, APPLICATION_JSON, ctx.getContent(), auth);
        try {
            if (regType == DEFAULT) {
                ClientRepresentation clirep = JsonSerialization.readValue(response, ClientRepresentation.class);
                outputResult(clirep);
                token = clirep.getRegistrationAccessToken();
            } else if (regType == OIDC) {
                OIDCClientRepresentation clirep = JsonSerialization.readValue(response, OIDCClientRepresentation.class);
                outputResult(clirep);
                token = clirep.getRegistrationAccessToken();
            }
            String newToken = token;
            String clientToUpdate = clientId;
            saveMergeConfig(cfg -> {
                setRegistrationToken(cfg.ensureRealmConfigData(server, realm), clientToUpdate, newToken);
            });
        } catch (IOException e) {
            throw new RuntimeException("Failed to process HTTP response", e);
        }
        return CommandResult.SUCCESS;
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(e.getMessage() + suggestHelp(), e);
    } finally {
        commandInvocation.stop();
    }
}
Also used : AttributeOperation(org.keycloak.client.registration.cli.common.AttributeOperation) InputStream(java.io.InputStream) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) LinkedList(java.util.LinkedList) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) CmdStdinContext(org.keycloak.client.registration.cli.common.CmdStdinContext)

Example 2 with ConfigData

use of org.keycloak.client.registration.cli.config.ConfigData in project keycloak by keycloak.

the class AbstractAuthOptionsCmd method processGlobalOptions.

protected void processGlobalOptions() {
    super.processGlobalOptions();
    if (config != null && noconfig) {
        throw new RuntimeException("Options --config and --no-config are mutually exclusive");
    }
    if (!noconfig) {
        setConfigFile(config != null ? config : ConfigUtil.DEFAULT_CONFIG_FILE_PATH);
        ConfigUtil.setHandler(new FileConfigHandler());
    } else {
        InMemoryConfigHandler handler = new InMemoryConfigHandler();
        ConfigData data = new ConfigData();
        initConfigData(data);
        handler.setConfigData(data);
        ConfigUtil.setHandler(handler);
    }
}
Also used : FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) InMemoryConfigHandler(org.keycloak.client.registration.cli.config.InMemoryConfigHandler)

Example 3 with ConfigData

use of org.keycloak.client.registration.cli.config.ConfigData in project keycloak by keycloak.

the class KcRegCreateTest method testCreateThoroughly.

@Test
public void testCreateThoroughly() throws IOException {
    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        // set initial access token in config
        String token = issueInitialAccessToken("test");
        final String realm = "test";
        KcRegExec exe = execute("config initial-token -x --config '" + configFile.getName() + "' --insecure --server " + oauth.AUTH_SERVER_ROOT + " --realm " + realm + " " + token);
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        // check that current server, realm, and initial token are saved in the file
        ConfigData config = handler.loadConfig();
        Assert.assertEquals("Config serverUrl", oauth.AUTH_SERVER_ROOT, config.getServerUrl());
        Assert.assertEquals("Config realm", realm, config.getRealm());
        Assert.assertEquals("Config initial access token", token, config.ensureRealmConfigData(oauth.AUTH_SERVER_ROOT, realm).getInitialToken());
        // create configuration from file using stdin redirect ... output an object
        String content = "{\n" + "        \"clientId\": \"my_client\",\n" + "        \"enabled\": true,\n" + "        \"redirectUris\": [\"http://localhost:8980/myapp/*\"],\n" + "        \"serviceAccountsEnabled\": true,\n" + "        \"name\": \"My Client App\",\n" + "        \"implicitFlowEnabled\": false,\n" + "        \"publicClient\": true,\n" + "        \"protocol\": \"openid-connect\",\n" + "        \"webOrigins\": [\"http://localhost:8980/myapp\"],\n" + "        \"consentRequired\": false,\n" + "        \"baseUrl\": \"http://localhost:8980/myapp\",\n" + "        \"rootUrl\": \"http://localhost:8980/myapp\",\n" + "        \"bearerOnly\": true,\n" + "        \"standardFlowEnabled\": true\n" + "}";
        try (TempFileResource tmpFile = new TempFileResource(initTempFile(".json", content))) {
            exe = execute("create --insecure --config '" + configFile.getName() + "' -o -f - < '" + tmpFile.getName() + "'");
            assertExitCodeAndStdErrSize(exe, 0, 2);
            ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
            Assert.assertNotNull("id", client.getId());
            Assert.assertEquals("clientId", "my_client", client.getClientId());
            Assert.assertEquals("enabled", true, client.isEnabled());
            Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp/*"), client.getRedirectUris());
            Assert.assertEquals("serviceAccountsEnabled", true, client.isServiceAccountsEnabled());
            Assert.assertEquals("name", "My Client App", client.getName());
            Assert.assertEquals("implicitFlowEnabled", false, client.isImplicitFlowEnabled());
            Assert.assertEquals("publicClient", true, client.isPublicClient());
            // note there is no server-side check if protocol is supported
            Assert.assertEquals("protocol", "openid-connect", client.getProtocol());
            Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp"), client.getWebOrigins());
            Assert.assertEquals("consentRequired", false, client.isConsentRequired());
            Assert.assertEquals("baseUrl", "http://localhost:8980/myapp", client.getBaseUrl());
            Assert.assertEquals("rootUrl", "http://localhost:8980/myapp", client.getRootUrl());
            Assert.assertEquals("bearerOnly", true, client.isStandardFlowEnabled());
            Assert.assertNull("mappers are null", client.getProtocolMappers());
            // create configuration from file as a template and override clientId and other attributes ... output an object
            exe = execute("create --insecure --config '" + configFile.getName() + "' -o -f '" + tmpFile.getName() + "' -s clientId=my_client2 -s enabled=false -s 'redirectUris=[\"http://localhost:8980/myapp2/*\"]'" + " -s 'name=My Client App II' -s protocol=openid-connect -s 'webOrigins=[\"http://localhost:8980/myapp2\"]'" + " -s baseUrl=http://localhost:8980/myapp2 -s rootUrl=http://localhost:8980/myapp2");
            assertExitCodeAndStdErrSize(exe, 0, 2);
            ClientRepresentation client2 = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
            Assert.assertNotNull("id", client2.getId());
            Assert.assertEquals("clientId", "my_client2", client2.getClientId());
            Assert.assertEquals("enabled", false, client2.isEnabled());
            Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8980/myapp2/*"), client2.getRedirectUris());
            Assert.assertEquals("serviceAccountsEnabled", true, client2.isServiceAccountsEnabled());
            Assert.assertEquals("name", "My Client App II", client2.getName());
            Assert.assertEquals("implicitFlowEnabled", false, client2.isImplicitFlowEnabled());
            Assert.assertEquals("publicClient", true, client2.isPublicClient());
            Assert.assertEquals("protocol", "openid-connect", client2.getProtocol());
            Assert.assertEquals("webOrigins", Arrays.asList("http://localhost:8980/myapp2"), client2.getWebOrigins());
            Assert.assertEquals("consentRequired", false, client2.isConsentRequired());
            Assert.assertEquals("baseUrl", "http://localhost:8980/myapp2", client2.getBaseUrl());
            Assert.assertEquals("rootUrl", "http://localhost:8980/myapp2", client2.getRootUrl());
            Assert.assertEquals("bearerOnly", true, client2.isStandardFlowEnabled());
            Assert.assertNull("mappers are null", client2.getProtocolMappers());
            // check that using an invalid attribute key is not ignored
            exe = execute("create --config '" + configFile.getName() + "' -o -f '" + tmpFile.getName() + "' -s client_id=my_client3");
            assertExitCodeAndStreamSizes(exe, 1, 0, 1);
            Assert.assertEquals("Failed to set attribute 'client_id' on document type 'default'", exe.stderrLines().get(0));
        }
        // simple create, output an id
        exe = execute("create --insecure --config '" + configFile.getName() + "' -i -s clientId=my_client3");
        assertExitCodeAndStreamSizes(exe, 0, 1, 2);
        Assert.assertEquals("only clientId returned", "my_client3", exe.stdoutLines().get(0));
        // simple create, default output
        exe = execute("create --insecure --config '" + configFile.getName() + "' -s clientId=my_client4");
        assertExitCodeAndStreamSizes(exe, 0, 0, 3);
        Assert.assertEquals("only clientId returned", "Registered new client with client_id 'my_client4'", exe.stderrLines().get(2));
        // create using oidc endpoint - autodetect format
        content = "        {\n" + "            \"redirect_uris\" : [ \"http://localhost:8980/myapp/*\" ],\n" + "            \"grant_types\" : [ \"authorization_code\", \"client_credentials\", \"refresh_token\" ],\n" + "            \"response_types\" : [ \"code\", \"none\" ],\n" + "            \"client_name\" : \"My Client App\",\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 Client App V' " + " -s 'redirect_uris=[\"http://localhost:8980/myapp5/*\"]' -s client_uri=http://localhost:8980/myapp5" + " -o -f - < '" + tmpFile.getName() + "'");
            assertExitCodeAndStdErrSize(exe, 0, 2);
            OIDCClientRepresentation client = JsonSerialization.readValue(exe.stdout(), OIDCClientRepresentation.class);
            Assert.assertNotNull("clientId", client.getClientId());
            Assert.assertEquals("redirect_uris", Arrays.asList("http://localhost:8980/myapp5/*"), client.getRedirectUris());
            Assert.assertEquals("grant_types", Arrays.asList("authorization_code", "client_credentials", "refresh_token"), client.getGrantTypes());
            Assert.assertEquals("response_types", Arrays.asList("code", "none"), client.getResponseTypes());
            Assert.assertEquals("client_name", "My Client App V", client.getClientName());
            Assert.assertEquals("client_uri", "http://localhost:8980/myapp5", client.getClientUri());
            // try use incompatible endpoint override
            exe = execute("create --config '" + configFile.getName() + "' -e default -f '" + tmpFile.getName() + "'");
            assertExitCodeAndStreamSizes(exe, 1, 0, 1);
            Assert.assertEquals("Error message", "Attribute 'redirect_uris' not supported on document type 'default'", exe.stderrLines().get(0));
        }
        // test create saml formated xml - format autodetection
        File samlSpMetaFile = new File(System.getProperty("user.dir") + "/src/test/resources/cli/kcreg/saml-sp-metadata.xml");
        Assert.assertTrue("saml-sp-metadata.xml exists", samlSpMetaFile.isFile());
        exe = execute("create --insecure --config '" + configFile.getName() + "' -o -f - < '" + samlSpMetaFile.getAbsolutePath() + "'");
        assertExitCodeAndStdErrSize(exe, 0, 2);
        ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertNotNull("id", client.getId());
        Assert.assertEquals("clientId", "http://localhost:8080/sales-post-enc/", client.getClientId());
        Assert.assertEquals("redirectUris", Arrays.asList("http://localhost:8081/sales-post-enc/saml"), client.getRedirectUris());
        Assert.assertEquals("attributes.saml_name_id_format", "username", client.getAttributes().get("saml_name_id_format"));
        Assert.assertEquals("attributes.saml_assertion_consumer_url_post", "http://localhost:8081/sales-post-enc/saml", client.getAttributes().get("saml_assertion_consumer_url_post"));
        Assert.assertEquals("attributes.saml.signature.algorithm", "RSA_SHA256", client.getAttributes().get("saml.signature.algorithm"));
        // delete initial token
        exe = execute("config initial-token --config '" + configFile.getName() + "' --insecure --server " + serverUrl + " --realm " + realm + " --delete");
        assertExitCodeAndStreamSizes(exe, 0, 0, 0);
        config = handler.loadConfig();
        Assert.assertNull("initial token == null", config.ensureRealmConfigData(serverUrl, realm).getInitialToken());
    }
}
Also used : FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) File(java.io.File) TempFileResource(org.keycloak.testsuite.util.TempFileResource) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

Example 4 with ConfigData

use of org.keycloak.client.registration.cli.config.ConfigData in project keycloak by keycloak.

the class KcRegTruststoreTest method testTruststore.

@Test
public void testTruststore() throws IOException {
    File truststore = new File("src/test/resources/keystore/keycloak.truststore");
    KcRegExec exe = execute("config truststore --no-config '" + truststore.getAbsolutePath() + "'");
    assertExitCodeAndStreamSizes(exe, 1, 0, 2);
    Assert.assertEquals("stderr first line", "Unsupported option: --no-config", exe.stderrLines().get(0));
    Assert.assertEquals("try help", "Try '" + OsUtil.CMD + " help config truststore' for more information", exe.stderrLines().get(1));
    // only run the rest of this test if ssl protected keycloak server is available
    if (!AUTH_SERVER_SSL_REQUIRED) {
        System.out.println("TEST SKIPPED - This test requires HTTPS. Run with '-Pauth-server-wildfly -Dauth.server.ssl.required=true'");
        return;
    }
    FileConfigHandler handler = initCustomConfigFile();
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        if (runIntermittentlyFailingTests()) {
            // configure truststore
            exe = execute("config truststore --config '" + configFile.getName() + "' '" + truststore.getAbsolutePath() + "'");
            assertExitCodeAndStreamSizes(exe, 0, 0, 0);
            // perform authentication against server - asks for password, then for truststore password
            exe = KcRegExec.newBuilder().argsLine("config credentials --server " + oauth.AUTH_SERVER_ROOT + " --realm test --user user1" + " --config '" + configFile.getName() + "'").executeAsync();
            exe.waitForStdout("Enter password: ");
            exe.sendToStdin("userpass" + EOL);
            exe.waitForStdout("Enter truststore password: ");
            exe.sendToStdin("secret" + EOL);
            exe.waitCompletion();
            assertExitCodeAndStreamSizes(exe, 0, 2, 1);
            // configure truststore with password
            exe = execute("config truststore --config '" + configFile.getName() + "' --trustpass secret '" + truststore.getAbsolutePath() + "'");
            assertExitCodeAndStreamSizes(exe, 0, 0, 0);
            // perform authentication against server - asks for password, then for truststore password
            exe = KcRegExec.newBuilder().argsLine("config credentials --server " + oauth.AUTH_SERVER_ROOT + " --realm test --user user1" + " --config '" + configFile.getName() + "'").executeAsync();
            exe.waitForStdout("Enter password: ");
            exe.sendToStdin("userpass" + EOL);
            exe.waitCompletion();
            assertExitCodeAndStreamSizes(exe, 0, 1, 1);
        } else {
            System.out.println("TEST SKIPPED PARTIALLY - This test currently suffers from intermittent failures. Use -Dtest.intermittent=true to run it in full.");
        }
    }
    // configure truststore with password
    exe = execute("config truststore --trustpass secret '" + truststore.getAbsolutePath() + "'");
    assertExitCodeAndStreamSizes(exe, 0, 0, 0);
    // perform authentication against server - asks for password, then for truststore password
    exe = execute("config credentials --server " + serverUrl + " --realm test --user user1 --password userpass");
    assertExitCodeAndStreamSizes(exe, 0, 0, 1);
    exe = execute("config truststore --delete");
    assertExitCodeAndStreamSizes(exe, 0, 0, 0);
    exe = execute("config truststore --delete '" + truststore.getAbsolutePath() + "'");
    assertExitCodeAndStreamSizes(exe, 1, 0, 2);
    Assert.assertEquals("incompatible", "Option --delete is mutually exclusive with specifying a TRUSTSTORE", exe.stderrLines().get(0));
    Assert.assertEquals("try help", "Try '" + CMD + " help config truststore' for more information", exe.stderrLines().get(1));
    exe = execute("config truststore --delete --trustpass secret");
    assertExitCodeAndStreamSizes(exe, 1, 0, 2);
    Assert.assertEquals("no truststore error", "Options --trustpass and --delete are mutually exclusive", exe.stderrLines().get(0));
    Assert.assertEquals("try help", "Try '" + CMD + " help config truststore' for more information", exe.stderrLines().get(1));
    FileConfigHandler cfghandler = new FileConfigHandler();
    cfghandler.setConfigFile(DEFAULT_CONFIG_FILE_PATH);
    ConfigData config = cfghandler.loadConfig();
    Assert.assertNull("truststore null", config.getTruststore());
    Assert.assertNull("trustpass null", config.getTrustpass());
    // perform no-config CRUD test against ssl protected endpoint
    testCRUDWithOnTheFlyAuth(serverUrl, "--user user1 --password userpass", " --truststore '" + truststore.getAbsolutePath() + "' --trustpass secret", "Logging into " + serverUrl + " as user user1 of realm test");
}
Also used : FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) File(java.io.File) TempFileResource(org.keycloak.testsuite.util.TempFileResource) Test(org.junit.Test)

Example 5 with ConfigData

use of org.keycloak.client.registration.cli.config.ConfigData in project keycloak by keycloak.

the class DeleteCmd method execute.

@Override
public CommandResult execute(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
    try {
        if (printHelp()) {
            return help ? CommandResult.SUCCESS : CommandResult.FAILURE;
        }
        processGlobalOptions();
        if (args == null || args.isEmpty()) {
            throw new IllegalArgumentException("CLIENT not specified");
        }
        if (args.size() > 1) {
            throw new IllegalArgumentException("Invalid option: " + args.get(1));
        }
        String clientId = args.get(0);
        if (clientId.startsWith("-")) {
            warnfErr(ParseUtil.CLIENT_OPTION_WARN, clientId);
        }
        String regType = "default";
        ConfigData config = loadConfig();
        config = copyWithServerInfo(config);
        if (token == null) {
            // if registration access token is not set via -t, try use the one from configuration
            token = getRegistrationToken(config.sessionRealmConfigData(), clientId);
        }
        setupTruststore(config, commandInvocation);
        String auth = token;
        if (auth == null) {
            config = ensureAuthInfo(config, commandInvocation);
            config = copyWithServerInfo(config);
            if (credentialsAvailable(config)) {
                auth = ensureToken(config);
            }
        }
        auth = auth != null ? "Bearer " + auth : null;
        final String server = config.getServerUrl();
        final String realm = config.getRealm();
        doDelete(server + "/realms/" + realm + "/clients-registrations/" + regType + "/" + urlencode(clientId), auth);
        saveMergeConfig(cfg -> {
            cfg.ensureRealmConfigData(server, realm).getClients().remove(clientId);
        });
        return CommandResult.SUCCESS;
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException(e.getMessage() + suggestHelp(), e);
    } finally {
        commandInvocation.stop();
    }
}
Also used : ConfigData(org.keycloak.client.registration.cli.config.ConfigData)

Aggregations

ConfigData (org.keycloak.client.registration.cli.config.ConfigData)13 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)8 FileConfigHandler (org.keycloak.client.registration.cli.config.FileConfigHandler)7 RealmConfigData (org.keycloak.client.registration.cli.config.RealmConfigData)6 KcRegExec (org.keycloak.testsuite.cli.KcRegExec)6 Test (org.junit.Test)5 TempFileResource (org.keycloak.testsuite.util.TempFileResource)5 IOException (java.io.IOException)4 InputStream (java.io.InputStream)4 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)4 File (java.io.File)3 List (java.util.List)3 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 LinkedList (java.util.LinkedList)2 Arguments (org.jboss.aesh.cl.Arguments)2 CommandDefinition (org.jboss.aesh.cl.CommandDefinition)2 Option (org.jboss.aesh.cl.Option)2 CommandException (org.jboss.aesh.console.command.CommandException)2 CommandResult (org.jboss.aesh.console.command.CommandResult)2