Search in sources :

Example 6 with Statement

use of org.opensaml.saml.saml2.core.Statement in project cas by apereo.

the class SamlProfileSamlAttributeStatementBuilderTests method verifyAttributeAsNameIDSameAsSubject.

@Test
public void verifyAttributeAsNameIDSameAsSubject() throws Exception {
    val service = getSamlRegisteredServiceForTestShib();
    service.getAttributeValueTypes().put("customNameId", NameIDType.class.getSimpleName());
    val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get(samlRegisteredServiceCachingMetadataResolver, service, service.getServiceId()).get();
    val buildContext = SamlProfileBuilderContext.builder().samlRequest(getAuthnRequestFor(service)).httpRequest(new MockHttpServletRequest()).httpResponse(new MockHttpServletResponse()).authenticatedAssertion(getAssertion(Map.of("customNameId", List.of(UUID.randomUUID().toString())))).registeredService(service).adaptor(adaptor).binding(SAMLConstants.SAML2_POST_BINDING_URI).build();
    val statement = samlProfileSamlAttributeStatementBuilder.build(buildContext);
    val attributes = statement.getAttributes();
    assertFalse(attributes.isEmpty());
    val result = attributes.stream().filter(a -> a.getName().equals("customNameId")).findFirst();
    assertTrue(result.isPresent());
    assertTrue(result.get().getAttributeValues().get(0) instanceof NameIDType);
}
Also used : lombok.val(lombok.val) lombok.val(lombok.val) Autowired(org.springframework.beans.factory.annotation.Autowired) TestPropertySource(org.springframework.test.context.TestPropertySource) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) UUID(java.util.UUID) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test) BaseSamlIdPConfigurationTests(org.apereo.cas.support.saml.BaseSamlIdPConfigurationTests) List(java.util.List) SamlProfileBuilderContext(org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileBuilderContext) SamlProfileObjectBuilder(org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileObjectBuilder) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Map(java.util.Map) NameIDType(org.opensaml.saml.saml2.core.NameIDType) Qualifier(org.springframework.beans.factory.annotation.Qualifier) Assertions(org.junit.jupiter.api.Assertions) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) Tag(org.junit.jupiter.api.Tag) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) NameIDType(org.opensaml.saml.saml2.core.NameIDType) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 7 with Statement

use of org.opensaml.saml.saml2.core.Statement in project cas by apereo.

the class SamlProfileSamlAttributeStatementBuilderTests method verifyTestAttributeDefns.

@Test
public void verifyTestAttributeDefns() throws Exception {
    val service = getSamlRegisteredServiceForTestShib();
    val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get(samlRegisteredServiceCachingMetadataResolver, service, service.getServiceId()).get();
    val buildContext = SamlProfileBuilderContext.builder().samlRequest(getAuthnRequestFor(service)).httpRequest(new MockHttpServletRequest()).httpResponse(new MockHttpServletResponse()).authenticatedAssertion(getAssertion(Map.of("emptyAttributeCol", List.of()))).registeredService(service).adaptor(adaptor).binding(SAMLConstants.SAML2_POST_BINDING_URI).build();
    val statement = samlProfileSamlAttributeStatementBuilder.build(buildContext);
    val attributes = statement.getAttributes();
    assertFalse(attributes.isEmpty());
    assertTrue(attributes.stream().anyMatch(a -> a.getName().equals("urn:oid:0.9.2342.19200300.100.1.3")));
    assertTrue(attributes.stream().anyMatch(a -> a.getName().equals("alias")));
    assertTrue(attributes.stream().anyMatch(a -> a.getName().equals("common-name")));
    assertTrue(attributes.stream().anyMatch(a -> a.getName().equals("nickname")));
}
Also used : lombok.val(lombok.val) lombok.val(lombok.val) Autowired(org.springframework.beans.factory.annotation.Autowired) TestPropertySource(org.springframework.test.context.TestPropertySource) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) UUID(java.util.UUID) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test) BaseSamlIdPConfigurationTests(org.apereo.cas.support.saml.BaseSamlIdPConfigurationTests) List(java.util.List) SamlProfileBuilderContext(org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileBuilderContext) SamlProfileObjectBuilder(org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileObjectBuilder) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Map(java.util.Map) NameIDType(org.opensaml.saml.saml2.core.NameIDType) Qualifier(org.springframework.beans.factory.annotation.Qualifier) Assertions(org.junit.jupiter.api.Assertions) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) Tag(org.junit.jupiter.api.Tag) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 8 with Statement

use of org.opensaml.saml.saml2.core.Statement in project cas by apereo.

the class SamlProfileSamlAttributeStatementBuilder method newAttributeStatement.

/**
 * New attribute statement.
 *
 * @param context    the context
 * @param attributes the attributes
 * @param builder    the builder
 * @return the attribute statement
 * @throws Exception the exception
 */
public AttributeStatement newAttributeStatement(final SamlProfileBuilderContext context, final Map<String, Object> attributes, final Saml20AttributeBuilder builder) throws Exception {
    val attrStatement = SamlUtils.newSamlObject(AttributeStatement.class);
    val resp = samlIdPProperties.getResponse();
    val nameFormats = new HashMap<>(resp.configureAttributeNameFormats());
    nameFormats.putAll(context.getRegisteredService().getAttributeNameFormats());
    val globalFriendlyNames = samlIdPProperties.getCore().getAttributeFriendlyNames();
    val friendlyNames = new HashMap<>(CollectionUtils.convertDirectedListToMap(globalFriendlyNames));
    val urns = new HashMap<String, String>();
    attributeDefinitionStore.getAttributeDefinitions().stream().filter(defn -> defn instanceof SamlIdPAttributeDefinition).map(SamlIdPAttributeDefinition.class::cast).forEach(defn -> {
        if (StringUtils.isNotBlank(defn.getFriendlyName())) {
            friendlyNames.put(defn.getKey(), defn.getFriendlyName());
        }
        if (StringUtils.isNotBlank(defn.getUrn())) {
            urns.put(defn.getKey(), defn.getUrn());
        }
    });
    friendlyNames.putAll(context.getRegisteredService().getAttributeFriendlyNames());
    SamlIdPAttributeDefinitionCatalog.load().filter(defn -> !friendlyNames.containsKey(defn.getKey())).forEach(defn -> {
        friendlyNames.put(defn.getKey(), defn.getFriendlyName());
        urns.put(defn.getKey(), defn.getUrn());
    });
    for (val entry : attributes.entrySet()) {
        var attributeValue = entry.getValue();
        if (attributeValue instanceof Collection<?> && ((Collection<?>) attributeValue).isEmpty()) {
            LOGGER.info("Skipping attribute [{}] because it does not have any values.", entry.getKey());
            continue;
        }
        val friendlyName = friendlyNames.getOrDefault(entry.getKey(), null);
        val attributeNames = urns.containsKey(entry.getKey()) ? List.of(urns.get(entry.getKey())) : getMappedAttributeNamesFromAttributeDefinitionStore(entry);
        for (val name : attributeNames) {
            LOGGER.trace("Processing SAML attribute [{}] with value [{}], friendlyName [{}]", name, attributeValue, friendlyName);
            val valueType = context.getRegisteredService().getAttributeValueTypes().get(name);
            if (NameIDType.class.getSimpleName().equalsIgnoreCase(valueType)) {
                val nameIdObject = samlNameIdBuilder.build(context);
                if (nameIdObject instanceof NameID) {
                    val nameID = newSamlObject(NameID.class);
                    val nameId = (NameID) nameIdObject;
                    nameID.setFormat(nameId.getFormat());
                    nameID.setNameQualifier(nameId.getNameQualifier());
                    nameID.setSPNameQualifier(nameId.getSPNameQualifier());
                    nameID.setValue(nameId.getValue());
                    attributeValue = nameID;
                }
            }
            if (NameID.PERSISTENT.equalsIgnoreCase(valueType)) {
                val nameID = newSamlObject(NameID.class);
                nameID.setFormat(NameID.PERSISTENT);
                nameID.setNameQualifier(SamlIdPUtils.determineNameIdNameQualifier(context.getRegisteredService(), samlIdPMetadataResolver));
                FunctionUtils.doIf(StringUtils.isNotBlank(context.getRegisteredService().getServiceProviderNameIdQualifier()), value -> nameID.setSPNameQualifier(context.getRegisteredService().getServiceProviderNameIdQualifier()), value -> nameID.setSPNameQualifier(context.getAdaptor().getEntityId())).accept(context.getRegisteredService());
                CollectionUtils.firstElement(attributeValue).ifPresent(value -> nameID.setValue(value.toString()));
                attributeValue = nameID;
            }
            LOGGER.debug("Creating SAML attribute [{}] with value [{}], friendlyName [{}]", name, attributeValue, friendlyName);
            val attribute = newAttribute(friendlyName, name, attributeValue, nameFormats, resp.getDefaultAttributeNameFormat(), context.getRegisteredService().getAttributeValueTypes());
            LOGGER.trace("Created SAML attribute [{}] with NameID format [{}]", attribute.getName(), attribute.getNameFormat());
            builder.build(attrStatement, attribute);
        }
    }
    return attrStatement;
}
Also used : lombok.val(lombok.val) AbstractSaml20ObjectBuilder(org.apereo.cas.support.saml.util.AbstractSaml20ObjectBuilder) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) SamlUtils(org.apereo.cas.support.saml.SamlUtils) ProtocolAttributeEncoder(org.apereo.cas.authentication.ProtocolAttributeEncoder) Saml20AttributeBuilder(org.apereo.cas.support.saml.util.Saml20AttributeBuilder) SamlIdPObjectEncrypter(org.apereo.cas.support.saml.web.idp.profile.builders.enc.SamlIdPObjectEncrypter) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) ServiceFactory(org.apereo.cas.authentication.principal.ServiceFactory) AttributeDefinitionStore(org.apereo.cas.authentication.attribute.AttributeDefinitionStore) Collection(java.util.Collection) SamlIdPProperties(org.apereo.cas.configuration.model.support.saml.idp.SamlIdPProperties) lombok.val(lombok.val) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) SamlIdPUtils(org.apereo.cas.support.saml.SamlIdPUtils) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) AttributeDefinition(org.apereo.cas.authentication.attribute.AttributeDefinition) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) SamlProfileBuilderContext(org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileBuilderContext) SAMLObject(org.opensaml.saml.common.SAMLObject) SamlProfileObjectBuilder(org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileObjectBuilder) NameIDType(org.opensaml.saml.saml2.core.NameIDType) NameID(org.opensaml.saml.saml2.core.NameID) HashMap(java.util.HashMap) NameID(org.opensaml.saml.saml2.core.NameID) NameIDType(org.opensaml.saml.saml2.core.NameIDType)

Example 9 with Statement

use of org.opensaml.saml.saml2.core.Statement in project ddf by codice.

the class AttributeQueryClaimsHandler method createClaims.

/**
 * Creates claims from the extracted attributes.
 *
 * @param claimsCollection The collection of claims.
 * @param assertion Assertion from the response.
 * @return The collection of claims.
 * @throws URISyntaxException
 */
protected ClaimsCollection createClaims(ClaimsCollection claimsCollection, Assertion assertion) {
    // Should only contain one Attribute Statement.
    AttributeStatement attributeStatement = assertion.getAttributeStatements().get(0);
    List<Attribute> attributeList = attributeStatement.getAttributes();
    // and create the claim, otherwise, create the claim using its original attribute value.
    for (Attribute attribute : attributeList) {
        for (String claimType : supportedClaims) {
            if (claimType.equalsIgnoreCase(attribute.getName())) {
                String claimValue = attribute.getDOM().getTextContent();
                claimsCollection.add(createSingleValuedClaim(claimType, attributeMap.getOrDefault(claimValue, claimValue)));
                break;
            }
        }
    }
    return claimsCollection;
}
Also used : Attribute(org.opensaml.saml.saml2.core.Attribute) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement)

Example 10 with Statement

use of org.opensaml.saml.saml2.core.Statement in project ddf by codice.

the class LogoutRequestService method sendLogoutRequest.

@GET
@Path("/request")
public Response sendLogoutRequest(@QueryParam("EncryptedNameIdTime") String encryptedNameIdTime) {
    String nameIdTime = encryptionService.decrypt(encryptedNameIdTime);
    String[] nameIdTimeArray = StringUtils.split(nameIdTime, "\n");
    if (nameIdTimeArray.length == 2) {
        try {
            String name = nameIdTimeArray[0];
            long time = Long.parseLong(nameIdTimeArray[1]);
            if (System.currentTimeMillis() - time > logOutPageTimeOut) {
                String msg = String.format("Logout request was older than %sms old so it was rejected. Please refresh page and request again.", logOutPageTimeOut);
                LOGGER.info(msg);
                return buildLogoutResponse(msg);
            }
            Element idpSecToken = getIdpSecurityToken();
            if (idpSecToken == null) {
                LOGGER.info("Unable to logout. Please try again.");
                return buildLogoutResponse("Unable to logout. Please try again.");
            }
            // Logout removes the SAML assertion. This statement must be called before the SAML
            // assertion is removed.
            List<String> sessionIndexes = new SecurityAssertionSaml(idpSecToken).getAuthnStatements().stream().filter(Objects::nonNull).map(AuthenticationStatement::getSessionIndex).collect(Collectors.toList());
            logout();
            if (logoutMessage == null) {
                LOGGER.info("Logout message not available yet");
                return buildLogoutResponse(UNABLE_TO_CREATE_LOGOUT_REQUEST);
            }
            LogoutWrapper<LogoutRequest> logoutRequest = logoutMessage.buildLogoutRequest(name, getEntityId(), sessionIndexes);
            String relayState = relayStates.encode(name);
            return getLogoutRequest(relayState, logoutRequest);
        } catch (RuntimeException e) {
            LOGGER.info(UNABLE_TO_CREATE_LOGOUT_REQUEST, e);
            return buildLogoutResponse(UNABLE_TO_CREATE_LOGOUT_REQUEST);
        }
    } else {
        LOGGER.info(UNABLE_TO_DECRYPT_LOGOUT_REQUEST);
        return buildLogoutResponse(UNABLE_TO_DECRYPT_LOGOUT_REQUEST);
    }
}
Also used : Element(org.w3c.dom.Element) Objects(java.util.Objects) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) SecurityAssertionSaml(ddf.security.assertion.saml.impl.SecurityAssertionSaml) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)19 Attribute (org.opensaml.saml.saml2.core.Attribute)10 Assertion (org.opensaml.saml.saml2.core.Assertion)8 Map (java.util.Map)7 Test (org.junit.jupiter.api.Test)6 XMLObject (org.opensaml.core.xml.XMLObject)6 AuthnStatement (org.opensaml.saml.saml2.core.AuthnStatement)6 List (java.util.List)5 lombok.val (lombok.val)5 SamlProfileBuilderContext (org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileBuilderContext)5 SamlProfileObjectBuilder (org.apereo.cas.support.saml.web.idp.profile.builders.SamlProfileObjectBuilder)5 NameIDType (org.opensaml.saml.saml2.core.NameIDType)5 UUID (java.util.UUID)4 BaseSamlIdPConfigurationTests (org.apereo.cas.support.saml.BaseSamlIdPConfigurationTests)4 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)4 Assertions (org.junit.jupiter.api.Assertions)4 Tag (org.junit.jupiter.api.Tag)4 SAMLConstants (org.opensaml.saml.common.xml.SAMLConstants)4 Autowired (org.springframework.beans.factory.annotation.Autowired)4 Qualifier (org.springframework.beans.factory.annotation.Qualifier)4