Java Code Examples for org.opensaml.core.xml.XMLObject

The following examples show how to use org.opensaml.core.xml.XMLObject. These examples are extracted from open source projects. 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
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
@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 3
/**
 * 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 4
Source Project: centraldogma   Source File: SamlAuthSsoHandler.java    License: 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 5
/**
 * 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 6
/**
 * `
 * 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 Project: saml-client   Source File: SamlClient.java    License: 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 8
Source Project: armeria   Source File: SamlMessageUtil.java    License: 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 9
Source Project: carbon-apimgt   Source File: Util.java    License: 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 10
Source Project: carbon-apimgt   Source File: Util.java    License: 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 11
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());
        }
    }
}
 
Example 12
/**
 * Create XMLObject from a given QName
 *
 * @param objectQName: QName of the object to be built into a XMLObject
 * @return built xmlObject
 * @throws EntitlementException
 */
private static XMLObject buildXMLObject(QName objectQName) throws EntitlementException {

    XMLObjectBuilder builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(objectQName);
    if (builder == null) {
        throw new EntitlementException("Unable to retrieve builder for object QName "
                + objectQName);
    }
    return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(),
            objectQName.getPrefix());
}
 
Example 13
Source Project: saml-client   Source File: SamlClient.java    License: MIT License 5 votes vote down vote up
private StringWriter marshallXmlObject(XMLObject object) throws MarshallingException {
  StringWriter stringWriter = new StringWriter();
  Marshaller marshaller =
      XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object);
  Element dom = marshaller.marshall(object);
  XMLHelper.writeNode(dom, stringWriter);

  return stringWriter;
}
 
Example 14
Source Project: armeria   Source File: SamlMessageUtil.java    License: Apache License 2.0 5 votes vote down vote up
static XMLObject deserialize(byte[] bytes) {
    requireNonNull(bytes, "bytes");
    final ParserPool parserPool = XMLObjectProviderRegistrySupport.getParserPool();
    assert parserPool != null;

    final InputStream is = new ByteArrayInputStream(bytes);
    try {
        return XMLObjectSupport.unmarshallFromInputStream(parserPool, is);
    } catch (XMLParserException | UnmarshallingException e) {
        throw new InvalidSamlRequestException(
                "failed to deserialize an XML document bytes into a SAML object", e);
    }
}
 
Example 15
Source Project: syncope   Source File: SAML2ReaderWriter.java    License: 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 16
Source Project: syncope   Source File: SAML2ReaderWriter.java    License: 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 17
Source Project: carbon-apimgt   Source File: Util.java    License: 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 18
Source Project: carbon-apimgt   Source File: Util.java    License: 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 19
Source Project: carbon-apimgt   Source File: Util.java    License: 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 20
Source Project: carbon-apimgt   Source File: SAMLSSORelyingPartyObject.java    License: 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 21
Source Project: carbon-apimgt   Source File: SAMLSSORelyingPartyObject.java    License: 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 22
Source Project: carbon-apimgt   Source File: SAMLSSORelyingPartyObject.java    License: 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 23
Source Project: carbon-apimgt   Source File: TokenMgtUtil.java    License: 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 24
Source Project: carbon-apimgt   Source File: SAMLGroupIDExtractorImpl.java    License: 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 25
Source Project: carbon-apimgt   Source File: SAMLGroupIDExtractorImpl.java    License: 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 26
Source Project: carbon-apimgt   Source File: APIKeyMgtUtil.java    License: 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 27
Source Project: cxf   Source File: ActAsValidator.java    License: 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 28
Source Project: cxf   Source File: ClaimsValidator.java    License: 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 29
Source Project: cxf   Source File: ClaimsValidator.java    License: 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 30
Source Project: cxf   Source File: StaxClaimsValidator.java    License: 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;
}