org.opensaml.core.xml.XMLObject Java Examples

The following examples show how to use org.opensaml.core.xml.XMLObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 7 votes vote down vote up
private String marshallSamlXml(XMLObject xmlObject) {
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        Marshaller out = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(xmlObject);
        out.marshall(xmlObject, document);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(document);
        StringWriter stringWriter = new StringWriter();

        transformer.transform(source, new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (ParserConfigurationException | MarshallingException | TransformerFactoryConfigurationError
            | TransformerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: Util.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Serializing a SAML2 object into a String
 *
 * @param xmlObject object that needs to serialized.
 * @return serialized object
 * @throws Exception
 */
public static String marshall(XMLObject xmlObject) throws Exception {
    try {
        doBootstrap();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStrm);
        writer.write(element, output);
        return byteArrayOutputStrm.toString();
    } catch (Exception e) {
        throw new Exception("Error Serializing the SAML Response", e);
    }
}
 
Example #3
Source File: Util.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Constructing the XMLObject Object from a String
 *
 * @param authReqStr
 * @return Corresponding XMLObject which is a SAML2 object
 * @throws Exception
 */
public static XMLObject unmarshall(String authReqStr) throws Exception {
    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = getSecuredDocumentBuilder();
        documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setIgnoringComments(true);
        Document document = getDocument(documentBuilderFactory, authReqStr);
        if (isSignedWithComments(document)) {
            documentBuilderFactory.setIgnoringComments(false);
            document = getDocument(documentBuilderFactory, authReqStr);
        }
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (Exception e) {
        throw new Exception("Error in constructing AuthRequest from " +
                "the encoded String ", e);
    }
}
 
Example #4
Source File: SamlMessageUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
static Element serialize(XMLObject message) {
    requireNonNull(message, "message");

    if (message.getDOM() != null) {
        // Return cached DOM if it exists.
        return message.getDOM();
    }

    final Marshaller marshaller =
            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(message);
    if (marshaller == null) {
        throw new SamlException("failed to serialize a SAML object into an XML document, " +
                                "no serializer registered for message object: " +
                                message.getElementQName());
    }

    try {
        return marshaller.marshall(message);
    } catch (MarshallingException e) {
        throw new SamlException("failed to serialize a SAML object into an XML document", e);
    }
}
 
Example #5
Source File: SamlClient.java    From saml-client with MIT License 6 votes vote down vote up
/**
 * Gets attributes from the IDP Response
 *
 * @param response the response
 * @return the attributes
 */
public static Map<String, String> getAttributes(SamlResponse response) {
  HashMap<String, String> map = new HashMap<>();
  if (response == null) {
    return map;
  }
  List<AttributeStatement> attributeStatements = response.getAssertion().getAttributeStatements();
  if (attributeStatements == null) {
    return map;
  }

  for (AttributeStatement statement : attributeStatements) {
    for (Attribute attribute : statement.getAttributes()) {
      XMLObject xmlObject = attribute.getAttributeValues().get(0);
      if (xmlObject instanceof XSStringImpl) {
        map.put(attribute.getName(), ((XSStringImpl) xmlObject).getValue());
      } else {
        map.put(attribute.getName(), ((XSAnyImpl) xmlObject).getTextContent());
      }
    }
  }
  return map;
}
 
Example #6
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * `
 * Serialize XML objects
 *
 * @param xmlObject : XACML or SAML objects to be serialized
 * @return serialized XACML or SAML objects
 * @throws EntitlementException
 */
private String marshall(XMLObject xmlObject) throws EntitlementException {

    try {
        doBootstrap();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        Marshaller marshaller = marshallerFactory.getMarshaller(xmlObject);
        Element element = marshaller.marshall(xmlObject);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
        DOMImplementationLS impl =
                (DOMImplementationLS) registry.getDOMImplementation("LS");
        LSSerializer writer = impl.createLSSerializer();
        LSOutput output = impl.createLSOutput();
        output.setByteStream(byteArrayOutputStream);
        writer.write(element, output);
        return byteArrayOutputStream.toString();
    } catch (Exception e) {
        log.error("Error Serializing the SAML Response");
        throw new EntitlementException("Error Serializing the SAML Response", e);
    }
}
 
Example #7
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Constructing the SAML or XACML Objects from a String
 *
 * @param xmlString Decoded SAML or XACML String
 * @return SAML or XACML Object
 * @throws org.wso2.carbon.identity.entitlement.EntitlementException
 */
public XMLObject unmarshall(String xmlString) throws EntitlementException {

    try {
        doBootstrap();
        DocumentBuilderFactory documentBuilderFactory = IdentityUtil.getSecuredDocumentBuilderFactory();

        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = docBuilder.parse(new ByteArrayInputStream(xmlString.trim().getBytes()));
        Element element = document.getDocumentElement();
        UnmarshallerFactory unmarshallerFactory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
        return unmarshaller.unmarshall(element);
    } catch (Exception e) {
        log.error("Error in constructing XML(SAML or XACML) Object from the encoded String", e);
        throw new EntitlementException("Error in constructing XML(SAML or XACML) from the encoded String ", e);
    }
}
 
Example #8
Source File: CasHTTPSOAP11Encoder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Override
protected void buildAndStoreSOAPMessage(final XMLObject payload) {
    final XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory();

    final SOAPObjectBuilder<Envelope> envBuilder =
            (SOAPObjectBuilder<Envelope>) builderFactory.getBuilder(Envelope.DEFAULT_ELEMENT_NAME);
    final Envelope envelope = envBuilder.buildObject(
            SOAPConstants.SOAP11_NS, Envelope.DEFAULT_ELEMENT_LOCAL_NAME, OPENSAML_11_SOAP_NS_PREFIX);

    final SOAPObjectBuilder<Body> bodyBuilder =
            (SOAPObjectBuilder<Body>) builderFactory.getBuilder(Body.DEFAULT_ELEMENT_NAME);
    final Body body = bodyBuilder.buildObject(
            SOAPConstants.SOAP11_NS, Body.DEFAULT_ELEMENT_LOCAL_NAME, OPENSAML_11_SOAP_NS_PREFIX);

    if(!body.getUnknownXMLObjects().isEmpty()) {
        LOGGER.warn("Existing SOAP Envelope Body already contained children");
    }

    body.getUnknownXMLObjects().add(payload);
    envelope.setBody(body);
    this.storeSOAPEnvelope(envelope);
}
 
Example #9
Source File: SamlAuthSsoHandler.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Nullable
private String findLoginNameFromAttributes(Response response) {
    if (Strings.isNullOrEmpty(attributeLoginName)) {
        return null;
    }
    return response.getAssertions()
                   .stream()
                   .flatMap(s -> s.getAttributeStatements().stream())
                   .flatMap(s -> s.getAttributes().stream())
                   .filter(attr -> attr.getName().equals(attributeLoginName))
                   .findFirst()
                   .map(attr -> {
                       final XMLObject v = attr.getAttributeValues().get(0);
                       if (v instanceof XSString) {
                           return ((XSString) v).getValue();
                       } else {
                           return null;
                       }
                   })
                   .orElse(null);
}
 
Example #10
Source File: AbstractSamlObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Marshal the saml xml object to raw xml.
 *
 * @param object the object
 * @param writer the writer
 * @return the xml string
 */
public String marshalSamlXmlObject(final XMLObject object, final StringWriter writer)  {
    try {
        final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
        final Marshaller marshaller = marshallerFactory.getMarshaller(object);
        if (marshaller == null) {
            throw new IllegalArgumentException("Cannot obtain marshaller for object " + object.getElementQName());
        }
        final Element element = marshaller.marshall(object);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SAMLConstants.SAML20_NS);
        element.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");

        final TransformerFactory transFactory = TransformerFactory.newInstance();
        final Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(element), new StreamResult(writer));
        return writer.toString();
    } catch (final Exception e) {
        throw new IllegalStateException("An error has occurred while marshalling SAML object to xml", e);
    }
}
 
Example #11
Source File: SAMLGroupIDExtractorImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get the organization list from the SAML2 Assertion
 *
 * @param assertions SAML2 assertions returned in SAML response
 * @return Organization list from the assertion
 */
private String getOrganizationFromSamlAssertion(List<Assertion> assertions) {
    List<String> attributeValueArray = new ArrayList<>();
    String organizationAttributeName = getOrganizationClaim();

    for (Assertion assertion : assertions) {
        List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();
        if (attributeStatementList != null) {
            for (AttributeStatement statement : attributeStatementList) {
                List<Attribute> attributesList = statement.getAttributes();
                for (Attribute attribute : attributesList) {
                    String attributeName = attribute.getName();
                    if (organizationAttributeName.equals(attributeName)) {
                        List<XMLObject> attributeValues = attribute.getAttributeValues();
                        if (attributeValues != null) {
                            for (XMLObject attributeValue : attributeValues) {
                                attributeValueArray.add(getAttributeValue(attributeValue));
                            }
                        }
                    }
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Organization list found in assertion: " + attributeValueArray);
    }

    return String.join(",", attributeValueArray);
}
 
Example #12
Source File: ClaimsManager.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected List<ProcessedClaim> parseClaimsInAssertion(org.opensaml.saml.saml2.core.Assertion assertion) {
    List<org.opensaml.saml.saml2.core.AttributeStatement> attributeStatements =
        assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.finest("No attribute statements found");
        }
        return Collections.emptyList();
    }

    List<ProcessedClaim> collection = new ArrayList<>();

    for (org.opensaml.saml.saml2.core.AttributeStatement statement : attributeStatements) {
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.finest("parsing statement: " + statement.getElementQName());
        }
        List<org.opensaml.saml.saml2.core.Attribute> attributes = statement.getAttributes();
        for (org.opensaml.saml.saml2.core.Attribute attribute : attributes) {
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.finest("parsing attribute: " + attribute.getName());
            }
            ProcessedClaim c = new ProcessedClaim();
            c.setClaimType(URI.create(attribute.getName()));
            c.setIssuer(assertion.getIssuer().getNameQualifier());
            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String value = attributeValueElement.getTextContent();
                if (LOG.isLoggable(Level.FINEST)) {
                    LOG.finest(" [" + value + "]");
                }
                c.addValue(value);
            }
            collection.add(c);
        }
    }
    return collection;

}
 
Example #13
Source File: Util.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public static String getDomainName(XMLObject samlObject) {
    NodeList list = samlObject.getDOM().getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "NameID");
    String domainName = null;
    if (list.getLength() > 0) {
        String userName = list.item(0).getTextContent();
        domainName = MultitenantUtils.getTenantDomain(userName);
    }
    return domainName;
}
 
Example #14
Source File: Util.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Assertion
 *
 * @param assertion SAML2 assertion
 * @return username
 */
public static String getUsernameFromAssertion(Assertion assertion, String usernameAttribute) {
    String username = null;
    if (!StringUtils.isEmpty(usernameAttribute)) {
        // There can be multiple AttributeStatements in Assertion
        List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
        if (attributeStatements != null) {
            for (AttributeStatement attributeStatement : attributeStatements) {
                // There can be multiple Attributes in an attributeStatement
                List<Attribute> attributes = attributeStatement.getAttributes();
                if (attributes != null) {
                    for (Attribute attribute : attributes) {
                        String attributeName = attribute.getDOM().getAttribute(SSOConstants.SAML_NAME_ATTRIBUTE);
                        if (attributeName.equals(usernameAttribute)) {
                            List<XMLObject> attributeValues = attribute.getAttributeValues();
                            // There can be multiple attribute values in an attribute, but get the first one
                            username = attributeValues.get(0).getDOM().getTextContent();
                            if (log.isDebugEnabled()) {
                                log.debug("Name of authenticated user from SAML response : " + username);
                            }
                        }
                    }
                }
            }
        }
    } else {
        Subject subject = assertion.getSubject();
        if (subject != null) {
            if (subject.getNameID() != null) {
                username = subject.getNameID().getValue();
                if (log.isDebugEnabled()) {
                    log.debug("Name of authenticated user from SAML response : " + username);
                }
            }
        }
    }
    return username;
}
 
Example #15
Source File: SAMLSSORelyingPartyObject.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * @param cx
 * @param thisObj
 * @param args    -args[0]-Logout request xml as a string.
 * @param funObj
 * @return
 * @throws Exception
 */
public static boolean jsFunction_isLogoutRequest(Context cx, Scriptable thisObj, Object[] args,
                                                 Function funObj)
        throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. Logout request xml is missing.");
    }

    SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;
    String encoded = getSSOSamlEncodingProperty(relyingPartyObject);
    boolean isEncoded = true;
    if (encoded != null) {
        try {
            isEncoded = Boolean.parseBoolean(encoded);
        } catch (Exception e) {
            throw new ScriptException("Invalid property value found for " +
                    "" + SSOConstants.SAML_ENCODED + " " + encoded);
        }
    }

    String logoutRequest = StringEscapeUtils.unescapeXml((String) args[0]);
    String decodedString = isEncoded ? Util.decode(logoutRequest) : logoutRequest;
    XMLObject samlObject = Util.unmarshall(decodedString);
    if (log.isDebugEnabled() && samlObject instanceof LogoutRequest) {
        log.debug("Request is a logout request and request is " + args[0]);
    }

    return samlObject instanceof LogoutRequest;

}
 
Example #16
Source File: SAMLSSORelyingPartyObject.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * @param cx
 * @param thisObj
 * @param args-args[0]- Logout response xml as a string
 * @param funObj
 * @return
 * @throws Exception
 */
public static boolean jsFunction_isLogoutResponse(Context cx, Scriptable thisObj, Object[] args,
                                                  Function funObj)
        throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. Logout response xml is missing.");
    }

    SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;
    String encoded = getSSOSamlEncodingProperty(relyingPartyObject);
    boolean isEncoded = true;
    if (encoded != null) {
        try {
            isEncoded = Boolean.parseBoolean(encoded);
        } catch (Exception e) {
            throw new ScriptException("Invalid property value found for " +
                    "" + SSOConstants.SAML_ENCODED + " " + encoded);
        }
    }

    String decodedString = isEncoded ? Util.decode((String) args[0]) : (String) args[0];
    XMLObject samlObject = Util.unmarshall(decodedString);
    if (log.isDebugEnabled() && samlObject instanceof LogoutResponse) {
        log.debug("Response is a logout response and response is " + args[0]);
    }
    return samlObject instanceof LogoutResponse;

}
 
Example #17
Source File: SAMLSSORelyingPartyObject.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Checking whether the response is for passiveAuth SAML request or not.
 *
 * @param cx
 * @param thisObj
 * @param args    - args[0] response for passiveAuth required as XML
 * @param funObj
 * @return
 * @throws Exception
 */

public static boolean jsFunction_isPassiveAuthResponse(Context cx, Scriptable thisObj, Object[] args,
                                                       Function funObj) throws Exception {
    int argLength = args.length;
    if (argLength != 1 || !(args[0] instanceof String)) {
        throw new ScriptException("Invalid argument. Logout response xml is missing.");
    }

    SAMLSSORelyingPartyObject relyingPartyObject = (SAMLSSORelyingPartyObject) thisObj;
    String encoded = getSSOSamlEncodingProperty(relyingPartyObject);
    boolean isEncoded = true;
    if (encoded != null) {
        try {
            isEncoded = Boolean.parseBoolean(encoded);
        } catch (Exception e) {
            throw new ScriptException("Invalid property value found for " +
                    "" + SSOConstants.SAML_ENCODED + " " + encoded);
        }
    }

    String decodedString = isEncoded ? Util.decode((String) args[0]) : (String) args[0];
    XMLObject samlObject = Util.unmarshall(decodedString);

    if (samlObject instanceof Response) {
        Response samlResponse = (Response) samlObject;

        if (samlResponse.getStatus() != null &&
                samlResponse.getStatus().getStatusCode() != null &&
                samlResponse.getStatus().getStatusCode().getValue().equals("urn:oasis:names:tc:SAML:2.0:status:Responder") &&
                samlResponse.getStatus().getStatusCode().getStatusCode() != null &&
                samlResponse.getStatus().getStatusCode().getStatusCode().getValue().equals("urn:oasis:names:tc:SAML:2.0:status:NoPassive")) {
            return true;
        }

    }
    return false;

}
 
Example #18
Source File: TokenMgtUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static String getAttributeValue(XMLObject attributeValue) {
    if (attributeValue == null){
        return null;
    } else if (attributeValue instanceof XSString){
        return getStringAttributeValue((XSString) attributeValue);
    } else if(attributeValue instanceof XSAnyImpl){
        return getAnyAttributeValue((XSAnyImpl) attributeValue);
    } else {
        return attributeValue.toString();
    }
}
 
Example #19
Source File: ClaimsValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean handleSAML2Assertion(
    org.opensaml.saml.saml2.core.Assertion assertion
) throws WSSecurityException {
    List<org.opensaml.saml.saml2.core.AttributeStatement> attributeStatements =
        assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    for (org.opensaml.saml.saml2.core.AttributeStatement statement : attributeStatements) {
        List<org.opensaml.saml.saml2.core.Attribute> attributes = statement.getAttributes();
        for (org.opensaml.saml.saml2.core.Attribute attribute : attributes) {
            if (!attribute.getName().startsWith(ClaimTypes.URI_BASE.toString())) {
                continue;
            }

            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String text = attributeValueElement.getTextContent();
                if (!"admin-user".equals(text)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #20
Source File: SAMLGroupIDExtractorImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get the String value from XMLObject
 *
 * @param attributeValue XMLObject of attribute value recived in SAML Assertion     *
 * @return attribute value as a String
 */
private String getAttributeValue(XMLObject attributeValue) {
    if (attributeValue == null){
        return null;
    } else if (attributeValue instanceof XSString){
        return getStringAttributeValue((XSString) attributeValue);
    } else if(attributeValue instanceof XSAnyImpl){
        return getAnyAttributeValue((XSAnyImpl) attributeValue);
    } else {
        return attributeValue.toString();
    }
}
 
Example #21
Source File: APIKeyMgtUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static String getAttributeValue(XMLObject attributeValue) {
    if (attributeValue == null){
        return null;
    } else if (attributeValue instanceof XSString){
        return getStringAttributeValue((XSString) attributeValue);
    } else if(attributeValue instanceof XSAnyImpl){
        return getAnyAttributeValue((XSAnyImpl) attributeValue);
    } else {
        return attributeValue.toString();
    }
}
 
Example #22
Source File: ActAsValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    Assertion saml2Assertion = assertion.getSaml2();
    if (saml2Assertion == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // The technical user should be in the Subject
    Subject subject = saml2Assertion.getSubject();
    if (subject == null || subject.getNameID() == null
        || !subject.getNameID().getValue().contains("www.client.com")) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    for (AttributeStatement statement : attributeStatements) {
        List<Attribute> attributes = statement.getAttributes();
        for (Attribute attribute : attributes) {
            if (!"CustomActAs".equals(attribute.getName()) && !"ActAs".equals(attribute.getName())) {
                continue;
            }
            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String text = attributeValueElement.getTextContent();
                if (text.contains("alice") || text.contains("bob")) {
                    return validatedCredential;
                }
            }
        }
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example #23
Source File: ClaimsValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean handleSAML1Assertion(
    org.opensaml.saml.saml1.core.Assertion assertion
) throws WSSecurityException {
    List<org.opensaml.saml.saml1.core.AttributeStatement> attributeStatements =
        assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    for (org.opensaml.saml.saml1.core.AttributeStatement statement : attributeStatements) {
        List<org.opensaml.saml.saml1.core.Attribute> attributes = statement.getAttributes();
        for (org.opensaml.saml.saml1.core.Attribute attribute : attributes) {

            if (!ClaimTypes.URI_BASE.toString().equals(attribute.getAttributeNamespace())) {
                continue;
            }

            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String text = attributeValueElement.getTextContent();
                if (!"admin-user".equals(text)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #24
Source File: StaxClaimsValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean handleSAML2Assertion(
    org.opensaml.saml.saml2.core.Assertion assertion
) throws WSSecurityException {
    List<org.opensaml.saml.saml2.core.AttributeStatement> attributeStatements =
        assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    for (org.opensaml.saml.saml2.core.AttributeStatement statement : attributeStatements) {
        List<org.opensaml.saml.saml2.core.Attribute> attributes = statement.getAttributes();
        for (org.opensaml.saml.saml2.core.Attribute attribute : attributes) {
            if (!attribute.getName().startsWith(ClaimTypes.URI_BASE.toString())) {
                continue;
            }

            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String text = attributeValueElement.getTextContent();
                if (!"admin-user".equals(text)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #25
Source File: StaxClaimsValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean handleSAML1Assertion(
    org.opensaml.saml.saml1.core.Assertion assertion
) throws WSSecurityException {
    List<org.opensaml.saml.saml1.core.AttributeStatement> attributeStatements =
        assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    for (org.opensaml.saml.saml1.core.AttributeStatement statement : attributeStatements) {
        List<org.opensaml.saml.saml1.core.Attribute> attributes = statement.getAttributes();
        for (org.opensaml.saml.saml1.core.Attribute attribute : attributes) {

            if (!ClaimTypes.URI_BASE.toString().equals(attribute.getAttributeNamespace())) {
                continue;
            }

            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String text = attributeValueElement.getTextContent();
                if (!"admin-user".equals(text)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #26
Source File: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static XMLObject read(final boolean useDeflateEncoding, final String response)
        throws DataFormatException, UnsupportedEncodingException, XMLStreamException, WSSecurityException {

    InputStream tokenStream;
    byte[] deflatedToken = Base64.getDecoder().decode(response);
    tokenStream = useDeflateEncoding
            ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
            : new ByteArrayInputStream(deflatedToken);

    // parse the provided SAML response
    Document responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, StandardCharsets.UTF_8));
    XMLObject responseObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());

    if (LOG.isDebugEnabled()) {
        try {
            StringWriter writer = new StringWriter();
            write(writer, responseObject, false);
            writer.close();

            LOG.debug("Parsed SAML response: {}", writer.toString());
        } catch (Exception e) {
            LOG.error("Could not log the received SAML response", e);
        }
    }

    return responseObject;
}
 
Example #27
Source File: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static void write(final Writer writer, final XMLObject object, final boolean signObject)
        throws TransformerConfigurationException, WSSecurityException, TransformerException {

    Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
    StreamResult streamResult = new StreamResult(writer);
    DOMSource source = new DOMSource(OpenSAMLUtil.toDom(object, null, signObject));
    transformer.transform(source, streamResult);
}
 
Example #28
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a SAML2 Assertion with StaticClaimsHandler
 */
@org.junit.Test
public void testSaml2StaticClaims() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    StaticClaimsHandler claimsHandler = new StaticClaimsHandler();
    Map<String, String> staticClaimsMap = new HashMap<>();
    staticClaimsMap.put(CLAIM_STATIC_COMPANY, CLAIM_STATIC_COMPANY_VALUE);
    claimsHandler.setGlobalClaims(staticClaimsMap);
    claimsManager.setClaimHandlers(Collections.singletonList((ClaimsHandler)claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(CLAIM_STATIC_COMPANY);
    claims.add(claim);
    providerParameters.setRequestedPrimaryClaims(claims);

    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));

    SamlAssertionWrapper assertion = new SamlAssertionWrapper(token);
    List<Attribute> attributes = assertion.getSaml2().getAttributeStatements().get(0).getAttributes();
    assertEquals(attributes.size(), 1);
    assertEquals(attributes.get(0).getName(), CLAIM_STATIC_COMPANY);
    XMLObject valueObj = attributes.get(0).getAttributeValues().get(0);
    assertEquals(valueObj.getDOM().getTextContent(), CLAIM_STATIC_COMPANY_VALUE);
}
 
Example #29
Source File: Util.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Builds an xml object with the given QName
 *
 * @param objectQName QName object
 * @return built XML object
 * @throws SSOHostObjectException
 */
public static XMLObject buildXMLObject(QName objectQName)
        throws SSOHostObjectException {

    XMLObjectBuilder builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(objectQName);
    if (builder == null) {
        throw new SSOHostObjectException("Unable to retrieve builder for object QName "
                + objectQName);
    }
    return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(),
            objectQName.getPrefix());
}
 
Example #30
Source File: ConsumerServlet.java    From OpenSAML-ref-project-demo-v3 with Apache License 2.0 5 votes vote down vote up
private void logAssertionAttributes(Assertion assertion) {
    for (Attribute attribute : assertion.getAttributeStatements().get(0).getAttributes()) {
        logger.info("Attribute name: " + attribute.getName());
        for (XMLObject attributeValue : attribute.getAttributeValues()) {
            logger.info("Attribute value: " + ((XSString) attributeValue).getValue());
        }
    }
}