Java Code Examples for org.keycloak.common.util.MultivaluedHashMap#add()

The following examples show how to use org.keycloak.common.util.MultivaluedHashMap#add() . 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: 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 2
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 3
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 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: 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 6
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 7
Source File: AbstractUserAdapterFederatedStorage.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, List<String>> getAttributes() {
    MultivaluedHashMap<String, String> attributes = getFederatedStorage().getAttributes(realm, this.getId());
    if (attributes == null) {
        attributes = new MultivaluedHashMap<>();
    }
    List<String> firstName = attributes.remove(FIRST_NAME_ATTRIBUTE);
    attributes.add(UserModel.FIRST_NAME, firstName != null && firstName.size() >= 1 ? firstName.get(0) : null);
    List<String> lastName = attributes.remove(LAST_NAME_ATTRIBUTE);
    attributes.add(UserModel.LAST_NAME, lastName != null && lastName.size() >= 1 ? lastName.get(0) : null);
    List<String> email = attributes.remove(EMAIL_ATTRIBUTE);
    attributes.add(UserModel.EMAIL, email != null && email.size() >= 1 ? email.get(0) : null);
    attributes.add(UserModel.USERNAME, getUsername());
    return attributes;
}
 
Example 8
Source File: FilterSessionStore.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static MultivaluedHashMap<String, String> parseForm(InputStream entityStream)
        throws IOException
{
    char[] buffer = new char[100];
    StringBuffer buf = new StringBuffer();
    BufferedReader reader = new BufferedReader(new InputStreamReader(entityStream));

    int wasRead = 0;
    do
    {
        wasRead = reader.read(buffer, 0, 100);
        if (wasRead > 0) buf.append(buffer, 0, wasRead);
    } while (wasRead > -1);

    String form = buf.toString();

    MultivaluedHashMap<String, String> formData = new MultivaluedHashMap<String, String>();
    if ("".equals(form)) return formData;

    String[] params = form.split("&");

    for (String param : params)
    {
        if (param.indexOf('=') >= 0)
        {
            String[] nv = param.split("=");
            String val = nv.length > 1 ? nv[1] : "";
            formData.add(Encode.decode(nv[0]), Encode.decode(val));
        }
        else
        {
            formData.add(Encode.decode(param), "");
        }
    }
    return formData;
}
 
Example 9
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 10
Source File: ExportUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static MultivaluedHashMap<String, ComponentExportRepresentation> exportComponents(RealmModel realm, String parentId) {
    List<ComponentModel> componentList = realm.getComponents(parentId);
    MultivaluedHashMap<String, ComponentExportRepresentation> components = new MultivaluedHashMap<>();
    for (ComponentModel component : componentList) {
        ComponentExportRepresentation compRep = new ComponentExportRepresentation();
        compRep.setId(component.getId());
        compRep.setProviderId(component.getProviderId());
        compRep.setConfig(component.getConfig());
        compRep.setName(component.getName());
        compRep.setSubType(component.getSubType());
        compRep.setSubComponents(exportComponents(realm, component.getId()));
        components.add(component.getProviderType(), compRep);
    }
    return components;
}
 
Example 11
Source File: ApplicationsBean.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void processRoles(Set<RoleModel> inputRoles, List<RoleModel> realmRoles, MultivaluedHashMap<String, ClientRoleEntry> clientRoles) {
    for (RoleModel role : inputRoles) {
        if (role.getContainer() instanceof RealmModel) {
            realmRoles.add(role);
        } else {
            ClientModel currentClient = (ClientModel) role.getContainer();
            ClientRoleEntry clientRole = new ClientRoleEntry(currentClient.getClientId(), currentClient.getName(),
                    role.getName(), role.getDescription());
            clientRoles.add(currentClient.getClientId(), clientRole);
        }
    }
}
 
Example 12
Source File: ResourceAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, List<String>> getAttributes() {
    MultivaluedHashMap<String, String> result = new MultivaluedHashMap<>();
    for (ResourceAttributeEntity attr : entity.getAttributes()) {
        result.add(attr.getName(), attr.getValue());
    }
    return Collections.unmodifiableMap(result);
}
 
Example 13
Source File: UserAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, List<String>> getAttributes() {
    MultivaluedHashMap<String, String> result = new MultivaluedHashMap<>();
    for (UserAttributeEntity attr : user.getAttributes()) {
        result.add(attr.getName(), attr.getValue());
    }
    result.add(UserModel.FIRST_NAME, user.getFirstName());
    result.add(UserModel.LAST_NAME, user.getLastName());
    result.add(UserModel.EMAIL, user.getEmail());
    result.add(UserModel.USERNAME, user.getUsername());
    return result;
}
 
Example 14
Source File: LDAPMappersComparatorTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompareWithSAMAccountNameUsername() {
    MultivaluedHashMap<String, String> cfg = new MultivaluedHashMap<>();
    cfg.add(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, LDAPConstants.SAM_ACCOUNT_NAME);
    LDAPConfig config = new LDAPConfig(cfg);

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

    sorted = LDAPMappersComparator.sortDesc(config, getMappers());
    assertOrder(sorted, "full name", "first name", "username-cn", "sAMAccountName");
}
 
Example 15
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 16
Source File: AbstractUserAdapter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, List<String>> getAttributes() {
    MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
    attributes.add(UserModel.USERNAME, getUsername());
    return attributes;
}
 
Example 17
Source File: ResourceAdminManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private void putClientSessions(MultivaluedHashMap<String, AuthenticatedClientSessionModel> clientSessions, UserSessionModel userSession) {
    for (Map.Entry<String, AuthenticatedClientSessionModel> entry : userSession.getAuthenticatedClientSessions().entrySet()) {
        clientSessions.add(entry.getKey(), entry.getValue());
    }
}
 
Example 18
Source File: FilterSessionStore.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void saveRequest() {
    HttpSession session = request.getSession(true);
    session.setAttribute(REDIRECT_URI, facade.getRequest().getURI());
    session.setAttribute(SAVED_METHOD, request.getMethod());
    MultivaluedHashMap<String, String> headers = new MultivaluedHashMap<>();
    Enumeration<String> names = request.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        Enumeration<String> values = request.getHeaders(name);
        while (values.hasMoreElements()) {
            headers.add(name.toLowerCase(), values.nextElement());
        }
    }
    session.setAttribute(SAVED_HEADERS, headers);
    if (request.getMethod().equalsIgnoreCase("GET")) {
        return;
    }
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    byte[] buffer = new byte[4096];
    int bytesRead;
    int totalRead = 0;
    try {
        InputStream is = request.getInputStream();

        while ( (bytesRead = is.read(buffer) ) >= 0) {
            os.write(buffer, 0, bytesRead);
            totalRead += bytesRead;
            if (totalRead > maxBuffer) {
                throw new RuntimeException("max buffer reached on a saved request");
            }

        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    byte[] body = os.toByteArray();
    // Only save the request body if there is something to save
    if (body.length > 0) {
        session.setAttribute(SAVED_BODY, body);
    }


}
 
Example 19
Source File: OIDCScopeTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void configureTestRealm(RealmRepresentation testRealm) {
    UserRepresentation user = UserBuilder.create()
            .id(userId)
            .username("john")
            .enabled(true)
            .email("[email protected]")
            .firstName("John")
            .lastName("Doe")
            .password("password")
            .role("account", "manage-account")
            .role("account", "view-profile")
            .addRoles("role-1", "role-2")
            .build();

    user.setEmailVerified(true);
    MultivaluedHashMap<String, String> attrs = new MultivaluedHashMap<>();
    attrs.add("street", "Elm 5");
    attrs.add("phoneNumber", "111-222-333");
    attrs.add("phoneNumberVerified", "true");
    user.setAttributes(attrs);

    testRealm.getUsers().add(user);


    // Add sample realm roles
    RoleRepresentation role1 = new RoleRepresentation();
    role1.setName("role-1");
    testRealm.getRoles().getRealm().add(role1);
    RoleRepresentation role2 = new RoleRepresentation();
    role2.setName("role-2");
    testRealm.getRoles().getRealm().add(role2);

    RoleRepresentation roleParent = RoleBuilder.create()
            .name("role-parent")
            .realmComposite("role-1")
            .build();
    testRealm.getRoles().getRealm().add(roleParent);

    // Add sample group
    GroupRepresentation group = new GroupRepresentation();
    group.setName("group-role-1");
    group.setRealmRoles(Collections.singletonList("role-1"));
    testRealm.getGroups().add(group);

    // Add more sample users
    user = UserBuilder.create()
            .username("role-1-user")
            .enabled(true)
            .password("password")
            .addRoles("role-1")
            .build();
    testRealm.getUsers().add(user);

    user = UserBuilder.create()
            .username("role-2-user")
            .enabled(true)
            .password("password")
            .addRoles("role-2")
            .build();
    testRealm.getUsers().add(user);

    user = UserBuilder.create()
            .username("role-parent-user")
            .enabled(true)
            .password("password")
            .addRoles("role-parent")
            .build();
    testRealm.getUsers().add(user);

    user = UserBuilder.create()
            .username("group-role-1-user")
            .enabled(true)
            .password("password")
            .addGroups("group-role-1")
            .build();
    testRealm.getUsers().add(user);
}
 
Example 20
Source File: WebAuthnCredentialProvider.java    From keycloak-webauthn-authenticator with Apache License 2.0 3 votes vote down vote up
private CredentialModel createCredentialModel(CredentialInput input) {
    if (!supportsCredentialType(input.getType())) return null;

    WebAuthnCredentialModel webAuthnModel = (WebAuthnCredentialModel) input;
    CredentialModel model = new CredentialModel();
    model.setType(WebAuthnCredentialModel.WEBAUTHN_CREDENTIAL_TYPE);
    model.setCreatedDate(Time.currentTimeMillis());

    MultivaluedHashMap<String, String> credential = new MultivaluedHashMap<>();

    AttestationStatementConverter attConv = new AttestationStatementConverter();
    credential.add(ATTESTATION_STATEMENT, attConv.convertToDatabaseColumn(webAuthnModel.getAttestationStatement()));

    credential.add(AAGUID, webAuthnModel.getAttestedCredentialData().getAaguid().toString());

    credential.add(CREDENTIAL_ID, Base64.encodeBytes(webAuthnModel.getAttestedCredentialData().getCredentialId()));

    CredentialPublicKeyConverter credConv = new CredentialPublicKeyConverter();
    credential.add(CREDENTIAL_PUBLIC_KEY, credConv.convertToDatabaseColumn(webAuthnModel.getAttestedCredentialData().getCredentialPublicKey()));

    model.setId(webAuthnModel.getAuthenticatorId());

    model.setConfig(credential);

    // authenticator's counter
    model.setValue(String.valueOf(webAuthnModel.getCount()));

    dumpCredentialModel(model);
    dumpWebAuthnCredentialModel(webAuthnModel);

    return model;
}