Search in sources :

Example 6 with ConfigData

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

the class GetCmd 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);
        EndpointType regType = endpoint != null ? EndpointType.of(endpoint) : EndpointType.DEFAULT;
        if (clientId.startsWith("-")) {
            warnfErr(ParseUtil.CLIENT_OPTION_WARN, clientId);
        }
        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();
        InputStream response = doGet(server + "/realms/" + realm + "/clients-registrations/" + regType.getEndpoint() + "/" + urlencode(clientId), APPLICATION_JSON, auth);
        try {
            String json = readFully(response);
            Object result = null;
            switch(regType) {
                case DEFAULT:
                    {
                        ClientRepresentation client = JsonSerialization.readValue(json, ClientRepresentation.class);
                        result = client;
                        saveMergeConfig(cfg -> {
                            setRegistrationToken(cfg.ensureRealmConfigData(server, realm), client.getClientId(), client.getRegistrationAccessToken());
                        });
                        break;
                    }
                case OIDC:
                    {
                        OIDCClientRepresentation client = JsonSerialization.readValue(json, OIDCClientRepresentation.class);
                        result = client;
                        saveMergeConfig(cfg -> {
                            setRegistrationToken(cfg.ensureRealmConfigData(server, realm), client.getClientId(), client.getRegistrationAccessToken());
                        });
                        break;
                    }
                case INSTALL:
                    {
                        result = JsonSerialization.readValue(json, AdapterConfig.class);
                        break;
                    }
                case SAML2:
                    {
                        break;
                    }
                default:
                    {
                        throw new RuntimeException("Unexpected type: " + regType);
                    }
            }
            if (!compressed && result != null) {
                json = JsonSerialization.writeValueAsPrettyString(result);
            }
            printOut(json);
        // } catch (UnrecognizedPropertyException e) {
        // throw new RuntimeException("Failed to parse returned JSON - " + e.getMessage(), e);
        } 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 : APPLICATION_JSON(org.keycloak.client.registration.cli.util.HttpUtil.APPLICATION_JSON) CMD(org.keycloak.client.registration.cli.util.OsUtil.CMD) CommandResult(org.jboss.aesh.console.command.CommandResult) CommandDefinition(org.jboss.aesh.cl.CommandDefinition) AuthUtil.ensureToken(org.keycloak.client.registration.cli.util.AuthUtil.ensureToken) ConfigUtil.setRegistrationToken(org.keycloak.client.registration.cli.util.ConfigUtil.setRegistrationToken) IoUtil.printOut(org.keycloak.client.registration.cli.util.IoUtil.printOut) ConfigUtil.saveMergeConfig(org.keycloak.client.registration.cli.util.ConfigUtil.saveMergeConfig) CommandInvocation(org.jboss.aesh.console.command.invocation.CommandInvocation) HttpUtil.doGet(org.keycloak.client.registration.cli.util.HttpUtil.doGet) ParseUtil(org.keycloak.client.registration.cli.util.ParseUtil) EndpointType(org.keycloak.client.registration.cli.common.EndpointType) ConfigUtil.getRegistrationToken(org.keycloak.client.registration.cli.util.ConfigUtil.getRegistrationToken) IoUtil.warnfErr(org.keycloak.client.registration.cli.util.IoUtil.warnfErr) EOL(org.keycloak.client.registration.cli.util.OsUtil.EOL) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) PrintWriter(java.io.PrintWriter) HttpUtil.urlencode(org.keycloak.client.registration.cli.util.HttpUtil.urlencode) Arguments(org.jboss.aesh.cl.Arguments) StringWriter(java.io.StringWriter) DEFAULT_CONFIG_FILE_STRING(org.keycloak.client.registration.cli.util.ConfigUtil.DEFAULT_CONFIG_FILE_STRING) IOException(java.io.IOException) ConfigUtil.loadConfig(org.keycloak.client.registration.cli.util.ConfigUtil.loadConfig) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) JsonSerialization(org.keycloak.util.JsonSerialization) ConfigUtil.credentialsAvailable(org.keycloak.client.registration.cli.util.ConfigUtil.credentialsAvailable) PROMPT(org.keycloak.client.registration.cli.util.OsUtil.PROMPT) Option(org.jboss.aesh.cl.Option) List(java.util.List) CommandException(org.jboss.aesh.console.command.CommandException) IoUtil.readFully(org.keycloak.client.registration.cli.util.IoUtil.readFully) AdapterConfig(org.keycloak.representations.adapters.config.AdapterConfig) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) InputStream(java.io.InputStream) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) InputStream(java.io.InputStream) EndpointType(org.keycloak.client.registration.cli.common.EndpointType) IOException(java.io.IOException) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation)

Example 7 with ConfigData

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

the class UpdateTokenCmd 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");
        }
        String clientId = args.get(0);
        if (clientId.startsWith("-")) {
            warnfOut(ParseUtil.CLIENT_OPTION_WARN, clientId);
        }
        ConfigData config = loadConfig();
        config = copyWithServerInfo(config);
        setupTruststore(config, commandInvocation);
        config = ensureAuthInfo(config, commandInvocation);
        String auth = ensureToken(config);
        String cid = null;
        final String server = config.getServerUrl();
        final String realm = config.getRealm();
        // first we need to get id of the client with client_id == clientId
        InputStream response = doGet(server + "/admin/realms/" + realm + "/clients", APPLICATION_JSON, "Bearer " + auth);
        try {
            List<ClientRepresentation> clients = JsonSerialization.readValue(response, new TypeReference<List<ClientRepresentation>>() {
            });
            for (ClientRepresentation client : clients) {
                if (clientId.equals(client.getClientId())) {
                    cid = client.getId();
                    break;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to process response from server", e);
        }
        if (cid == null) {
            throw new RuntimeException("No client found for: " + clientId);
        }
        response = doPost(server + "/admin/realms/" + realm + "/clients/" + cid + "/registration-access-token", APPLICATION_JSON, APPLICATION_JSON, null, "Bearer " + auth);
        try {
            ClientRepresentation client = JsonSerialization.readValue(response, ClientRepresentation.class);
            if (noconfig) {
                // output to stdout
                printOut(client.getRegistrationAccessToken());
            } else {
                saveMergeConfig(cfg -> {
                    setRegistrationToken(cfg.ensureRealmConfigData(server, realm), client.getClientId(), client.getRegistrationAccessToken());
                });
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to process response from server", e);
        }
        // System.out.println("Token updated for client " + 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) InputStream(java.io.InputStream) List(java.util.List) IOException(java.io.IOException) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation)

Example 8 with ConfigData

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

the class AbstractAuthOptionsCmd method copyWithServerInfo.

protected ConfigData copyWithServerInfo(ConfigData config) {
    ConfigData result = config.deepcopy();
    if (server != null) {
        result.setServerUrl(server);
    }
    if (realm != null) {
        result.setRealm(realm);
    }
    checkServerInfo(result);
    return result;
}
Also used : RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData) ConfigData(org.keycloak.client.registration.cli.config.ConfigData)

Example 9 with ConfigData

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

the class CreateCmd 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();
        if (args != null) {
            Iterator<String> it = args.iterator();
            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;
                        }
                    default:
                        {
                            throw new IllegalArgumentException("Unsupported option: " + option);
                        }
                }
            }
        }
        if (file == null && attrs.size() == 0) {
            throw new IllegalArgumentException("No file nor attribute values specified");
        }
        if (outputClient && returnClientId) {
            throw new IllegalArgumentException("Options -o and -i are mutually exclusive");
        }
        // if --token is specified read it
        if ("-".equals(token)) {
            token = readSecret("Enter Initial Access Token: ", commandInvocation);
        }
        CmdStdinContext ctx = new CmdStdinContext();
        if (file != null) {
            ctx = parseFileOrStdin(file, regType);
        }
        if (ctx.getEndpointType() == null) {
            regType = regType != null ? regType : DEFAULT;
            ctx.setEndpointType(regType);
        } else if (regType != null && ctx.getEndpointType() != regType) {
            throw new RuntimeException("Requested endpoint type not compatible with detected configuration format: " + ctx.getEndpointType());
        }
        if (attrs.size() > 0) {
            ctx = mergeAttributes(ctx, attrs);
        }
        String contentType = getExpectedContentType(ctx.getEndpointType());
        ConfigData config = loadConfig();
        config = copyWithServerInfo(config);
        if (token == null) {
            // if initial token is not set, try use the one from configuration
            token = config.sessionRealmConfigData().getInitialToken();
        }
        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();
        InputStream response = doPost(server + "/realms/" + realm + "/clients-registrations/" + ctx.getEndpointType().getEndpoint(), contentType, HttpUtil.APPLICATION_JSON, ctx.getContent(), auth);
        try {
            if (ctx.getEndpointType() == DEFAULT || ctx.getEndpointType() == SAML2) {
                ClientRepresentation client = JsonSerialization.readValue(response, ClientRepresentation.class);
                outputResult(client.getClientId(), client);
                saveMergeConfig(cfg -> {
                    setRegistrationToken(cfg.ensureRealmConfigData(server, realm), client.getClientId(), client.getRegistrationAccessToken());
                });
            } else if (ctx.getEndpointType() == OIDC) {
                OIDCClientRepresentation client = JsonSerialization.readValue(response, OIDCClientRepresentation.class);
                outputResult(client.getClientId(), client);
                saveMergeConfig(cfg -> {
                    setRegistrationToken(cfg.ensureRealmConfigData(server, realm), client.getClientId(), client.getRegistrationAccessToken());
                });
            } else {
                printOut("Response from server: " + readFully(response));
            }
        } catch (UnrecognizedPropertyException e) {
            throw new RuntimeException("Failed to process HTTP reponse - " + e.getMessage(), e);
        } 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 : UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) DEFAULT(org.keycloak.client.registration.cli.common.EndpointType.DEFAULT) CMD(org.keycloak.client.registration.cli.util.OsUtil.CMD) OIDC(org.keycloak.client.registration.cli.common.EndpointType.OIDC) ParseUtil.parseKeyVal(org.keycloak.client.registration.cli.util.ParseUtil.parseKeyVal) CommandResult(org.jboss.aesh.console.command.CommandResult) CommandDefinition(org.jboss.aesh.cl.CommandDefinition) AuthUtil.ensureToken(org.keycloak.client.registration.cli.util.AuthUtil.ensureToken) ConfigUtil.setRegistrationToken(org.keycloak.client.registration.cli.util.ConfigUtil.setRegistrationToken) IoUtil.printOut(org.keycloak.client.registration.cli.util.IoUtil.printOut) ConfigUtil.saveMergeConfig(org.keycloak.client.registration.cli.util.ConfigUtil.saveMergeConfig) CommandInvocation(org.jboss.aesh.console.command.invocation.CommandInvocation) EndpointType(org.keycloak.client.registration.cli.common.EndpointType) LinkedList(java.util.LinkedList) ParseUtil.parseFileOrStdin(org.keycloak.client.registration.cli.util.ParseUtil.parseFileOrStdin) CmdStdinContext(org.keycloak.client.registration.cli.common.CmdStdinContext) EOL(org.keycloak.client.registration.cli.util.OsUtil.EOL) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) PrintWriter(java.io.PrintWriter) IoUtil.readSecret(org.keycloak.client.registration.cli.util.IoUtil.readSecret) Iterator(java.util.Iterator) ParseUtil.mergeAttributes(org.keycloak.client.registration.cli.util.ParseUtil.mergeAttributes) Arguments(org.jboss.aesh.cl.Arguments) StringWriter(java.io.StringWriter) DEFAULT_CONFIG_FILE_STRING(org.keycloak.client.registration.cli.util.ConfigUtil.DEFAULT_CONFIG_FILE_STRING) SAML2(org.keycloak.client.registration.cli.common.EndpointType.SAML2) IOException(java.io.IOException) ConfigUtil.loadConfig(org.keycloak.client.registration.cli.util.ConfigUtil.loadConfig) HttpUtil(org.keycloak.client.registration.cli.util.HttpUtil) HttpUtil.getExpectedContentType(org.keycloak.client.registration.cli.util.HttpUtil.getExpectedContentType) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) JsonSerialization(org.keycloak.util.JsonSerialization) ConfigUtil.credentialsAvailable(org.keycloak.client.registration.cli.util.ConfigUtil.credentialsAvailable) PROMPT(org.keycloak.client.registration.cli.util.OsUtil.PROMPT) Option(org.jboss.aesh.cl.Option) List(java.util.List) AttributeOperation(org.keycloak.client.registration.cli.common.AttributeOperation) CommandException(org.jboss.aesh.console.command.CommandException) EndpointTypeConverter(org.keycloak.client.registration.cli.aesh.EndpointTypeConverter) IoUtil.readFully(org.keycloak.client.registration.cli.util.IoUtil.readFully) SET(org.keycloak.client.registration.cli.common.AttributeOperation.Type.SET) OS_ARCH(org.keycloak.client.registration.cli.util.OsUtil.OS_ARCH) Command(org.jboss.aesh.console.command.Command) IoUtil.printErr(org.keycloak.client.registration.cli.util.IoUtil.printErr) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) InputStream(java.io.InputStream) HttpUtil.doPost(org.keycloak.client.registration.cli.util.HttpUtil.doPost) AttributeOperation(org.keycloak.client.registration.cli.common.AttributeOperation) InputStream(java.io.InputStream) UnrecognizedPropertyException(com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException) IOException(java.io.IOException) 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 10 with ConfigData

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

the class KcRegUpdateTokenTest method testUpdateToken.

@Test
public void testUpdateToken() throws IOException {
    FileConfigHandler handler = initCustomConfigFile();
    ConfigUtil.setHandler(handler);
    try (TempFileResource configFile = new TempFileResource(handler.getConfigFile())) {
        KcRegExec exe = execute("config credentials --config '" + configFile.getName() + "' --server " + serverUrl + " --realm master --user admin --password admin");
        assertExitCodeAndStreamSizes(exe, 0, 0, 1);
        // read current registration access token
        ConfigData data = ConfigUtil.loadConfig();
        RealmConfigData rdata = data.getRealmConfigData(serverUrl, "test");
        Assert.assertNull("realm info set", rdata);
        // update registration access token
        exe = execute("update-token --config '" + configFile.getName() + "' reg-cli-secret-direct  --server " + serverUrl + " --realm test --user user1 --password userpass");
        assertExitCodeAndStreamSizes(exe, 0, 0, 1);
        // read current registration token
        data = ConfigUtil.loadConfig();
        rdata = data.getRealmConfigData(serverUrl, "test");
        Assert.assertEquals("current session realm unchanged", "master", data.getRealm());
        Assert.assertNotNull("realm info set", rdata);
        Assert.assertNull("on the fly login was transient", rdata.getToken());
        Assert.assertNotNull("client info has registration access token", rdata.getClients().get("reg-cli-secret-direct"));
        // use --no-config and on-the-fly auth
        exe = execute("update-token reg-cli-secret-direct --no-config --server " + serverUrl + " --realm test --user user1 --password userpass");
        assertExitCodeAndStreamSizes(exe, 0, 1, 1);
        // save the token
        String token = exe.stdoutLines().get(0);
        // test that the token works
        exe = execute("get reg-cli-secret-direct --no-config --server " + serverUrl + " --realm test -t " + token);
        assertExitCodeAndStdErrSize(exe, 0, 0);
        ClientRepresentation client = JsonSerialization.readValue(exe.stdout(), ClientRepresentation.class);
        Assert.assertEquals("client representation returned", "reg-cli-secret-direct", client.getClientId());
    }
}
Also used : RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData) FileConfigHandler(org.keycloak.client.registration.cli.config.FileConfigHandler) RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData) ConfigData(org.keycloak.client.registration.cli.config.ConfigData) KcRegExec(org.keycloak.testsuite.cli.KcRegExec) TempFileResource(org.keycloak.testsuite.util.TempFileResource) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) Test(org.junit.Test)

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