Search in sources :

Example 16 with MultivaluedHashMap

use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.

the class LDAPSamlIdPInitiatedVaryingLetterCaseTest method afterImportTestRealm.

@Override
protected void afterImportTestRealm() {
    getTestingClient().server().run(session -> {
        LDAPTestContext ctx = LDAPTestContext.init(session);
        RealmModel appRealm = ctx.getRealm();
        // Delete all LDAP users
        LDAPTestUtils.removeAllLDAPUsers(ctx.getLdapProvider(), appRealm);
        // Add some new LDAP users for testing
        LDAPObject user = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, USER_NAME_LDAP, USER_FIRST_NAME, USER_LAST_NAME, USER_EMAIL, USER_STREET, USER_POSTAL_CODE);
        LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), user, USER_PASSWORD);
    });
    ComponentRepresentation ldap = testRealm().components().query(null, "org.keycloak.storage.UserStorageProvider").get(0);
    ComponentRepresentation ldapMapper = new ComponentRepresentation();
    ldapMapper.setName("uid-to-user-attr-mapper");
    ldapMapper.setProviderId(UserAttributeLDAPStorageMapperFactory.PROVIDER_ID);
    ldapMapper.setProviderType("org.keycloak.storage.ldap.mappers.LDAPStorageMapper");
    ldapMapper.setParentId(ldap.getId());
    MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
    config.add(UserAttributeLDAPStorageMapper.USER_MODEL_ATTRIBUTE, "ldapUid");
    config.add(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE, "uid");
    config.add(UserAttributeLDAPStorageMapper.READ_ONLY, "true");
    config.add(UserAttributeLDAPStorageMapper.IS_MANDATORY_IN_LDAP, "true");
    ldapMapper.setConfig(config);
    testRealm().components().add(ldapMapper);
}
Also used : RealmModel(org.keycloak.models.RealmModel) ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) LDAPObject(org.keycloak.storage.ldap.idm.model.LDAPObject) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 17 with MultivaluedHashMap

use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.

the class LdapUserStorage method getParameters.

@Override
public <T> Stream<T> getParameters(Class<T> clazz) {
    if (UserStorageProviderModel.class.isAssignableFrom(clazz)) {
        MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
        for (java.util.Map.Entry<String, String> entry : ldapRule.getConfig().entrySet()) {
            config.add(entry.getKey(), entry.getValue());
        }
        config.putSingle(LDAPConstants.SYNC_REGISTRATIONS, "true");
        config.putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString());
        UserStorageProviderModel federatedStorage = new UserStorageProviderModel();
        federatedStorage.setName(LDAPStorageProviderFactory.PROVIDER_NAME + ":" + counter.getAndIncrement());
        federatedStorage.setProviderId(LDAPStorageProviderFactory.PROVIDER_NAME);
        federatedStorage.setProviderType(UserStorageProvider.class.getName());
        federatedStorage.setLastSync(0);
        federatedStorage.setChangedSyncPeriod(-1);
        federatedStorage.setFullSyncPeriod(-1);
        federatedStorage.setPriority(0);
        federatedStorage.setConfig(config);
        return Stream.of((T) federatedStorage);
    } else {
        return super.getParameters(clazz);
    }
}
Also used : MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) UserStorageProvider(org.keycloak.storage.UserStorageProvider) UserStorageProviderModel(org.keycloak.storage.UserStorageProviderModel) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap)

Example 18 with MultivaluedHashMap

use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.

the class RealmManager method generateNewRsaKey.

public String generateNewRsaKey(KeyPair keyPair, String name) {
    RealmRepresentation rep = realm.toRepresentation();
    Certificate certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, "test");
    String certificatePem = PemUtils.encodeCertificate(certificate);
    ComponentRepresentation keyProviderRepresentation = new ComponentRepresentation();
    keyProviderRepresentation.setName(name);
    keyProviderRepresentation.setParentId(rep.getId());
    keyProviderRepresentation.setProviderId(ImportedRsaKeyProviderFactory.ID);
    keyProviderRepresentation.setProviderType(KeyProvider.class.getName());
    MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
    config.putSingle(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));
    config.putSingle(Attributes.CERTIFICATE_KEY, certificatePem);
    config.putSingle(Attributes.PRIORITY_KEY, "100");
    keyProviderRepresentation.setConfig(config);
    Response response = realm.components().add(keyProviderRepresentation);
    String providerId = ApiUtil.getCreatedId(response);
    response.close();
    deactivateOtherRsaKeys(providerId);
    return providerId;
}
Also used : ComponentRepresentation(org.keycloak.representations.idm.ComponentRepresentation) KeyProvider(org.keycloak.keys.KeyProvider) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) Response(javax.ws.rs.core.Response) RealmRepresentation(org.keycloak.representations.idm.RealmRepresentation) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 19 with MultivaluedHashMap

use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.

the class AbstractSamlAuthenticationHandler method handleLoginResponse.

protected AuthOutcome handleLoginResponse(SAMLDocumentHolder responseHolder, boolean postBinding, OnSessionCreated onCreateSession) {
    if (!sessionStore.isLoggingIn()) {
        log.warn("Adapter obtained LoginResponse, however containers session is not aware of sending any request. " + "This may be because the session cookies created by container are not properly configured " + "with SameSite settings. Refer to KEYCLOAK-14103 for more details.");
    }
    final ResponseType responseType = (ResponseType) responseHolder.getSamlObject();
    AssertionType assertion = null;
    if (!isSuccessfulSamlResponse(responseType) || responseType.getAssertions() == null || responseType.getAssertions().isEmpty()) {
        return failed(createAuthChallenge403(responseType));
    }
    try {
        assertion = AssertionUtil.getAssertion(responseHolder, responseType, deployment.getDecryptionKey());
        ConditionsValidator.Builder cvb = new ConditionsValidator.Builder(assertion.getID(), assertion.getConditions(), destinationValidator);
        try {
            cvb.clockSkewInMillis(deployment.getIDP().getAllowedClockSkew());
            cvb.addAllowedAudience(URI.create(deployment.getEntityID()));
            if (responseType.getDestination() != null) {
                // getDestination has been validated to match request URL already so it matches SAML endpoint
                cvb.addAllowedAudience(URI.create(responseType.getDestination()));
            }
        } catch (IllegalArgumentException ex) {
        // warning has been already emitted in DeploymentBuilder
        }
        if (!cvb.build().isValid()) {
            return initiateLogin();
        }
    } catch (Exception e) {
        log.error("Error extracting SAML assertion: " + e.getMessage());
        return failed(CHALLENGE_EXTRACTION_FAILURE);
    }
    Element assertionElement = null;
    if (deployment.getIDP().getSingleSignOnService().validateAssertionSignature()) {
        try {
            assertionElement = getAssertionFromResponse(responseHolder);
            if (!AssertionUtil.isSignatureValid(assertionElement, deployment.getIDP().getSignatureValidationKeyLocator())) {
                log.error("Failed to verify saml assertion signature");
                return failed(CHALLENGE_INVALID_SIGNATURE);
            }
        } catch (Exception e) {
            log.error("Error processing validation of SAML assertion: " + e.getMessage());
            return failed(CHALLENGE_EXTRACTION_FAILURE);
        }
    }
    SubjectType subject = assertion.getSubject();
    SubjectType.STSubType subType = subject.getSubType();
    NameIDType subjectNameID = subType == null ? null : (NameIDType) subType.getBaseID();
    String principalName = subjectNameID == null ? null : subjectNameID.getValue();
    Set<String> roles = new HashSet<>();
    MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
    MultivaluedHashMap<String, String> friendlyAttributes = new MultivaluedHashMap<>();
    Set<StatementAbstractType> statements = assertion.getStatements();
    for (StatementAbstractType statement : statements) {
        if (statement instanceof AttributeStatementType) {
            AttributeStatementType attributeStatement = (AttributeStatementType) statement;
            List<AttributeStatementType.ASTChoiceType> attList = attributeStatement.getAttributes();
            for (AttributeStatementType.ASTChoiceType obj : attList) {
                AttributeType attr = obj.getAttribute();
                if (isRole(attr)) {
                    List<Object> attributeValues = attr.getAttributeValue();
                    if (attributeValues != null) {
                        for (Object attrValue : attributeValues) {
                            String role = getAttributeValue(attrValue);
                            log.debugv("Add role: {0}", role);
                            roles.add(role);
                        }
                    }
                } else {
                    List<Object> attributeValues = attr.getAttributeValue();
                    if (attributeValues != null) {
                        for (Object attrValue : attributeValues) {
                            String value = getAttributeValue(attrValue);
                            if (attr.getName() != null) {
                                attributes.add(attr.getName(), value);
                            }
                            if (attr.getFriendlyName() != null) {
                                friendlyAttributes.add(attr.getFriendlyName(), value);
                            }
                        }
                    }
                }
            }
        }
    }
    if (deployment.getPrincipalNamePolicy() == SamlDeployment.PrincipalNamePolicy.FROM_ATTRIBUTE) {
        if (deployment.getPrincipalAttributeName() != null) {
            String attribute = attributes.getFirst(deployment.getPrincipalAttributeName());
            if (attribute != null)
                principalName = attribute;
            else {
                attribute = friendlyAttributes.getFirst(deployment.getPrincipalAttributeName());
                if (attribute != null)
                    principalName = attribute;
            }
        }
    }
    // use the configured role mappings provider to map roles if necessary.
    if (deployment.getRoleMappingsProvider() != null) {
        roles = deployment.getRoleMappingsProvider().map(principalName, roles);
    }
    // roles should also be there as regular attributes
    // this mainly required for elytron and its ABAC nature
    attributes.put(DEFAULT_ROLE_ATTRIBUTE_NAME, new ArrayList<>(roles));
    AuthnStatementType authn = null;
    for (Object statement : assertion.getStatements()) {
        if (statement instanceof AuthnStatementType) {
            authn = (AuthnStatementType) statement;
            break;
        }
    }
    URI nameFormat = subjectNameID == null ? null : subjectNameID.getFormat();
    String nameFormatString = nameFormat == null ? JBossSAMLURIConstants.NAMEID_FORMAT_UNSPECIFIED.get() : nameFormat.toString();
    if (deployment.isKeepDOMAssertion() && assertionElement == null) {
        // obtain the assertion from the response to add the DOM document to the principal
        assertionElement = getAssertionFromResponseNoException(responseHolder);
    }
    final SamlPrincipal principal = new SamlPrincipal(assertion, deployment.isKeepDOMAssertion() ? getAssertionDocumentFromElement(assertionElement) : null, principalName, principalName, nameFormatString, attributes, friendlyAttributes);
    final String sessionIndex = authn == null ? null : authn.getSessionIndex();
    final XMLGregorianCalendar sessionNotOnOrAfter = authn == null ? null : authn.getSessionNotOnOrAfter();
    SamlSession account = new SamlSession(principal, roles, sessionIndex, sessionNotOnOrAfter);
    sessionStore.saveAccount(account);
    onCreateSession.onSessionCreated(account);
    // redirect to original request, it will be restored
    String redirectUri = sessionStore.getRedirectUri();
    if (redirectUri != null) {
        facade.getResponse().setHeader("Location", redirectUri);
        facade.getResponse().setStatus(302);
        facade.getResponse().end();
    } else {
        log.debug("IDP initiated invocation");
    }
    log.debug("AUTHENTICATED authn");
    return AuthOutcome.AUTHENTICATED;
}
Also used : SAML2AuthnRequestBuilder(org.keycloak.saml.SAML2AuthnRequestBuilder) KeycloakUriBuilder(org.keycloak.common.util.KeycloakUriBuilder) BaseSAML2BindingBuilder(org.keycloak.saml.BaseSAML2BindingBuilder) Element(org.w3c.dom.Element) URI(java.net.URI) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) AuthnStatementType(org.keycloak.dom.saml.v2.assertion.AuthnStatementType) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) SamlSession(org.keycloak.adapters.saml.SamlSession) VerificationException(org.keycloak.common.VerificationException) SignatureException(java.security.SignatureException) KeyManagementException(java.security.KeyManagementException) InvalidKeyException(java.security.InvalidKeyException) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) IOException(java.io.IOException) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) SamlPrincipal(org.keycloak.adapters.saml.SamlPrincipal) SAML2Object(org.keycloak.dom.saml.v2.SAML2Object) ConditionsValidator(org.keycloak.saml.validators.ConditionsValidator) StatementAbstractType(org.keycloak.dom.saml.v2.assertion.StatementAbstractType)

Example 20 with MultivaluedHashMap

use of org.keycloak.common.util.MultivaluedHashMap in project keycloak by keycloak.

the class SamlDescriptorIDPKeysExtractorTest method testParse.

public void testParse(String fileToParse) {
    InputStream stream = getClass().getResourceAsStream(fileToParse);
    SamlDescriptorIDPKeysExtractor extractor = new SamlDescriptorIDPKeysExtractor();
    try {
        MultivaluedHashMap keyMap = extractor.parse(stream);
        assertFalse(keyMap.isEmpty());
        assertTrue(keyMap.containsKey("signing"));
        assertTrue(keyMap.containsKey("encryption"));
    } catch (ParsingException e) {
        fail(e.getMessage());
    }
}
Also used : MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) InputStream(java.io.InputStream) ParsingException(org.keycloak.saml.common.exceptions.ParsingException)

Aggregations

MultivaluedHashMap (org.keycloak.common.util.MultivaluedHashMap)44 ComponentModel (org.keycloak.component.ComponentModel)15 List (java.util.List)9 LinkedList (java.util.LinkedList)8 Map (java.util.Map)8 KeyProvider (org.keycloak.keys.KeyProvider)8 RealmModel (org.keycloak.models.RealmModel)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 ComponentExportRepresentation (org.keycloak.representations.idm.ComponentExportRepresentation)6 IOException (java.io.IOException)5 HttpSession (javax.servlet.http.HttpSession)5 ComponentRepresentation (org.keycloak.representations.idm.ComponentRepresentation)5 UserRepresentation (org.keycloak.representations.idm.UserRepresentation)5 RoleModel (org.keycloak.models.RoleModel)4 HashSet (java.util.HashSet)3 Test (org.junit.Test)3 ClientModel (org.keycloak.models.ClientModel)3 ClientScopeModel (org.keycloak.models.ClientScopeModel)3 BufferedReader (java.io.BufferedReader)2