Search in sources :

Example 36 with XMLObject

use of org.opensaml.core.xml.XMLObject in project cas by apereo.

the class Saml2ClientMetadataController method getSaml2ClientIdentityProviderMetadataResponseEntity.

private ResponseEntity<String> getSaml2ClientIdentityProviderMetadataResponseEntity(final SAML2Client saml2Client) {
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_XML);
    saml2Client.getIdentityProviderMetadataResolver().resolve();
    final XMLObject entity = saml2Client.getIdentityProviderMetadataResolver().getEntityDescriptorElement();
    final String metadata = SamlUtils.transformSamlObject(openSamlConfigBean, entity).toString();
    return new ResponseEntity<>(metadata, headers, HttpStatus.OK);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) XMLObject(org.opensaml.core.xml.XMLObject)

Example 37 with XMLObject

use of org.opensaml.core.xml.XMLObject in project cas by apereo.

the class SamlUtils method transformSamlObject.

/**
 * Transform saml object t.
 *
 * @param <T>        the type parameter
 * @param configBean the config bean
 * @param xml        the xml
 * @param clazz      the clazz
 * @return the t
 */
public static <T extends XMLObject> T transformSamlObject(final OpenSamlConfigBean configBean, final String xml, final Class<T> clazz) {
    try (InputStream in = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8))) {
        final Document document = configBean.getParserPool().parse(in);
        final Element root = document.getDocumentElement();
        final Unmarshaller marshaller = configBean.getUnmarshallerFactory().getUnmarshaller(root);
        if (marshaller != null) {
            final Object result = marshaller.unmarshall(root);
            if (!clazz.isAssignableFrom(result.getClass())) {
                throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz);
            }
            return (T) result;
        }
    } catch (final Exception e) {
        throw new SamlException(e.getMessage(), e);
    }
    return null;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) XMLObject(org.opensaml.core.xml.XMLObject) Document(org.w3c.dom.Document) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller)

Example 38 with XMLObject

use of org.opensaml.core.xml.XMLObject in project verify-hub by alphagov.

the class EidasAttributeQueryRequestBuilder method build.

public EidasAttributeQueryRequestDto build() {
    XmlObjectToBase64EncodedStringTransformer<XMLObject> toBase64EncodedStringTransformer = new XmlObjectToBase64EncodedStringTransformer<>();
    EncryptedAssertion encryptedIdentityAssertion = AssertionBuilder.anAssertion().withId(UUID.randomUUID().toString()).build();
    String encryptedIdentityAssertionString = toBase64EncodedStringTransformer.apply(encryptedIdentityAssertion);
    return anEidasAttributeQueryRequestDto().withEncryptedIdentityAssertion(encryptedIdentityAssertionString).build();
}
Also used : EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) XMLObject(org.opensaml.core.xml.XMLObject) XmlObjectToBase64EncodedStringTransformer(uk.gov.ida.saml.serializers.XmlObjectToBase64EncodedStringTransformer)

Example 39 with XMLObject

use of org.opensaml.core.xml.XMLObject in project pac4j by pac4j.

the class SAML2DefaultResponseValidator method validateSamlProtocolResponse.

/**
 * Validates the SAML protocol response:
 * - IssueInstant
 * - Issuer
 * - StatusCode
 * - Signature
 *
 * @param response the response
 * @param context  the context
 * @param engine   the engine
 */
protected final void validateSamlProtocolResponse(final Response response, final SAML2MessageContext context, final SignatureTrustEngine engine) {
    if (!StatusCode.SUCCESS.equals(response.getStatus().getStatusCode().getValue())) {
        String status = response.getStatus().getStatusCode().getValue();
        if (response.getStatus().getStatusMessage() != null) {
            status += " / " + response.getStatus().getStatusMessage().getMessage();
        }
        throw new SAMLException("Authentication response is not success ; actual " + status);
    }
    if (response.getSignature() != null) {
        final String entityId = context.getSAMLPeerEntityContext().getEntityId();
        validateSignature(response.getSignature(), entityId, engine);
        context.getSAMLPeerEntityContext().setAuthenticated(true);
    }
    if (!isIssueInstantValid(response.getIssueInstant())) {
        throw new SAMLIssueInstantException("Response issue instant is too old or in the future");
    }
    AuthnRequest request = null;
    final SAMLMessageStorage messageStorage = context.getSAMLMessageStorage();
    if (messageStorage != null && response.getInResponseTo() != null) {
        final XMLObject xmlObject = messageStorage.retrieveMessage(response.getInResponseTo());
        if (xmlObject == null) {
            throw new SAMLInResponseToMismatchException("InResponseToField of the Response doesn't correspond to sent message " + response.getInResponseTo());
        } else if (xmlObject instanceof AuthnRequest) {
            request = (AuthnRequest) xmlObject;
        } else {
            throw new SAMLInResponseToMismatchException("Sent request was of different type than the expected AuthnRequest " + response.getInResponseTo());
        }
    }
    verifyEndpoint(context.getSAMLEndpointContext().getEndpoint(), response.getDestination());
    if (request != null) {
        verifyRequest(request, context);
    }
    if (response.getIssuer() != null) {
        validateIssuer(response.getIssuer(), context);
    }
}
Also used : SAMLInResponseToMismatchException(org.pac4j.saml.exceptions.SAMLInResponseToMismatchException) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) XMLObject(org.opensaml.core.xml.XMLObject) SAMLIssueInstantException(org.pac4j.saml.exceptions.SAMLIssueInstantException) SAMLMessageStorage(org.pac4j.saml.storage.SAMLMessageStorage) SAMLException(org.pac4j.saml.exceptions.SAMLException)

Example 40 with XMLObject

use of org.opensaml.core.xml.XMLObject in project pac4j by pac4j.

the class SAML2Authenticator method validate.

@Override
public void validate(final SAML2Credentials credentials, final WebContext context) {
    init();
    final SAML2Profile profile = getProfileDefinition().newProfile();
    final NameID nameId = credentials.getNameId();
    profile.setId(nameId.getValue());
    profile.addAttribute(SESSION_INDEX, credentials.getSessionIndex());
    profile.addAuthenticationAttribute(SAML_NAME_ID_FORMAT, nameId.getFormat());
    profile.addAuthenticationAttribute(SAML_NAME_ID_NAME_QUALIFIER, nameId.getNameQualifier());
    profile.addAuthenticationAttribute(SAML_NAME_ID_SP_NAME_QUALIFIER, nameId.getSPNameQualifier());
    profile.addAuthenticationAttribute(SAML_NAME_ID_SP_PROVIDED_ID, nameId.getSPProvidedID());
    for (final Attribute attribute : credentials.getAttributes()) {
        logger.debug("Processing profile attribute {}", attribute);
        final String name = attribute.getName();
        final String friendlyName = attribute.getFriendlyName();
        final List<String> values = new ArrayList<>();
        for (final XMLObject attributeValue : attribute.getAttributeValues()) {
            final Element attributeValueElement = attributeValue.getDOM();
            if (attributeValueElement != null) {
                final String value = attributeValueElement.getTextContent();
                logger.debug("Adding attribute value {} for attribute {} / {}", value, name, friendlyName);
                values.add(value);
            } else {
                logger.warn("Attribute value DOM element is null for {}", attribute);
            }
        }
        if (!values.isEmpty()) {
            getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, name, values);
            if (CommonHelper.isNotBlank(friendlyName)) {
                getProfileDefinition().convertAndAdd(profile, PROFILE_ATTRIBUTE, friendlyName, values);
            }
        } else {
            logger.debug("No attribute values found for {}", name);
        }
    }
    // Add in issuerID and authnContexts
    profile.addAuthenticationAttribute(ISSUER_ID, credentials.getIssuerId());
    profile.addAuthenticationAttribute(AUTHN_CONTEXT, credentials.getAuthnContexts());
    // Retrieve conditions attributes
    // Adding them to both the "regular" and authentication attributes so we don't break anyone currently using it.
    Conditions conditions = credentials.getConditions();
    if (conditions != null) {
        profile.addAttribute(SAML_CONDITION_NOT_BEFORE_ATTRIBUTE, conditions.getNotBefore());
        profile.addAuthenticationAttribute(SAML_CONDITION_NOT_BEFORE_ATTRIBUTE, conditions.getNotBefore());
        profile.addAttribute(SAML_CONDITION_NOT_ON_OR_AFTER_ATTRIBUTE, conditions.getNotOnOrAfter());
        profile.addAuthenticationAttribute(SAML_CONDITION_NOT_ON_OR_AFTER_ATTRIBUTE, conditions.getNotOnOrAfter());
    }
    credentials.setUserProfile(profile);
}
Also used : NameID(org.opensaml.saml.saml2.core.NameID) Attribute(org.opensaml.saml.saml2.core.Attribute) SAML2Profile(org.pac4j.saml.profile.SAML2Profile) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) XMLObject(org.opensaml.core.xml.XMLObject) Conditions(org.opensaml.saml.saml2.core.Conditions)

Aggregations

XMLObject (org.opensaml.core.xml.XMLObject)68 Element (org.w3c.dom.Element)27 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)21 Document (org.w3c.dom.Document)21 ByteArrayInputStream (java.io.ByteArrayInputStream)19 Attribute (org.opensaml.saml.saml2.core.Attribute)14 AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)10 IOException (java.io.IOException)9 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)9 ArrayList (java.util.ArrayList)8 Test (org.junit.Test)8 XSString (org.opensaml.core.xml.schema.XSString)7 Assertion (org.opensaml.saml.saml2.core.Assertion)7 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)7 HashMap (java.util.HashMap)6 List (java.util.List)6 XMLStreamException (javax.xml.stream.XMLStreamException)6 InputStream (java.io.InputStream)5 InputStreamReader (java.io.InputStreamReader)5 LogoutSecurityException (ddf.security.samlp.LogoutSecurityException)4