Search in sources :

Example 21 with AttributeType

use of org.keycloak.dom.saml.v2.assertion.AttributeType in project keycloak by keycloak.

the class UsernameTemplateMapper method setUserNameFromTemplate.

private void setUserNameFromTemplate(IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    AssertionType assertion = (AssertionType) context.getContextData().get(SAMLEndpoint.SAML_ASSERTION);
    String template = mapperModel.getConfig().get(TEMPLATE);
    Matcher m = SUBSTITUTION.matcher(template);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String variable = m.group(1);
        UnaryOperator<String> transformer = Optional.ofNullable(m.group(2)).map(TRANSFORMERS::get).orElse(UnaryOperator.identity());
        if (variable.equals("ALIAS")) {
            m.appendReplacement(sb, transformer.apply(context.getIdpConfig().getAlias()));
        } else if (variable.equals("UUID")) {
            m.appendReplacement(sb, transformer.apply(KeycloakModelUtils.generateId()));
        } else if (variable.equals("NAMEID")) {
            SubjectType subject = assertion.getSubject();
            SubjectType.STSubType subType = subject.getSubType();
            NameIDType subjectNameID = (NameIDType) subType.getBaseID();
            m.appendReplacement(sb, transformer.apply(subjectNameID.getValue()));
        } else if (variable.startsWith("ATTRIBUTE.")) {
            String name = variable.substring("ATTRIBUTE.".length());
            String value = "";
            for (AttributeStatementType statement : assertion.getAttributeStatements()) {
                for (AttributeStatementType.ASTChoiceType choice : statement.getAttributes()) {
                    AttributeType attr = choice.getAttribute();
                    if (name.equals(attr.getName()) || name.equals(attr.getFriendlyName())) {
                        List<Object> attributeValue = attr.getAttributeValue();
                        if (attributeValue != null && !attributeValue.isEmpty()) {
                            value = attributeValue.get(0).toString();
                        }
                        break;
                    }
                }
            }
            m.appendReplacement(sb, transformer.apply(value));
        } else {
            m.appendReplacement(sb, m.group(1));
        }
    }
    m.appendTail(sb);
    Target t = getTarget(mapperModel.getConfig().get(TARGET));
    t.set(context, sb.toString());
}
Also used : Matcher(java.util.regex.Matcher) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) ArrayList(java.util.ArrayList) List(java.util.List) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType)

Example 22 with AttributeType

use of org.keycloak.dom.saml.v2.assertion.AttributeType in project keycloak by keycloak.

the class BrokerTest method createAuthnResponse.

private SAML2Object createAuthnResponse(SAML2Object so) {
    AuthnRequestType req = (AuthnRequestType) so;
    try {
        final ResponseType res = new SAML2LoginResponseBuilder().requestID(req.getID()).destination(req.getAssertionConsumerServiceURL().toString()).issuer("https://saml.idp/saml").assertionExpiration(1000000).subjectExpiration(1000000).requestIssuer(getAuthServerRealmBase(REALM_NAME).toString()).sessionIndex("idp:" + UUID.randomUUID()).buildModel();
        AttributeStatementType attrStatement = new AttributeStatementType();
        AttributeType attribute = new AttributeType("mail");
        attribute.addAttributeValue("v@w.x");
        attrStatement.addAttribute(new ASTChoiceType(attribute));
        res.getAssertions().get(0).getAssertion().addStatement(attrStatement);
        return res;
    } catch (ConfigurationException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
Also used : AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) SAML2LoginResponseBuilder(org.keycloak.saml.SAML2LoginResponseBuilder) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException)

Example 23 with AttributeType

use of org.keycloak.dom.saml.v2.assertion.AttributeType in project keycloak by keycloak.

the class ProtocolMapperTest method hardcodedAttributeMapperWithNullValueTest.

@Test
public void hardcodedAttributeMapperWithNullValueTest() throws Exception {
    pmu.add(createSamlProtocolMapper(HardcodedAttributeMapper.PROVIDER_ID, AttributeStatementHelper.SAML_ATTRIBUTE_NAME, "HARDCODED_ATTRIBUTE", AttributeStatementHelper.SAML_ATTRIBUTE_NAMEFORMAT, AttributeStatementHelper.BASIC, HardcodedAttributeMapper.ATTRIBUTE_VALUE, null)).update();
    SAMLDocumentHolder samlResponse = new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_EMPLOYEE_2, RoleMapperTest.SAML_ASSERTION_CONSUMER_URL_EMPLOYEE_2, SamlClient.Binding.POST).build().login().user(bburkeUser).build().getSamlResponse(SamlClient.Binding.POST);
    assertThat(samlResponse.getSamlObject(), Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    Stream<AssertionType> assertions = assertionsUnencrypted(samlResponse.getSamlObject());
    Stream<AttributeType> attributes = attributesUnecrypted(attributeStatements(assertions));
    Set<Object> attributeValues = attributes.flatMap(a -> a.getAttributeValue().stream()).collect(Collectors.toSet());
    assertThat(attributeValues, hasSize(1));
    assertThat(attributeValues.iterator().next(), nullValue());
}
Also used : AttributeStatementHelper(org.keycloak.protocol.saml.mappers.AttributeStatementHelper) HardcodedAttributeMapper(org.keycloak.protocol.saml.mappers.HardcodedAttributeMapper) ClientAttributeUpdater(org.keycloak.testsuite.updaters.ClientAttributeUpdater) ProtocolMappersUpdater(org.keycloak.testsuite.updaters.ProtocolMappersUpdater) Matchers(org.keycloak.testsuite.util.Matchers) SamlStreams.attributesUnecrypted(org.keycloak.testsuite.util.SamlStreams.attributesUnecrypted) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) Set(java.util.Set) Test(org.junit.Test) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Collectors(java.util.stream.Collectors) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) Assert.assertThat(org.junit.Assert.assertThat) Stream(java.util.stream.Stream) RoleMapperTest.createSamlProtocolMapper(org.keycloak.testsuite.saml.RoleMapperTest.createSamlProtocolMapper) SamlClient(org.keycloak.testsuite.util.SamlClient) Matchers.hasSize(org.hamcrest.Matchers.hasSize) SamlStreams.attributeStatements(org.keycloak.testsuite.util.SamlStreams.attributeStatements) SamlStreams.assertionsUnencrypted(org.keycloak.testsuite.util.SamlStreams.assertionsUnencrypted) Collections(java.util.Collections) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) Before(org.junit.Before) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Test(org.junit.Test)

Example 24 with AttributeType

use of org.keycloak.dom.saml.v2.assertion.AttributeType 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 25 with AttributeType

use of org.keycloak.dom.saml.v2.assertion.AttributeType in project keycloak by keycloak.

the class SAMLRequestedAttributeParser method instantiateElement.

@Override
protected RequestedAttributeType instantiateElement(XMLEventReader xmlEventReader, StartElement element) throws ParsingException {
    RequestedAttributeType attributeType = new RequestedAttributeType(StaxParserUtil.getRequiredAttributeValue(element, SAMLAssertionQNames.ATTR_NAME));
    attributeType.setFriendlyName(StaxParserUtil.getAttributeValue(element, SAMLMetadataQNames.ATTR_FRIENDLY_NAME));
    attributeType.setIsRequired(StaxParserUtil.getBooleanAttributeValue(element, SAMLMetadataQNames.ATTR_IS_REQUIRED));
    attributeType.setNameFormat(StaxParserUtil.getAttributeValue(element, SAMLMetadataQNames.ATTR_NAME_FORMAT));
    String encoding = StaxParserUtil.getAttributeValue(element, SAMLMetadataQNames.ATTR_X500_ENCODING);
    if (encoding != null && !encoding.isEmpty()) {
        attributeType.getOtherAttributes().put(SAMLMetadataQNames.ATTR_X500_ENCODING.getQName(), encoding);
    }
    return attributeType;
}
Also used : RequestedAttributeType(org.keycloak.dom.saml.v2.metadata.RequestedAttributeType)

Aggregations

AttributeType (org.keycloak.dom.saml.v2.assertion.AttributeType)42 AttributeStatementType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType)24 Test (org.junit.Test)17 AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)13 ASTChoiceType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType)12 RequestedAttributeType (org.keycloak.dom.saml.v2.metadata.RequestedAttributeType)10 QName (javax.xml.namespace.QName)9 Element (org.w3c.dom.Element)9 Matchers.containsString (org.hamcrest.Matchers.containsString)8 StatementAbstractType (org.keycloak.dom.saml.v2.assertion.StatementAbstractType)8 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)8 SAML2Object (org.keycloak.dom.saml.v2.SAML2Object)7 NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)7 JBossSAMLURIConstants (org.keycloak.saml.common.constants.JBossSAMLURIConstants)7 SamlClientBuilder (org.keycloak.testsuite.util.SamlClientBuilder)7 URI (java.net.URI)6 HashMap (java.util.HashMap)6 Set (java.util.Set)6 Collectors (java.util.stream.Collectors)6 Assert.assertThat (org.junit.Assert.assertThat)6