Search in sources :

Example 1 with RealmConfigData

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

the class ConfigInitialTokenCmd method process.

public CommandResult process(CommandInvocation commandInvocation) throws CommandException, InterruptedException {
    List<String> args = new ArrayList<>();
    Iterator<String> it = parent.args.iterator();
    // skip the first argument 'initial-token'
    it.next();
    while (it.hasNext()) {
        String arg = it.next();
        switch(arg) {
            case "-d":
            case "--delete":
                {
                    delete = true;
                    break;
                }
            case "-k":
            case "--keep-domain":
                {
                    keepDomain = true;
                    break;
                }
            default:
                {
                    args.add(arg);
                }
        }
    }
    if (args.size() > 1) {
        throw new IllegalArgumentException("Invalid option: " + args.get(1));
    }
    String token = args.size() == 1 ? args.get(0) : null;
    if (realm == null) {
        throw new IllegalArgumentException("Realm not specified");
    }
    if (token != null && token.startsWith("-")) {
        warnfOut(ParseUtil.TOKEN_OPTION_WARN, token);
    }
    checkUnsupportedOptions("--client", clientId, "--user", user, "--password", password, "--secret", secret, "--keystore", keystore, "--storepass", storePass, "--keypass", keyPass, "--alias", alias, "--truststore", trustStore, "--trustpass", keyPass, "--no-config", booleanOptionForCheck(noconfig));
    if (!delete && token == null) {
        token = IoUtil.readSecret("Enter Initial Access Token: ", commandInvocation);
    }
    // now update the config
    processGlobalOptions();
    String initialToken = token;
    saveMergeConfig(config -> {
        if (!keepDomain && !delete) {
            config.setServerUrl(server);
            config.setRealm(realm);
        }
        if (delete) {
            RealmConfigData rdata = config.getRealmConfigData(server, realm);
            if (rdata != null) {
                rdata.setInitialToken(null);
            }
        } else {
            RealmConfigData rdata = config.ensureRealmConfigData(server, realm);
            rdata.setInitialToken(initialToken);
        }
    });
    return CommandResult.SUCCESS;
}
Also used : RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData) ArrayList(java.util.ArrayList)

Example 2 with RealmConfigData

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

the class AbstractAuthOptionsCmd method initConfigData.

private void initConfigData(ConfigData data) {
    if (server != null)
        data.setServerUrl(server);
    if (realm != null)
        data.setRealm(realm);
    if (trustStore != null)
        data.setTruststore(trustStore);
    RealmConfigData rdata = data.sessionRealmConfigData();
    if (clientId != null)
        rdata.setClientId(clientId);
    if (secret != null)
        rdata.setSecret(secret);
    String grantTypeForAuthentication = user == null ? OAuth2Constants.CLIENT_CREDENTIALS : OAuth2Constants.PASSWORD;
    rdata.setGrantTypeForAuthentication(grantTypeForAuthentication);
}
Also used : RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData)

Example 3 with RealmConfigData

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

the class AbstractRegCliTest method assertFieldsEqualWithExclusions.

void assertFieldsEqualWithExclusions(ConfigData config1, ConfigData config2, String... excluded) {
    HashSet<String> exclusions = new HashSet<>(Arrays.asList(excluded));
    if (!exclusions.contains("serverUrl")) {
        Assert.assertEquals("serverUrl", config1.getServerUrl(), config2.getServerUrl());
    }
    if (!exclusions.contains("realm")) {
        Assert.assertEquals("realm", config1.getRealm(), config2.getRealm());
    }
    if (!exclusions.contains("truststore")) {
        Assert.assertEquals("truststore", config1.getTruststore(), config2.getTruststore());
    }
    if (!exclusions.contains("endpoints")) {
        Map<String, Map<String, RealmConfigData>> endp1 = config1.getEndpoints();
        Map<String, Map<String, RealmConfigData>> endp2 = config2.getEndpoints();
        Iterator<Map.Entry<String, Map<String, RealmConfigData>>> it1 = endp1.entrySet().iterator();
        Iterator<Map.Entry<String, Map<String, RealmConfigData>>> it2 = endp2.entrySet().iterator();
        while (it1.hasNext()) {
            Map.Entry<String, Map<String, RealmConfigData>> ent1 = it1.next();
            Map.Entry<String, Map<String, RealmConfigData>> ent2 = it2.next();
            String serverUrl = ent1.getKey();
            String endpskey = "endpoints." + serverUrl;
            if (!exclusions.contains(endpskey)) {
                Assert.assertEquals(endpskey, ent1.getKey(), ent2.getKey());
                Map<String, RealmConfigData> realms1 = ent1.getValue();
                Map<String, RealmConfigData> realms2 = ent2.getValue();
                Iterator<Map.Entry<String, RealmConfigData>> rit1 = realms1.entrySet().iterator();
                Iterator<Map.Entry<String, RealmConfigData>> rit2 = realms2.entrySet().iterator();
                while (rit1.hasNext()) {
                    Map.Entry<String, RealmConfigData> rent1 = rit1.next();
                    Map.Entry<String, RealmConfigData> rent2 = rit2.next();
                    String realm = rent1.getKey();
                    String rkey = endpskey + "." + realm;
                    if (!exclusions.contains(endpskey)) {
                        Assert.assertEquals(rkey, rent1.getKey(), rent2.getKey());
                        RealmConfigData rdata1 = rent1.getValue();
                        RealmConfigData rdata2 = rent2.getValue();
                        assertFieldsEqualWithExclusions(serverUrl, realm, rdata1, rdata2, excluded);
                    }
                }
            }
        }
    }
}
Also used : RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 4 with RealmConfigData

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

the class AuthUtil method ensureToken.

public static String ensureToken(ConfigData config) {
    checkAuthInfo(config);
    RealmConfigData realmConfig = config.sessionRealmConfigData();
    long now = currentTimeMillis();
    // if it's less than 5s to expiry, renew it
    if (realmConfig.getExpiresAt() - now < 5000) {
        // if it's less than 5s to expiry, fail with credentials expired
        if (realmConfig.getRefreshExpiresAt() != null && realmConfig.getRefreshExpiresAt() - now < 5000) {
            throw new RuntimeException("Session has expired. Login again with '" + OsUtil.CMD + " config credentials'");
        }
        if (realmConfig.getSigExpiresAt() != null && realmConfig.getSigExpiresAt() - now < 5000) {
            throw new RuntimeException("Session has expired. Login again with '" + OsUtil.CMD + " config credentials'");
        }
        try {
            String authorization = null;
            StringBuilder body = new StringBuilder();
            if (realmConfig.getRefreshToken() != null) {
                body.append("grant_type=refresh_token").append("&refresh_token=").append(realmConfig.getRefreshToken());
            } else {
                body.append("grant_type=").append(realmConfig.getGrantTypeForAuthentication());
            }
            body.append("&client_id=").append(urlencode(realmConfig.getClientId()));
            if (realmConfig.getSigningToken() != null) {
                body.append("&client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer").append("&client_assertion=").append(realmConfig.getSigningToken());
            } else if (realmConfig.getSecret() != null) {
                authorization = BasicAuthHelper.createHeader(realmConfig.getClientId(), realmConfig.getSecret());
            }
            InputStream result = doPost(realmConfig.serverUrl() + "/realms/" + realmConfig.realm() + "/protocol/openid-connect/token", APPLICATION_FORM_URL_ENCODED, APPLICATION_JSON, body.toString(), authorization);
            AccessTokenResponse token = JsonSerialization.readValue(result, AccessTokenResponse.class);
            saveMergeConfig(cfg -> {
                RealmConfigData realmData = cfg.sessionRealmConfigData();
                realmData.setToken(token.getToken());
                realmData.setRefreshToken(token.getRefreshToken());
                realmData.setExpiresAt(currentTimeMillis() + token.getExpiresIn() * 1000);
                if (token.getRefreshToken() != null) {
                    realmData.setRefreshExpiresAt(currentTimeMillis() + token.getRefreshExpiresIn() * 1000);
                }
            });
            return token.getToken();
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Unexpected error", e);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read Refresh Token response", e);
        }
    }
    return realmConfig.getToken();
}
Also used : RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

Example 5 with RealmConfigData

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

the class ConfigUtil method saveTokens.

public static void saveTokens(AccessTokenResponse tokens, String endpoint, String realm, String clientId, String signKey, Long sigExpiresAt, String secret, String grantTypeForAuthentication) {
    handler.saveMergeConfig(config -> {
        config.setServerUrl(endpoint);
        config.setRealm(realm);
        RealmConfigData realmConfig = config.ensureRealmConfigData(endpoint, realm);
        realmConfig.setToken(tokens.getToken());
        realmConfig.setRefreshToken(tokens.getRefreshToken());
        realmConfig.setSigningToken(signKey);
        realmConfig.setSecret(secret);
        realmConfig.setExpiresAt(System.currentTimeMillis() + tokens.getExpiresIn() * 1000);
        if (realmConfig.getRefreshToken() != null) {
            realmConfig.setRefreshExpiresAt(tokens.getRefreshExpiresIn() == 0 ? Long.MAX_VALUE : System.currentTimeMillis() + tokens.getRefreshExpiresIn() * 1000);
        }
        realmConfig.setSigExpiresAt(sigExpiresAt);
        realmConfig.setClientId(clientId);
        realmConfig.setGrantTypeForAuthentication(grantTypeForAuthentication);
    });
}
Also used : RealmConfigData(org.keycloak.client.registration.cli.config.RealmConfigData)

Aggregations

RealmConfigData (org.keycloak.client.registration.cli.config.RealmConfigData)8 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 ConfigData (org.keycloak.client.registration.cli.config.ConfigData)2 FileConfigHandler (org.keycloak.client.registration.cli.config.FileConfigHandler)2 KcRegExec (org.keycloak.testsuite.cli.KcRegExec)2 File (java.io.File)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)1 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)1 AuthServerContainerExclude (org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude)1 TempFileResource (org.keycloak.testsuite.util.TempFileResource)1