Search in sources :

Example 61 with Attribute

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

the class SamlIdPSaml2AttributeQueryProfileHandlerController method handlePostRequest.

/**
 * Handle post request.
 *
 * @param response the response
 * @param request  the request
 * @throws Exception the exception
 */
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SOAP_ATTRIBUTE_QUERY)
protected void handlePostRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
    val enabled = configurationContext.getCasProperties().getAuthn().getSamlIdp().getCore().isAttributeQueryProfileEnabled();
    if (!enabled) {
        LOGGER.warn("SAML2 attribute query profile is not enabled");
        response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
        return;
    }
    val ctx = decodeSoapRequest(request);
    val query = (AttributeQuery) ctx.getMessage();
    try {
        val issuer = Objects.requireNonNull(query).getIssuer().getValue();
        val registeredService = verifySamlRegisteredService(issuer);
        val adaptor = getSamlMetadataFacadeFor(registeredService, query);
        val facade = adaptor.orElseThrow(() -> new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer));
        verifyAuthenticationContextSignature(ctx, request, query, facade, registeredService);
        val nameIdValue = determineNameIdForQuery(query, registeredService, facade);
        val factory = (SamlAttributeQueryTicketFactory) getConfigurationContext().getTicketFactory().get(SamlAttributeQueryTicket.class);
        val id = factory.createTicketIdFor(nameIdValue, facade.getEntityId());
        LOGGER.debug("Created ticket id for attribute query [{}]", id);
        val ticket = getConfigurationContext().getTicketRegistry().getTicket(id, SamlAttributeQueryTicket.class);
        if (ticket == null || ticket.isExpired()) {
            LOGGER.warn("Attribute query ticket [{}] has either expired, or it is linked to " + "a single sign-on session that is no longer valid and has now expired", id);
            throw new InvalidTicketException(id);
        }
        val authentication = ticket.getAuthentication();
        val principal = resolvePrincipalForAttributeQuery(authentication, registeredService);
        val releasePolicyContext = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(ticket.getService()).principal(principal).build();
        val principalAttributes = registeredService.getAttributeReleasePolicy().getConsentableAttributes(releasePolicyContext);
        LOGGER.debug("Initial consentable principal attributes are [{}]", principalAttributes);
        val authenticationAttributes = getConfigurationContext().getAuthenticationAttributeReleasePolicy().getAuthenticationAttributesForRelease(authentication, null, Map.of(), registeredService);
        val finalAttributes = CollectionUtils.merge(principalAttributes, authenticationAttributes);
        val principalId = registeredService.getUsernameAttributeProvider().resolveUsername(authentication.getPrincipal(), ticket.getService(), registeredService);
        LOGGER.debug("Principal id used for attribute query response should be [{}]", principalId);
        LOGGER.debug("Final attributes to be processed for the SAML2 response are [{}]", finalAttributes);
        val casAssertion = buildCasAssertion(principalId, registeredService, finalAttributes);
        request.setAttribute(AttributeQuery.class.getSimpleName(), query);
        val buildContext = SamlProfileBuilderContext.builder().samlRequest(query).httpRequest(request).httpResponse(response).authenticatedAssertion(casAssertion).registeredService(registeredService).adaptor(facade).binding(SAMLConstants.SAML2_SOAP11_BINDING_URI).messageContext(ctx).build();
        getConfigurationContext().getResponseBuilder().build(buildContext);
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, "Unable to build SOAP response: " + StringUtils.defaultString(e.getMessage()));
        val buildContext = SamlProfileBuilderContext.builder().samlRequest(query).httpRequest(request).httpResponse(response).binding(SAMLConstants.SAML2_SOAP11_BINDING_URI).messageContext(ctx).build();
        getConfigurationContext().getSamlFaultResponseBuilder().build(buildContext);
    }
}
Also used : lombok.val(lombok.val) SamlAttributeQueryTicketFactory(org.apereo.cas.ticket.query.SamlAttributeQueryTicketFactory) SamlAttributeQueryTicket(org.apereo.cas.ticket.query.SamlAttributeQueryTicket) AttributeQuery(org.opensaml.saml.saml2.core.AttributeQuery) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 62 with Attribute

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

the class SamlProfileSamlNameIdBuilder method encodeNameIdBasedOnNameFormat.

/**
 * Encode name id based on name format name id.
 *
 * @param context    the context
 * @param nameFormat the name format
 * @return the name id
 */
protected NameID encodeNameIdBasedOnNameFormat(final SamlProfileBuilderContext context, final String nameFormat) {
    try {
        val attribute = prepareNameIdAttribute(context, nameFormat);
        val encoder = SamlAttributeBasedNameIdGenerator.get(Optional.of(context.getSamlRequest()), nameFormat, context.getRegisteredService(), attribute);
        context.getHttpRequest().setAttribute(NameID.class.getName(), attribute);
        LOGGER.debug("Encoding NameID based on [{}]", nameFormat);
        val prc = new ProfileRequestContext();
        val nameId = Objects.requireNonNull(encoder.generate(prc, nameFormat));
        LOGGER.debug("Final NameID encoded with format [{}] has value [{}]", nameId.getFormat(), nameId.getValue());
        return nameId;
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
    }
    return null;
}
Also used : lombok.val(lombok.val) NameID(org.opensaml.saml.saml2.core.NameID) ProfileRequestContext(org.opensaml.profile.context.ProfileRequestContext) SamlException(org.apereo.cas.support.saml.SamlException)

Example 63 with Attribute

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

the class AbstractSamlObjectBuilder method newAttributeValue.

/**
 * New attribute value.
 *
 * @param value       the value
 * @param valueType   the value type
 * @param elementName the element name
 * @return the xS string
 */
protected XMLObject newAttributeValue(final Object value, final String valueType, final QName elementName) {
    LOGGER.trace("Creating new attribute value XMLObject for value: [{}], value type: [{}], QName: [{}]", value, valueType, elementName);
    if (value instanceof NameIDType) {
        LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, value);
        ((NameIDType) value).detach();
        return (NameIDType) value;
    }
    if (XSString.class.getSimpleName().equalsIgnoreCase(valueType)) {
        val builder = new XSStringBuilder();
        val attrValueObj = builder.buildObject(elementName, XSString.TYPE_NAME);
        attrValueObj.setValue(value.toString());
        LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
        return attrValueObj;
    }
    if (XSURI.class.getSimpleName().equalsIgnoreCase(valueType)) {
        val builder = new XSURIBuilder();
        val attrValueObj = builder.buildObject(elementName, XSURI.TYPE_NAME);
        attrValueObj.setURI(value.toString());
        LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
        return attrValueObj;
    }
    if (XSBoolean.class.getSimpleName().equalsIgnoreCase(valueType)) {
        val builder = new XSBooleanBuilder();
        val attrValueObj = builder.buildObject(elementName, XSBoolean.TYPE_NAME);
        attrValueObj.setValue(XSBooleanValue.valueOf(value.toString().toLowerCase()));
        LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
        return attrValueObj;
    }
    if (XSInteger.class.getSimpleName().equalsIgnoreCase(valueType)) {
        val builder = new XSIntegerBuilder();
        val attrValueObj = builder.buildObject(elementName, XSInteger.TYPE_NAME);
        attrValueObj.setValue(Integer.valueOf(value.toString()));
        LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
        return attrValueObj;
    }
    if (XSDateTime.class.getSimpleName().equalsIgnoreCase(valueType)) {
        val builder = new XSDateTimeBuilder();
        val attrValueObj = builder.buildObject(elementName, XSDateTime.TYPE_NAME);
        attrValueObj.setValue(ZonedDateTime.parse(value.toString()).toInstant());
        LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
        return attrValueObj;
    }
    if (XSBase64Binary.class.getSimpleName().equalsIgnoreCase(valueType)) {
        val builder = new XSBase64BinaryBuilder();
        val attrValueObj = builder.buildObject(elementName, XSBase64Binary.TYPE_NAME);
        attrValueObj.setValue(value.toString());
        LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
        return attrValueObj;
    }
    if (XSObject.class.getSimpleName().equalsIgnoreCase(valueType)) {
        val mapper = new JacksonXmlSerializer();
        val builder = new XSAnyBuilder();
        val attrValueObj = builder.buildObject(elementName);
        attrValueObj.setTextContent(mapper.writeValueAsString(value));
        LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
        return attrValueObj;
    }
    val builder = new XSAnyBuilder();
    val attrValueObj = builder.buildObject(elementName);
    attrValueObj.setTextContent(value.toString());
    LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
    return attrValueObj;
}
Also used : lombok.val(lombok.val) XSBase64BinaryBuilder(org.opensaml.core.xml.schema.impl.XSBase64BinaryBuilder) XSBooleanBuilder(org.opensaml.core.xml.schema.impl.XSBooleanBuilder) XSIntegerBuilder(org.opensaml.core.xml.schema.impl.XSIntegerBuilder) XSBase64Binary(org.opensaml.core.xml.schema.XSBase64Binary) XSAnyBuilder(org.opensaml.core.xml.schema.impl.XSAnyBuilder) XSObject(org.apache.xerces.xs.XSObject) XSString(org.opensaml.core.xml.schema.XSString) XSStringBuilder(org.opensaml.core.xml.schema.impl.XSStringBuilder) XSURI(org.opensaml.core.xml.schema.XSURI) XSDateTime(org.opensaml.core.xml.schema.XSDateTime) XSDateTimeBuilder(org.opensaml.core.xml.schema.impl.XSDateTimeBuilder) XSBoolean(org.opensaml.core.xml.schema.XSBoolean) XSInteger(org.opensaml.core.xml.schema.XSInteger) JacksonXmlSerializer(org.apereo.cas.util.serialization.JacksonXmlSerializer) NameIDType(org.opensaml.saml.saml2.core.NameIDType) XSURIBuilder(org.opensaml.core.xml.schema.impl.XSURIBuilder)

Example 64 with Attribute

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

the class WsFederationHelper method createCredentialFromToken.

/**
 * createCredentialFromToken converts a SAML 1.1 assertion to a WSFederationCredential.
 *
 * @param assertion the provided assertion
 * @return an equivalent credential.
 */
public WsFederationCredential createCredentialFromToken(final Assertion assertion) {
    val retrievedOn = ZonedDateTime.now(clock);
    LOGGER.trace("Retrieved on [{}]", retrievedOn);
    val credential = new WsFederationCredential();
    credential.setRetrievedOn(retrievedOn);
    credential.setId(assertion.getID());
    credential.setIssuer(assertion.getIssuer());
    credential.setIssuedOn(DateTimeUtils.zonedDateTimeOf(assertion.getIssueInstant()));
    val conditions = assertion.getConditions();
    if (conditions != null) {
        credential.setNotBefore(DateTimeUtils.zonedDateTimeOf(conditions.getNotBefore()));
        credential.setNotOnOrAfter(DateTimeUtils.zonedDateTimeOf(conditions.getNotOnOrAfter()));
        if (!conditions.getAudienceRestrictionConditions().isEmpty()) {
            credential.setAudience(conditions.getAudienceRestrictionConditions().get(0).getAudiences().get(0).getURI());
        }
    }
    if (!assertion.getAuthenticationStatements().isEmpty()) {
        credential.setAuthenticationMethod(assertion.getAuthenticationStatements().get(0).getAuthenticationMethod());
    }
    val attributes = new HashMap<String, List<Object>>();
    assertion.getAttributeStatements().stream().flatMap(attributeStatement -> attributeStatement.getAttributes().stream()).forEach(item -> {
        LOGGER.trace("Processed attribute: [{}]", item.getAttributeName());
        final List<Object> itemList = item.getAttributeValues().stream().map(xmlObject -> ((XSAny) xmlObject).getTextContent()).collect(Collectors.toList());
        if (!itemList.isEmpty()) {
            attributes.put(item.getAttributeName(), itemList);
        }
    });
    credential.setAttributes(attributes);
    LOGGER.debug("WsFederation Credential retrieved as: [{}]", credential);
    return credential;
}
Also used : lombok.val(lombok.val) WsFederationCertificateProvider(org.apereo.cas.support.wsfederation.authentication.crypto.WsFederationCertificateProvider) XSAny(org.opensaml.core.xml.schema.XSAny) ChainingEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver) ExplicitKeySignatureTrustEngine(org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine) SneakyThrows(lombok.SneakyThrows) Assertion(org.opensaml.saml.saml1.core.Assertion) ZonedDateTime(java.time.ZonedDateTime) RequiredArgsConstructor(lombok.RequiredArgsConstructor) StaticCredentialResolver(org.opensaml.security.credential.impl.StaticCredentialResolver) Security(java.security.Security) StringUtils(org.apache.commons.lang3.StringUtils) SamlUtils(org.apereo.cas.support.saml.SamlUtils) LoggingUtils(org.apereo.cas.util.LoggingUtils) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) Pair(org.apache.commons.lang3.tuple.Pair) StaticKeyInfoCredentialResolver(org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver) ByteArrayInputStream(java.io.ByteArrayInputStream) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) Unchecked(org.jooq.lambda.Unchecked) UsageType(org.opensaml.security.credential.UsageType) DateTimeUtils(org.apereo.cas.util.DateTimeUtils) PEMParser(org.bouncycastle.openssl.PEMParser) Collection(java.util.Collection) ProtocolCriterion(org.opensaml.saml.criterion.ProtocolCriterion) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) RequestedSecurityToken(org.opensaml.soap.wsfed.RequestedSecurityToken) EncryptedData(org.opensaml.xmlsec.encryption.EncryptedData) EncryptedElementTypeEncryptedKeyResolver(org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver) EncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.EncryptedKeyResolver) Setter(lombok.Setter) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) UsageCriterion(org.opensaml.security.criteria.UsageCriterion) RegisteredServiceProperty(org.apereo.cas.services.RegisteredServiceProperty) RegisteredServiceAccessStrategyUtils(org.apereo.cas.services.RegisteredServiceAccessStrategyUtils) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Decrypter(org.opensaml.saml.saml2.encryption.Decrypter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) X509CertParser(org.bouncycastle.jce.provider.X509CertParser) SAMLSignatureProfileValidator(org.opensaml.saml.security.impl.SAMLSignatureProfileValidator) Predicates(com.google.common.base.Predicates) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) XMLObject(org.opensaml.core.xml.XMLObject) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) SignatureTrustEngine(org.opensaml.xmlsec.signature.support.SignatureTrustEngine) ServicesManager(org.apereo.cas.services.ServicesManager) InlineEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver) RequestSecurityTokenResponse(org.opensaml.soap.wsfed.RequestSecurityTokenResponse) Credential(org.opensaml.security.credential.Credential) lombok.val(lombok.val) InputStreamReader(java.io.InputStreamReader) RegexUtils(org.apereo.cas.util.RegexUtils) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Service(org.apereo.cas.authentication.principal.Service) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) Clock(java.time.Clock) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) BufferedReader(java.io.BufferedReader) SimpleRetrievalMethodEncryptedKeyResolver(org.opensaml.xmlsec.encryption.support.SimpleRetrievalMethodEncryptedKeyResolver) HashMap(java.util.HashMap) XMLObject(org.opensaml.core.xml.XMLObject) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) XSAny(org.opensaml.core.xml.schema.XSAny)

Example 65 with Attribute

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

the class MetadataRequestedAttributesAttributeReleasePolicy method fetchRequestedAttributes.

private Map<String, List<Object>> fetchRequestedAttributes(final Map<String, List<Object>> attributes, final RegisteredServiceAttributeReleasePolicyContext context, final SamlRegisteredServiceServiceProviderMetadataFacade facade) {
    val releaseAttributes = new HashMap<String, List<Object>>();
    Optional.ofNullable(facade.getSsoDescriptor()).ifPresent(sso -> sso.getAttributeConsumingServices().forEach(svc -> svc.getRequestedAttributes().stream().filter(attr -> {
        val name = this.useFriendlyName ? attr.getFriendlyName() : attr.getName();
        LOGGER.debug("Checking for requested attribute [{}] in metadata for [{}]", name, context.getRegisteredService().getName());
        return attributes.containsKey(name);
    }).forEach(attr -> {
        val name = this.useFriendlyName ? attr.getFriendlyName() : attr.getName();
        LOGGER.debug("Found requested attribute [{}] in metadata for [{}]", name, context.getRegisteredService().getName());
        releaseAttributes.put(name, attributes.get(name));
    })));
    return releaseAttributes;
}
Also used : lombok.val(lombok.val) Setter(lombok.Setter) RegisteredServiceAttributeReleasePolicyContext(org.apereo.cas.services.RegisteredServiceAttributeReleasePolicyContext) Getter(lombok.Getter) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) lombok.val(lombok.val) HashMap(java.util.HashMap) EqualsAndHashCode(lombok.EqualsAndHashCode) ApplicationContext(org.springframework.context.ApplicationContext) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Map(java.util.Map) ToString(lombok.ToString) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) Optional(java.util.Optional) AllArgsConstructor(lombok.AllArgsConstructor) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) NoArgsConstructor(lombok.NoArgsConstructor) HashMap(java.util.HashMap)

Aggregations

Attribute (org.opensaml.saml.saml2.core.Attribute)63 AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)44 Test (org.junit.jupiter.api.Test)27 Assertion (org.opensaml.saml.saml2.core.Assertion)23 List (java.util.List)18 XMLObject (org.opensaml.core.xml.XMLObject)18 lombok.val (lombok.val)15 AttributeBuilder (org.opensaml.saml.saml2.core.impl.AttributeBuilder)13 Map (java.util.Map)12 EncryptedAttribute (org.opensaml.saml.saml2.core.EncryptedAttribute)12 ArrayList (java.util.ArrayList)11 HashMap (java.util.HashMap)11 XSString (org.opensaml.core.xml.schema.XSString)11 NameID (org.opensaml.saml.saml2.core.NameID)10 Slf4j (lombok.extern.slf4j.Slf4j)9 SimpleStringAttributeBuilder.aSimpleStringAttribute (uk.gov.ida.saml.core.test.builders.SimpleStringAttributeBuilder.aSimpleStringAttribute)9 Element (org.w3c.dom.Element)8 SamlTransformationErrorFactory.emptyAttribute (uk.gov.ida.saml.core.errors.SamlTransformationErrorFactory.emptyAttribute)8 Issuer (org.opensaml.saml.saml2.core.Issuer)7 AttributeStatementLogData (uk.gov.ida.hub.samlengine.logging.data.AttributeStatementLogData)7