org.keycloak.common.util.MultivaluedHashMap Java Examples

The following examples show how to use org.keycloak.common.util.MultivaluedHashMap. 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: GeneratedEcdsaKeyProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean createFallbackKeys(KeycloakSession session, KeyUse keyUse, String algorithm) {
    if (keyUse.equals(KeyUse.SIG) && (algorithm.equals(Algorithm.ES256) || algorithm.equals(Algorithm.ES384) || algorithm.equals(Algorithm.ES512))) {
        RealmModel realm = session.getContext().getRealm();

        ComponentModel generated = new ComponentModel();
        generated.setName("fallback-" + algorithm);
        generated.setParentId(realm.getId());
        generated.setProviderId(ID);
        generated.setProviderType(KeyProvider.class.getName());

        MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
        config.putSingle(Attributes.PRIORITY_KEY, "-100");
        config.putSingle(ECDSA_ELLIPTIC_CURVE_KEY, convertAlgorithmToECDomainParmNistRep(algorithm));
        generated.setConfig(config);

        realm.addComponentModel(generated);

        return true;
    } else {
        return false;
    }
}
 
Example #2
Source File: GeneratedEcdsaKeyProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void unsupportedEc(String ecInNistRep) {
    long priority = System.currentTimeMillis();

    ComponentRepresentation rep = createRep("valid", GeneratedEcdsaKeyProviderFactory.ID);
    rep.setConfig(new MultivaluedHashMap<>());
    rep.getConfig().putSingle("priority", Long.toString(priority));
    rep.getConfig().putSingle(ECDSA_ELLIPTIC_CURVE_KEY, ecInNistRep);
    boolean isEcAccepted = true;

    Response response = null;
    try {
        response = adminClient.realm(TEST_REALM_NAME).components().add(rep);
        String id = ApiUtil.getCreatedId(response);
        getCleanup().addComponentId(id);
        response.close();
    } catch (WebApplicationException e) {
        isEcAccepted = false;
    } finally {
        response.close();
    }
    assertEquals(isEcAccepted, false);
}
 
Example #3
Source File: GeneratedAesKeyProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean createFallbackKeys(KeycloakSession session, KeyUse keyUse, String algorithm) {
    if (keyUse.equals(KeyUse.ENC) && algorithm.equals(Algorithm.AES)) {
        RealmModel realm = session.getContext().getRealm();

        ComponentModel generated = new ComponentModel();
        generated.setName("fallback-" + algorithm);
        generated.setParentId(realm.getId());
        generated.setProviderId(ID);
        generated.setProviderType(KeyProvider.class.getName());

        MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
        config.putSingle(Attributes.PRIORITY_KEY, "-100");
        generated.setConfig(config);

        realm.addComponentModel(generated);

        return true;
    } else {
        return false;
    }
}
 
Example #4
Source File: JettyAdapterSessionStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void saveRequest() {
    // remember the current URI
    HttpSession session = myRequest.getSession();
    synchronized (session) {
        // But only if it is not set already, or we save every uri that leads to a login form redirect
        if (session.getAttribute(FormAuthenticator.__J_URI) == null) {
            StringBuffer buf = myRequest.getRequestURL();
            if (myRequest.getQueryString() != null)
                buf.append("?").append(myRequest.getQueryString());
            session.setAttribute(FormAuthenticator.__J_URI, buf.toString());
            session.setAttribute(JettyHttpFacade.__J_METHOD, myRequest.getMethod());

            if ("application/x-www-form-urlencoded".equals(myRequest.getContentType()) && "POST".equalsIgnoreCase(myRequest.getMethod())) {
                MultiMap<String> formParameters = extractFormParameters(myRequest);
                MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
                for (String key : formParameters.keySet()) {
                    for (Object value : formParameters.getValues(key)) {
                        map.add(key, (String) value);
                    }
                }
                session.setAttribute(CACHED_FORM_PARAMETERS, map);
            }
        }
    }
}
 
Example #5
Source File: ImportComponentsIT.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
@Test
@Order(2)
void shouldUpdateComponentsConfig() {
    doImport("01_update_realm__change_component_config.json");

    RealmRepresentation createdRealm = keycloakProvider.get().realm(REALM_NAME).toRepresentation();

    assertThat(createdRealm.getRealm(), is(REALM_NAME));
    assertThat(createdRealm.isEnabled(), is(true));

    ComponentRepresentation rsaComponent = getComponent(
            "org.keycloak.keys.KeyProvider",
            "rsa-generated"
    );

    assertThat(rsaComponent.getName(), is("rsa-generated"));
    assertThat(rsaComponent.getProviderId(), is("rsa-generated"));
    MultivaluedHashMap<String, String> componentConfig = rsaComponent.getConfig();

    List<String> keySize = componentConfig.get("keySize");
    assertThat(keySize, hasSize(1));
    assertThat(keySize.get(0), is("2048"));
}
 
Example #6
Source File: ImportComponentsIT.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
@Test
@Order(1)
void shouldCreateRealmWithComponent() {
    doImport("00_create_realm_with_component.json");

    RealmRepresentation createdRealm = keycloakProvider.get().realm(REALM_NAME).toRepresentation();

    assertThat(createdRealm.getRealm(), is(REALM_NAME));
    assertThat(createdRealm.isEnabled(), is(true));

    ComponentRepresentation rsaComponent = getComponent(
            "org.keycloak.keys.KeyProvider",
            "rsa-generated"
    );

    assertThat(rsaComponent.getName(), is("rsa-generated"));
    assertThat(rsaComponent.getProviderId(), is("rsa-generated"));
    MultivaluedHashMap<String, String> componentConfig = rsaComponent.getConfig();

    List<String> keySize = componentConfig.get("keySize");
    assertThat(keySize, hasSize(1));
    assertThat(keySize.get(0), is("4096"));
}
 
Example #7
Source File: JettyAdapterSessionStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void saveRequest() {
    // remember the current URI
    HttpSession session = myRequest.getSession();
    synchronized (session) {
        // But only if it is not set already, or we save every uri that leads to a login form redirect
        if (session.getAttribute(FormAuthenticator.__J_URI) == null) {
            StringBuffer buf = myRequest.getRequestURL();
            if (myRequest.getQueryString() != null)
                buf.append("?").append(myRequest.getQueryString());
            session.setAttribute(FormAuthenticator.__J_URI, buf.toString());
            session.setAttribute(JettyHttpFacade.__J_METHOD, myRequest.getMethod());

            if ("application/x-www-form-urlencoded".equals(myRequest.getContentType()) && "POST".equalsIgnoreCase(myRequest.getMethod())) {
                MultiMap<String> formParameters = extractFormParameters(myRequest);
                MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
                for (String key : formParameters.keySet()) {
                    for (Object value : formParameters.getValues(key)) {
                        map.add(key, (String) value);
                    }
                }
                session.setAttribute(CACHED_FORM_PARAMETERS, map);
            }
        }
    }
}
 
Example #8
Source File: StateService.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
private void setComponents(RealmImport realmImport) {
    MultivaluedHashMap<String, ComponentExportRepresentation> components = realmImport.getComponents();
    if (components == null) return;

    List<Object> state = new ArrayList<>();

    for (Map.Entry<String, List<ComponentExportRepresentation>> entry : components.entrySet()) {
        for (ComponentExportRepresentation component : entry.getValue()) {
            String componentName = component.getName();
            state.add(componentName);

            setSubComponents(component);
        }
    }

    stateRepository.setState("components", state);
}
 
Example #9
Source File: ComponentImportService.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
private boolean checkIfComponentMissingImport(ComponentRepresentation existingComponent, MultivaluedHashMap<String, ComponentExportRepresentation> componentsToImport) {
    String existingComponentProviderType = existingComponent.getProviderType();
    String existingComponentName = existingComponent.getName();

    for (Map.Entry<String, List<ComponentExportRepresentation>> entry : componentsToImport.entrySet()) {
        String providerType = entry.getKey();
        List<ComponentExportRepresentation> componentToImport = entry.getValue();

        if (!existingComponentProviderType.equals(providerType)) {
            continue;
        }

        boolean isInImport = componentToImport.stream().anyMatch(component -> existingComponentName.equals(component.getName()));

        if (isInImport) {
            return false;
        }
    }

    return true;
}
 
Example #10
Source File: ComponentImportService.java    From keycloak-config-cli with Apache License 2.0 6 votes vote down vote up
private void updateComponent(
        String realm,
        String providerType,
        ComponentExportRepresentation componentToImport,
        ComponentRepresentation patchedComponent
) {
    logger.debug("Updating component: {}/{}", patchedComponent.getProviderType(), componentToImport.getName());

    if (patchedComponent.getProviderType() == null) {
        patchedComponent.setProviderType(providerType);
    }

    componentRepository.update(realm, patchedComponent);

    MultivaluedHashMap<String, ComponentExportRepresentation> subComponents = componentToImport.getSubComponents();

    if (!subComponents.isEmpty()) {
        createOrUpdateSubComponents(realm, subComponents, patchedComponent.getId());
    }

    if (importConfigProperties.getManaged().getSubComponent() == ImportManagedPropertiesValues.FULL) {
        deleteComponentsMissingInImport(realm, subComponents, patchedComponent);
    }
}
 
Example #11
Source File: DefaultKeyProviders.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void createProviders(RealmModel realm, String privateKeyPem, String certificatePem) {
    if (!hasProvider(realm, "rsa")) {
        ComponentModel rsa = new ComponentModel();
        rsa.setName("rsa");
        rsa.setParentId(realm.getId());
        rsa.setProviderId("rsa");
        rsa.setProviderType(KeyProvider.class.getName());

        MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
        config.putSingle("priority", "100");
        config.putSingle("privateKey", privateKeyPem);
        if (certificatePem != null) {
            config.putSingle("certificate", certificatePem);
        }
        rsa.setConfig(config);

        realm.addComponentModel(rsa);
    }

    createSecretProvider(realm);
    createAesProvider(realm);
}
 
Example #12
Source File: JettyAdapterSessionStore.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void saveRequest() {
    // remember the current URI
    HttpSession session = myRequest.getSession();
    synchronized (session) {
        // But only if it is not set already, or we save every uri that leads to a login form redirect
        if (session.getAttribute(FormAuthenticator.__J_URI) == null) {
            StringBuffer buf = myRequest.getRequestURL();
            if (myRequest.getQueryString() != null)
                buf.append("?").append(myRequest.getQueryString());
            session.setAttribute(FormAuthenticator.__J_URI, buf.toString());
            session.setAttribute(JettyHttpFacade.__J_METHOD, myRequest.getMethod());

            if ("application/x-www-form-urlencoded".equals(myRequest.getContentType()) && "POST".equalsIgnoreCase(myRequest.getMethod())) {
                MultiMap<String> formParameters = extractFormParameters(myRequest);
                MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
                for (String key : formParameters.keySet()) {
                    for (Object value : formParameters.getValues(key)) {
                        map.add(key, (String) value);
                    }
                }
                session.setAttribute(CACHED_FORM_PARAMETERS, map);
            }
        }
    }
}
 
Example #13
Source File: SamlDescriptorIDPKeysExtractor.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public MultivaluedHashMap<String, KeyInfo> parse(InputStream stream) throws ParsingException {
    MultivaluedHashMap<String, KeyInfo> res = new MultivaluedHashMap<>();

    try {
        DocumentBuilder builder = DocumentUtil.getDocumentBuilder();
        Document doc = builder.parse(stream);

        XPathExpression expr = xpath.compile("//m:EntityDescriptor/m:IDPSSODescriptor/m:KeyDescriptor");
        NodeList keyDescriptors = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < keyDescriptors.getLength(); i ++) {
            Node keyDescriptor = keyDescriptors.item(i);
            Element keyDescriptorEl = (Element) keyDescriptor;
            KeyInfo ki = processKeyDescriptor(keyDescriptorEl);
            if (ki != null) {
                String use = keyDescriptorEl.getAttribute(JBossSAMLConstants.USE.get());
                res.add(use, ki);
            }
        }
    } catch (SAXException | IOException | ParserConfigurationException | MarshalException | XPathExpressionException e) {
        throw new ParsingException("Error parsing SAML descriptor", e);
    }

    return res;
}
 
Example #14
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected static void importComponents(RealmModel newRealm, MultivaluedHashMap<String, ComponentExportRepresentation> components, String parentId) {
    for (Map.Entry<String, List<ComponentExportRepresentation>> entry : components.entrySet()) {
        String providerType = entry.getKey();
        for (ComponentExportRepresentation compRep : entry.getValue()) {
            ComponentModel component = new ComponentModel();
            component.setId(compRep.getId());
            component.setName(compRep.getName());
            component.setConfig(compRep.getConfig());
            component.setProviderType(providerType);
            component.setProviderId(compRep.getProviderId());
            component.setSubType(compRep.getSubType());
            component.setParentId(parentId);
            component = newRealm.importComponentModel(component);
            if (compRep.getSubComponents() != null) {
                importComponents(newRealm, compRep.getSubComponents(), component.getId());
            }
        }
    }
}
 
Example #15
Source File: UserStorageRestTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ComponentRepresentation createBasicLDAPProviderRep() {
    ComponentRepresentation ldapRep = new ComponentRepresentation();
    ldapRep.setName("ldap2");
    ldapRep.setProviderId("ldap");
    ldapRep.setProviderType(UserStorageProvider.class.getName());
    ldapRep.setConfig(new MultivaluedHashMap<>());
    ldapRep.getConfig().putSingle("priority", Integer.toString(2));
    return ldapRep;
}
 
Example #16
Source File: ModelToRepresentation.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ComponentRepresentation toRepresentationWithoutConfig(ComponentModel component) {
    ComponentRepresentation rep = new ComponentRepresentation();
    rep.setId(component.getId());
    rep.setName(component.getName());
    rep.setProviderId(component.getProviderId());
    rep.setProviderType(component.getProviderType());
    rep.setSubType(component.getSubType());
    rep.setParentId(component.getParentId());
    rep.setConfig(new MultivaluedHashMap<>(component.getConfig()));
    return rep;
}
 
Example #17
Source File: Assert.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Assert all the fields from map available. Array "expected" contains pairs when first value from pair is expected key
 * and second is the expected value from the map for target key.
 *
 * Example config = {"key1" -> "value1" , "key2" -> "value2" }
 * then assertMap(config, "key1", "value1", "key2", "value2" will return true
 *
 */
public static void assertMultivaluedMap(MultivaluedHashMap<String, String> config, String... expected) {
    if (expected == null) {
        expected = new String[] {};
    }

    for (int i=0 ; i<expected.length ; i+=2) {
        String key = expected[i];
        String value = expected[i+1];
        Assert.assertEquals(value, config.getFirst(key));
    }
}
 
Example #18
Source File: LDAPMappersComparatorTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompareWithCNUsername() {
    MultivaluedHashMap<String, String> cfg = new MultivaluedHashMap<>();
    cfg.add(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, LDAPConstants.CN);
    LDAPConfig config = new LDAPConfig(cfg);

    List<ComponentModel> sorted = LDAPMappersComparator.sortAsc(config, getMappers());
    assertOrder(sorted, "username-cn", "sAMAccountName", "first name", "full name");

    sorted = LDAPMappersComparator.sortDesc(config, getMappers());
    assertOrder(sorted, "full name", "first name", "sAMAccountName", "username-cn");
}
 
Example #19
Source File: CredentialModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated Recommended to use {@link #getCredentialData()} instead and use the subtype of CredentialData specific to your credential
 */
@Deprecated
@JsonIgnore
public MultivaluedHashMap<String, String> getConfig() {
    Map<String, Object> credentialData = readMapFromJson(false);
    if (credentialData == null) {
        return null;
    }

    Object obj = credentialData.get("config");
    return obj == null ? null : new MultivaluedHashMap<>((Map)obj);
}
 
Example #20
Source File: GeneratedRsaKeyProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void largeKeysize() throws Exception {
    long priority = System.currentTimeMillis();

    ComponentRepresentation rep = createRep("valid", GeneratedRsaKeyProviderFactory.ID);
    rep.setConfig(new MultivaluedHashMap<>());
    rep.getConfig().putSingle("priority", Long.toString(priority));
    rep.getConfig().putSingle("keySize", "4096");

    Response response = adminClient.realm("test").components().add(rep);
    String id = ApiUtil.getCreatedId(response);
    getCleanup().addComponentId(id);
    response.close();

    ComponentRepresentation createdRep = adminClient.realm("test").components().component(id).toRepresentation();
    assertEquals(2, createdRep.getConfig().size());
    assertEquals("4096", createdRep.getConfig().getFirst("keySize"));

    KeysMetadataRepresentation keys = adminClient.realm("test").keys().getKeyMetadata();

    KeysMetadataRepresentation.KeyMetadataRepresentation key = keys.getKeys().get(0);

    assertEquals(id, key.getProviderId());
    assertEquals(AlgorithmType.RSA.name(), key.getType());
    assertEquals(priority, key.getProviderPriority());
    assertEquals(4096, ((RSAPublicKey) PemUtils.decodePublicKey(keys.getKeys().get(0).getPublicKey())).getModulus().bitLength());
}
 
Example #21
Source File: JettyAdapterSessionStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean restoreRequest() {
    HttpSession session = myRequest.getSession(false);
    if (session == null) return false;
    synchronized (session) {
        String j_uri = (String) session.getAttribute(FormAuthenticator.__J_URI);
        if (j_uri != null) {
            // check if the request is for the same url as the original and restore
            // params if it was a post
            StringBuffer buf = myRequest.getRequestURL();
            if (myRequest.getQueryString() != null)
                buf.append("?").append(myRequest.getQueryString());
            if (j_uri.equals(buf.toString())) {
                String method = (String)session.getAttribute(JettyHttpFacade.__J_METHOD);
                myRequest.setMethod(HttpMethod.valueOf(method.toUpperCase()), method);
                MultivaluedHashMap<String, String> j_post = (MultivaluedHashMap<String, String>) session.getAttribute(CACHED_FORM_PARAMETERS);
                if (j_post != null) {
                    myRequest.setContentType("application/x-www-form-urlencoded");
                    MultiMap<String> map = new MultiMap<String>();
                    for (String key : j_post.keySet()) {
                        for (String val : j_post.getList(key)) {
                            map.add(key, val);
                        }
                    }
                    restoreFormParameters(map, myRequest);
                }
                session.removeAttribute(FormAuthenticator.__J_URI);
                session.removeAttribute(JettyHttpFacade.__J_METHOD);
                session.removeAttribute(FormAuthenticator.__J_POST);
            }
            return true;
        }
    }
    return false;
}
 
Example #22
Source File: AbstractUserStorageDirtyDeletionTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected ComponentRepresentation getFederationProvider(UserStorageProvider.EditMode editMode, boolean importEnabled) {
    ComponentRepresentation provider = new ComponentRepresentation();

    provider.setName(getClass().getSimpleName());
    provider.setProviderId(UserMapStorageFactory.PROVIDER_ID);
    provider.setProviderType(UserStorageProvider.class.getName());
    provider.setConfig(new MultivaluedHashMap<>());
    provider.getConfig().putSingle("priority", Integer.toString(0));
    provider.getConfig().putSingle(LDAPConstants.EDIT_MODE, editMode.name());
    provider.getConfig().putSingle(IMPORT_ENABLED, Boolean.toString(importEnabled));

    return provider;
}
 
Example #23
Source File: GeneratedHmacKeyProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected ComponentRepresentation createRep(String name, String providerId) {
    ComponentRepresentation rep = new ComponentRepresentation();
    rep.setName(name);
    rep.setParentId("test");
    rep.setProviderId(providerId);
    rep.setProviderType(KeyProvider.class.getName());
    rep.setConfig(new MultivaluedHashMap<>());
    return rep;
}
 
Example #24
Source File: UserStorageTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Before
public void addProvidersBeforeTest() throws URISyntaxException, IOException {
    ComponentRepresentation memProvider = new ComponentRepresentation();
    memProvider.setName("memory");
    memProvider.setProviderId(UserMapStorageFactory.PROVIDER_ID);
    memProvider.setProviderType(UserStorageProvider.class.getName());
    memProvider.setConfig(new MultivaluedHashMap<>());
    memProvider.getConfig().putSingle("priority", Integer.toString(0));
    memProvider.getConfig().putSingle(IMPORT_ENABLED, Boolean.toString(false));

    memProviderId = addComponent(memProvider);

    // copy files used by the following RO/RW user providers
    File stResDir = new File(getClass().getResource("/storage-test").toURI());
    if (stResDir.exists() && stResDir.isDirectory() && CONFIG_DIR.exists() && CONFIG_DIR.isDirectory()) {
        for (File f : stResDir.listFiles()) {
            log.infof("Copying %s to %s", f.getName(), CONFIG_DIR.getAbsolutePath());
            FileUtils.copyFileToDirectory(f, CONFIG_DIR);
        }
    } else {
        throw new RuntimeException("Property `auth.server.config.dir` must be set to run UserStorageTests.");
    }

    ComponentRepresentation propProviderRO = new ComponentRepresentation();
    propProviderRO.setName("read-only-user-props");
    propProviderRO.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
    propProviderRO.setProviderType(UserStorageProvider.class.getName());
    propProviderRO.setConfig(new MultivaluedHashMap<>());
    propProviderRO.getConfig().putSingle("priority", Integer.toString(1));
    propProviderRO.getConfig().putSingle("propertyFile",
            CONFIG_DIR.getAbsolutePath() + File.separator + "read-only-user-password.properties");

    propProviderROId = addComponent(propProviderRO);

    propProviderRWId = addComponent(newPropProviderRW());

}
 
Example #25
Source File: GeneratedRsaKeyProviderTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected ComponentRepresentation createRep(String name, String providerId) {
    ComponentRepresentation rep = new ComponentRepresentation();
    rep.setName(name);
    rep.setParentId("test");
    rep.setProviderId(providerId);
    rep.setProviderType(KeyProvider.class.getName());
    rep.setConfig(new MultivaluedHashMap<>());
    return rep;
}
 
Example #26
Source File: CredentialModelBackwardsCompatibilityTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCredentialModelConfigMap() {
    MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
    map.add("key1", "val11");
    map.add("key1", "val12");
    map.add("key2", "val21");

    CredentialModel credential = new CredentialModel();
    Assert.assertNull(credential.getConfig());
    credential.setConfig(map);

    MultivaluedHashMap<String, String> loadedMap = credential.getConfig();
    Assert.assertEquals(map, loadedMap);
}
 
Example #27
Source File: HttpAdapterUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static MultivaluedHashMap<String, KeyInfo> downloadKeysFromSamlDescriptor(HttpClient client, String descriptorUrl) throws HttpClientAdapterException {
    try {
        HttpGet httpRequest = new HttpGet(descriptorUrl);
        HttpResponse response = client.execute(httpRequest);
        int status = response.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            EntityUtils.consumeQuietly(response.getEntity());
            throw new HttpClientAdapterException("Unexpected status = " + status);
        }

        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new HttpClientAdapterException("There was no entity.");
        }

        MultivaluedHashMap<String, KeyInfo> res;
        try (InputStream is = entity.getContent()) {
            res = extractKeysFromSamlDescriptor(is);
        }

        EntityUtils.consumeQuietly(entity);

        return res;
    } catch (IOException | ParsingException e) {
        throw new HttpClientAdapterException("IO error", e);
    }
}
 
Example #28
Source File: LDAPServerCapabilitiesManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static LDAPConfig buildLDAPConfig(TestLdapConnectionRepresentation config, RealmModel realm) {
    String bindCredential = config.getBindCredential();
    if (config.getComponentId() != null && ComponentRepresentation.SECRET_VALUE.equals(bindCredential)) {
        bindCredential = realm.getComponent(config.getComponentId()).getConfig().getFirst(LDAPConstants.BIND_CREDENTIAL);
    }
    MultivaluedHashMap<String, String> configMap = new MultivaluedHashMap<>();
    configMap.putSingle(LDAPConstants.AUTH_TYPE, config.getAuthType());
    configMap.putSingle(LDAPConstants.BIND_DN, config.getBindDn());
    configMap.putSingle(LDAPConstants.BIND_CREDENTIAL, bindCredential);
    configMap.add(LDAPConstants.CONNECTION_URL, config.getConnectionUrl());
    configMap.add(LDAPConstants.USE_TRUSTSTORE_SPI, config.getUseTruststoreSpi());
    configMap.putSingle(LDAPConstants.CONNECTION_TIMEOUT, config.getConnectionTimeout());
    configMap.add(LDAPConstants.START_TLS, config.getStartTls());
    return new LDAPConfig(configMap);
}
 
Example #29
Source File: TokenSignatureUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static ComponentRepresentation createKeyRep(String name, String providerId) {
    ComponentRepresentation rep = new ComponentRepresentation();
    rep.setName(name);
    rep.setParentId(TEST_REALM_NAME);
    rep.setProviderId(providerId);
    rep.setProviderType(KeyProvider.class.getName());
    rep.setConfig(new MultivaluedHashMap<>());
    return rep;
}
 
Example #30
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ComponentModel toModel(KeycloakSession session, ComponentRepresentation rep) {
    ComponentModel model = new ComponentModel();
    model.setId(rep.getId());
    model.setParentId(rep.getParentId());
    model.setProviderType(rep.getProviderType());
    model.setProviderId(rep.getProviderId());
    model.setConfig(new MultivaluedHashMap<>());
    model.setName(rep.getName());
    model.setSubType(rep.getSubType());

    if (rep.getConfig() != null) {
        Set<String> keys = new HashSet<>(rep.getConfig().keySet());
        for (String k : keys) {
            List<String> values = rep.getConfig().get(k);
            if (values != null) {
                ListIterator<String> itr = values.listIterator();
                while (itr.hasNext()) {
                    String v = itr.next();
                    if (v == null || v.trim().isEmpty()) {
                        itr.remove();
                    }
                }

                if (!values.isEmpty()) {
                    model.getConfig().put(k, values);
                }
            }
        }
    }

    return model;
}