org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport Java Examples

The following examples show how to use org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport. 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: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
public String handleSsoGetRequestBase(HttpRequest request) {
    try {

        HttpServletRequest httpServletRequest = new FakeHttpServletRequest(request);

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();
        decoder.setParserPool(XMLObjectProviderRegistrySupport.getParserPool());
        decoder.setHttpServletRequest(httpServletRequest);
        decoder.initialize();
        decoder.decode();

        MessageContext<SAMLObject> messageContext = decoder.getMessageContext();

        if (!(messageContext.getMessage() instanceof AuthnRequest)) {
            throw new RuntimeException("Expected AuthnRequest; received: " + messageContext.getMessage());
        }

        AuthnRequest authnRequest = (AuthnRequest) messageContext.getMessage();

        return createSamlAuthResponse(authnRequest);
    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: AuthnRequestFactory.java    From verify-service-provider with MIT License 6 votes vote down vote up
public AuthnRequest build(String serviceEntityId) {
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setID(String.format("_%s", UUID.randomUUID()));
    authnRequest.setIssueInstant(DateTime.now());
    authnRequest.setForceAuthn(false);
    authnRequest.setDestination(destination.toString());
    authnRequest.setExtensions(createExtensions());

    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(serviceEntityId);
    authnRequest.setIssuer(issuer);

    authnRequest.setSignature(createSignature());

    try {
        XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(authnRequest).marshall(authnRequest);
        Signer.signObject(authnRequest.getSignature());
    } catch (SignatureException | MarshallingException e) {
        throw new SAMLRuntimeException("Unknown problem while signing SAML object", e);
    }

    return authnRequest;
}
 
Example #9
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 #10
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 #11
Source File: SamlResponseHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
public static Attribute createVerifiedAttribute(String name, boolean value) {
    Attribute attribute = new OpenSamlXmlObjectFactory().createAttribute();
    attribute.setName(name);

    XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory();
    Verified verifiedValue = (Verified) builderFactory.getBuilder(Verified.TYPE_NAME).buildObject(Verified.DEFAULT_ELEMENT_NAME, Verified.TYPE_NAME);
    verifiedValue.setValue(value);

    attribute.getAttributeValues().add(verifiedValue);

    return attribute;
}
 
Example #12
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 #13
Source File: SamlClient.java    From saml-client with MIT License 5 votes vote down vote up
private SAMLObject parseResponse(String encodedResponse, String method) throws SamlException {
  logger.trace("Validating SAML response " + encodedResponse);
  try {
    Document responseDocument = domParser.parse(decodeAndInflate(encodedResponse, method));
    return (SAMLObject)
        XMLObjectProviderRegistrySupport.getUnmarshallerFactory()
            .getUnmarshaller(responseDocument.getDocumentElement())
            .unmarshall(responseDocument.getDocumentElement());
  } catch (UnmarshallingException | XMLParserException ex) {
    throw new SamlException("Cannot decode xml encoded response", ex);
  }
}
 
Example #14
Source File: SamlClient.java    From saml-client with 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 #15
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #16
Source File: WSXACMLMessageReceiver.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Create the issuer object to be added
 *
 * @return : the issuer of the statements
 */
private static Issuer createIssuer() {

    IssuerBuilder issuer = (IssuerBuilder) XMLObjectProviderRegistrySupport.getBuilderFactory().
            getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    Issuer issuerObject = issuer.buildObject();
    issuerObject.setValue("https://identity.carbon.wso2.org");
    issuerObject.setSPProvidedID("SPPProvierId");
    return issuerObject;
}
 
Example #17
Source File: AbstractOpenSamlTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Test
public void loadStaticContextFactories() {
    assertNotNull(XMLObjectProviderRegistrySupport.getParserPool());
    assertNotNull(XMLObjectProviderRegistrySupport.getBuilderFactory());
    assertNotNull(XMLObjectProviderRegistrySupport.getMarshallerFactory());
    assertNotNull(XMLObjectProviderRegistrySupport.getUnmarshallerFactory());
}
 
Example #18
Source File: CustomClaimsHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public ProcessedClaimCollection retrieveClaimValues(
        ClaimCollection claims, ClaimsParameters parameters) {

    if (claims != null && !claims.isEmpty()) {
        ProcessedClaimCollection claimCollection = new ProcessedClaimCollection();
        for (Claim requestClaim : claims) {
            ProcessedClaim claim = new ProcessedClaim();
            claim.setClaimType(requestClaim.getClaimType());
            claim.setIssuer("Test Issuer");
            claim.setOriginalIssuer("Original Issuer");
            if (ROLE.equals(requestClaim.getClaimType())) {
                claim.addValue("admin-user");
            } else if (GIVEN_NAME.equals(requestClaim.getClaimType())) {
                claim.addValue(parameters.getPrincipal().getName());
            } else if (NUMBER.equals(requestClaim.getClaimType())) {
                // Create and add a custom Attribute (Integer)
                OpenSAMLUtil.initSamlEngine();
                XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory();

                @SuppressWarnings("unchecked")
                XMLObjectBuilder<XSInteger> xsIntegerBuilder =
                    (XMLObjectBuilder<XSInteger>)builderFactory.getBuilder(XSInteger.TYPE_NAME);
                XSInteger attributeValue =
                    xsIntegerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME);
                attributeValue.setValue(5);

                claim.addValue(attributeValue);
            }
            claimCollection.add(claim);
        }
        return claimCollection;
    }
    return null;
}
 
Example #19
Source File: AbstractSamlObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Create a new SAML object.
 *
 * @param <T> the generic type
 * @param objectType the object type
 * @return the t
 */
public final <T extends SAMLObject> T newSamlObject(final Class<T> objectType) {
    final QName qName = getSamlObjectQName(objectType);
    final SAMLObjectBuilder<T> builder = (SAMLObjectBuilder<T>)
            XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName);
    if (builder == null) {
        throw new IllegalStateException("No SAMLObjectBuilder registered for class " + objectType.getName());
    }
    return objectType.cast(builder.buildObject(qName));
}
 
Example #20
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> T createSamlElement(final Class<T> clazz) {
    try {
        XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory();

        QName defaultElementName = (QName) clazz.getDeclaredField("DEFAULT_ELEMENT_NAME").get(null);

        return (T) builderFactory.getBuilder(defaultElementName).buildObject(defaultElementName);
    } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException | SecurityException e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createSamlAuthResponse(AuthnRequest authnRequest) {
    try {
        Response response = createSamlElement(Response.class);
        response.setID(nextId());

        if (authnRequest != null) {
            response.setInResponseTo(authnRequest.getID());
        }

        response.setVersion(SAMLVersion.VERSION_20);
        response.setStatus(createStatus(StatusCode.SUCCESS));
        response.setIssueInstant(new DateTime());

        Assertion assertion = createSamlElement(Assertion.class);
        response.getAssertions().add(assertion);

        assertion.setID(nextId());
        assertion.setIssueInstant(new DateTime());
        assertion.setIssuer(createIssuer());

        AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
        assertion.getAuthnStatements().add(authnStatement);

        authnStatement.setAuthnInstant(new DateTime());
        authnStatement.setSessionIndex(nextId());
        authnStatement.setAuthnContext(createAuthnCotext());

        Subject subject = createSamlElement(Subject.class);
        assertion.setSubject(subject);

        subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));

        if (authnRequest != null) {
            subject.getSubjectConfirmations()
                    .add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                            new DateTime().plusMinutes(1), authnRequest.getID(),
                            authnRequest.getAssertionConsumerServiceURL()));
        } else {
            subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                    new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
        }

        Conditions conditions = createSamlElement(Conditions.class);
        assertion.setConditions(conditions);

        conditions.setNotBefore(new DateTime());
        conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));

        if (authenticateUserRoles != null) {
            AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
            assertion.getAttributeStatements().add(attributeStatement);

            Attribute attribute = createSamlElement(Attribute.class);
            attributeStatement.getAttributes().add(attribute);

            attribute.setName("roles");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            for (String role : authenticateUserRoles) {
                attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
            }
        }

        if (signResponses) {
            Signature signature = createSamlElement(Signature.class);
            assertion.setSignature(signature);

            signature.setSigningCredential(this.signingCredential);
            signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
            signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);

            Signer.signObject(signature);
        }

        String marshalledXml = marshallSamlXml(response);

        return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);

    } catch (MarshallingException | SignatureException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: DummyPDP.java    From cxf with Apache License 2.0 4 votes vote down vote up
private ResponseType createResponse(DECISION decision) {
    XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory();

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<ResponseType> responseTypeBuilder =
        (XACMLObjectBuilder<ResponseType>)
        builderFactory.getBuilder(ResponseType.DEFAULT_ELEMENT_NAME);

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<ResultType> resultTypeBuilder =
        (XACMLObjectBuilder<ResultType>)
        builderFactory.getBuilder(ResultType.DEFAULT_ELEMENT_NAME);

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<DecisionType> decisionTypeBuilder =
        (XACMLObjectBuilder<DecisionType>)
        builderFactory.getBuilder(DecisionType.DEFAULT_ELEMENT_NAME);

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<StatusType> statusTypeBuilder =
        (XACMLObjectBuilder<StatusType>)
        builderFactory.getBuilder(StatusType.DEFAULT_ELEMENT_NAME);

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<StatusCodeType> statusCodeTypeBuilder =
        (XACMLObjectBuilder<StatusCodeType>)
        builderFactory.getBuilder(StatusCodeType.DEFAULT_ELEMENT_NAME);

    ResultType result = resultTypeBuilder.buildObject();

    DecisionType decisionType = decisionTypeBuilder.buildObject();
    decisionType.setDecision(decision);
    result.setDecision(decisionType);

    StatusType status = statusTypeBuilder.buildObject();
    StatusCodeType statusCode = statusCodeTypeBuilder.buildObject();
    statusCode.setValue("urn:oasis:names:tc:xacml:1.0:status:ok");
    status.setStatusCode(statusCode);
    result.setStatus(status);

    ResponseType response = responseTypeBuilder.buildObject();
    response.getResults().add(result);
    return response;
}
 
Example #23
Source File: PolicyDecisionPointMockImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public ResponseType evaluate(RequestType requestType) {

    XMLObjectBuilderFactory builderFactory =
        XMLObjectProviderRegistrySupport.getBuilderFactory();

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<ResponseType> responseTypeBuilder =
        (XACMLObjectBuilder<ResponseType>)
        builderFactory.getBuilder(ResponseType.DEFAULT_ELEMENT_NAME);

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<ResultType> resultTypeBuilder =
        (XACMLObjectBuilder<ResultType>)
        builderFactory.getBuilder(ResultType.DEFAULT_ELEMENT_NAME);

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<DecisionType> decisionTypeBuilder =
        (XACMLObjectBuilder<DecisionType>)
        builderFactory.getBuilder(DecisionType.DEFAULT_ELEMENT_NAME);

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<StatusType> statusTypeBuilder =
        (XACMLObjectBuilder<StatusType>)
        builderFactory.getBuilder(StatusType.DEFAULT_ELEMENT_NAME);

    @SuppressWarnings("unchecked")
    XACMLObjectBuilder<StatusCodeType> statusCodeTypeBuilder =
        (XACMLObjectBuilder<StatusCodeType>)
        builderFactory.getBuilder(StatusCodeType.DEFAULT_ELEMENT_NAME);

    DecisionType decisionType = decisionTypeBuilder.buildObject();

    String role = getSubjectRole(requestType);
    if ("manager".equals(role)) {
        decisionType.setDecision(DecisionType.DECISION.Permit);
    } else {
        decisionType.setDecision(DecisionType.DECISION.Deny);
    }

    ResultType result = resultTypeBuilder.buildObject();
    result.setDecision(decisionType);

    StatusType status = statusTypeBuilder.buildObject();
    StatusCodeType statusCode = statusCodeTypeBuilder.buildObject();
    statusCode.setValue("urn:oasis:names:tc:xacml:1.0:status:ok");
    status.setStatusCode(statusCode);
    result.setStatus(status);

    ResponseType response = responseTypeBuilder.buildObject();
    response.getResults().add(result);

    return response;
}
 
Example #24
Source File: CustomClaimsHandler.java    From cxf with Apache License 2.0 4 votes vote down vote up
public ProcessedClaimCollection retrieveClaimValues(
        ClaimCollection claims, ClaimsParameters parameters) {

    if (claims != null && !claims.isEmpty()) {
        ProcessedClaimCollection claimCollection = new ProcessedClaimCollection();
        for (Claim requestClaim : claims) {
            ProcessedClaim claim = new ProcessedClaim();
            claim.setClaimType(requestClaim.getClaimType());
            if (ClaimTypes.FIRSTNAME.toString().equals(requestClaim.getClaimType())) {
                if (requestClaim instanceof CustomRequestClaim) {
                    CustomRequestClaim customClaim = (CustomRequestClaim) requestClaim;
                    String customName = customClaim.getValues().get(0) + "@"
                        + customClaim.getScope();
                    claim.addValue(customName);
                } else {
                    claim.addValue("alice");
                }
            } else if (ClaimTypes.LASTNAME.toString().equals(requestClaim.getClaimType())) {
                claim.addValue("doe");
            } else if (ClaimTypes.EMAILADDRESS.toString().equals(requestClaim.getClaimType())) {
                claim.addValue("[email protected]");
            } else if (ClaimTypes.STREETADDRESS.toString().equals(requestClaim.getClaimType())) {
                claim.addValue("1234 1st Street");
            } else if (ClaimTypes.MOBILEPHONE.toString().equals(requestClaim.getClaimType())) {
                // Test custom (Integer) attribute value
                XMLObjectBuilderFactory builderFactory =
                    XMLObjectProviderRegistrySupport.getBuilderFactory();

                @SuppressWarnings("unchecked")
                XMLObjectBuilder<XSInteger> xsIntegerBuilder =
                    (XMLObjectBuilder<XSInteger>)builderFactory.getBuilder(XSInteger.TYPE_NAME);
                XSInteger attributeValue =
                    xsIntegerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME);
                attributeValue.setValue(185912592);

                claim.addValue(attributeValue);

            } else if (ROLE_CLAIM.equals(requestClaim.getClaimType())) {
                if (requestClaim.getValues().size() > 0) {
                    for (Object requestedRole : requestClaim.getValues()) {
                        if (isUserInRole(parameters.getPrincipal(), requestedRole.toString())) {
                            claim.addValue(requestedRole);
                        }
                    }
                    if (claim.getValues().isEmpty()) {
                        continue;
                    }
                } else {
                    // If no specific role was requested return DUMMY role for user
                    claim.addValue(role);
                }
            }
            claimCollection.add(claim);
        }
        return claimCollection;
    }

    return null;
}
 
Example #25
Source File: SAMLGroupIDExtractorImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void getGroupingIdentifierListTestCase() throws ParserConfigurationException, IOException, SAXException,
        UnmarshallingException, UserStoreException {

    String claim = "http://wso2.org/claims/organization";
    String organizationValue = "organization";
    SAMLGroupIDExtractorImpl samlGroupIDExtractor = new SAMLGroupIDExtractorImplWrapper();
    Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(documentBuilderFactory);
    Mockito.when(documentBuilderFactory.newDocumentBuilder()).
            thenReturn(documentBuilder);
    Mockito.when(documentBuilder.parse(samlGroupIDExtractor.getByteArrayInputStream("test"))).
            thenReturn(document);
    Mockito.when(document.getDocumentElement()).thenReturn(element);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(XMLObjectProviderRegistrySupport.class);
    Response response = Mockito.mock(Response.class);
    List<Assertion> assertion = new ArrayList();
    Subject subject = Mockito.mock(Subject.class);
    NameID nameID = Mockito.mock(NameID.class);
    Assertion assertion1 = Mockito.mock(Assertion.class);
    assertion.add(assertion1);
    Mockito.when(XMLObjectProviderRegistrySupport.getUnmarshallerFactory()).thenReturn(unmarshallerFactory);
    Mockito.when(unmarshallerFactory.getUnmarshaller(element)).thenReturn(unmarshaller);
    Mockito.when(unmarshaller.unmarshall(element)).thenReturn(response);
    Mockito.when(response.getAssertions()).thenReturn(assertion);
    Mockito.when(assertion.get(0).getSubject()).thenReturn(subject);
    Mockito.when(subject.getNameID()).thenReturn(nameID);
    Mockito.when(nameID.getValue()).thenReturn("user");
    System.setProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION, "true");
    APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
    APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
    Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).
            thenReturn("http://wso2.org/claims/organization");

    System.setProperty("carbon.home", "");
    PrivilegedCarbonContext carbonContext;
    carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);

    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()).thenReturn(-1234);
    PowerMockito.doNothing().when(carbonContext).setTenantDomain("carbon.super", true);

    AttributeStatement mockAttributeStatement = PowerMockito.mock(AttributeStatement.class);
    List<AttributeStatement> attributeStatementList = Collections.singletonList(mockAttributeStatement);
    PowerMockito.when(assertion1.getAttributeStatements()).thenReturn(attributeStatementList);

    Attribute mockAttribute = PowerMockito.mock(Attribute.class);
    List<Attribute> attributesList = Collections.singletonList(mockAttribute);
    PowerMockito.when(mockAttributeStatement.getAttributes()).thenReturn(attributesList);

    XMLObject rawAttribute = PowerMockito.mock(XMLObject.class);
    PowerMockito.when(rawAttribute.toString()).thenReturn(organizationValue);
    List<XMLObject> mockedAttributeValues = Collections.singletonList(rawAttribute);
    AttributedStringImpl mockedAttributedStringImpl = new AttributedStringImpl("nameSpaceURI", "elementLocalName",
            "namespacePrefix");
    String sampleAttrValue = "MockedAuthParamSampleAttribute";
    mockedAttributedStringImpl.setValue(sampleAttrValue);
    List<XMLObject> mockedXSSAttributeValues = Collections.singletonList((XMLObject) mockedAttributedStringImpl);
    XSAnyImpl mockedXSAnyImpl = Mockito.mock(XSAnyImpl.class);
    PowerMockito.when(mockedXSAnyImpl.getTextContent()).thenReturn(sampleAttrValue);
    List<XMLObject> mockedXSAnyImplAttributeValues = Collections.singletonList((XMLObject) mockedXSAnyImpl);
    List<XMLObject> multiMockedAttributeValues = Arrays.asList(rawAttribute, PowerMockito.mock(XMLObject.class));
    AuthenticatorsConfiguration.AuthenticatorConfig mockedAuthenticatorConfig = Mockito
            .mock(AuthenticatorsConfiguration.AuthenticatorConfig.class);
    PowerMockito.when(mockAttribute.getAttributeValues())
            .thenReturn(mockedAttributeValues, multiMockedAttributeValues, mockedXSSAttributeValues,
                    mockedXSAnyImplAttributeValues);

    PowerMockito.mockStatic(AuthenticatorsConfiguration.class);
    AuthenticatorsConfiguration mockedAuthenticatorsConfiguration = PowerMockito
            .mock(AuthenticatorsConfiguration.class);
    PowerMockito.when(AuthenticatorsConfiguration.getInstance()).thenReturn(mockedAuthenticatorsConfiguration);
    Map<String, String> mockedConfigParameters = new HashMap<String, String>();
    mockedConfigParameters.put(APIConstants.ORGANIZATION_CLAIM_ATTRIBUTE, claim);
    PowerMockito.when(mockedAuthenticatorConfig.getParameters()).thenReturn(mockedConfigParameters);
    PowerMockito.when(mockedAuthenticatorsConfiguration
            .getAuthenticatorConfig(APIConstants.SAML2_SSO_AUTHENTICATOR_NAME))
            .thenReturn(mockedAuthenticatorConfig);
    PowerMockito.when(mockAttribute.getName()).thenReturn(claim);

    String[] organizations = samlGroupIDExtractor.
            getGroupingIdentifierList("test");
    Assert.assertEquals(organizationValue, organizations[0]);
}
 
Example #26
Source File: SAMLGroupIDExtractorImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test
public void getGroupingIdentifiersTestCase() throws ParserConfigurationException, IOException, SAXException,
        UnmarshallingException, UserStoreException {

    SAMLGroupIDExtractorImpl samlGroupIDExtractor = new SAMLGroupIDExtractorImplWrapper();

    Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(documentBuilderFactory);
    Mockito.when(documentBuilderFactory.newDocumentBuilder()).thenReturn(documentBuilder);
    Mockito.when(documentBuilder.parse(samlGroupIDExtractor.getByteArrayInputStream("test"))).
            thenReturn(document);
    Mockito.when(document.getDocumentElement()).thenReturn(element);

    PowerMockito.mockStatic(XMLObjectProviderRegistrySupport.class);
    Response response = Mockito.mock(Response.class);
    List<Assertion> assertion = new ArrayList();
    Subject subject = Mockito.mock(Subject.class);
    NameID nameID = Mockito.mock(NameID.class);
    Assertion assertion1 = Mockito.mock(Assertion.class);
    assertion.add(assertion1);
    Mockito.when(XMLObjectProviderRegistrySupport.getUnmarshallerFactory()).thenReturn(unmarshallerFactory);
    Mockito.when(unmarshallerFactory.getUnmarshaller(element)).thenReturn(unmarshaller);
    Mockito.when(unmarshaller.unmarshall(element)).thenReturn(response);
    Mockito.when(response.getAssertions()).thenReturn(assertion);
    Mockito.when(assertion.get(0).getSubject()).thenReturn(subject);
    Mockito.when(subject.getNameID()).thenReturn(nameID);
    Mockito.when(nameID.getValue()).thenReturn("user");

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    RealmService realmService = Mockito.mock(RealmService.class);
    UserRealm userRealm = Mockito.mock(UserRealm.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    UserStoreManager userStoreManager = Mockito.mock(UserStoreManager.class);
    APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
    Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
    Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).
            thenReturn("http://wso2.org/claims/organization");

    Mockito.when(tenantManager.getTenantId("carbon.super")).thenReturn(1234);
    Mockito.when(realmService.getTenantUserRealm(1234)).thenReturn(userRealm);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
    Mockito.when(userStoreManager.getUserClaimValue(MultitenantUtils.
            getTenantAwareUsername("user"), "http://wso2.org/claims/organization", null)).
            thenReturn("organization");

    Assert.assertEquals("carbon.super/organization",samlGroupIDExtractor.
            getGroupingIdentifiers("test"));
}
 
Example #27
Source File: SamlClient.java    From saml-client with MIT License 4 votes vote down vote up
private static XMLObject buildSamlObject(QName qname) {
  return XMLObjectProviderRegistrySupport.getBuilderFactory()
      .getBuilder(qname)
      .buildObject(qname);
}
 
Example #28
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void handleSloGetRequestBase(HttpRequest request) {
    try {

        HttpServletRequest httpServletRequest = new FakeHttpServletRequest(request);

        HTTPRedirectDeflateDecoder decoder = new HTTPRedirectDeflateDecoder();
        decoder.setParserPool(XMLObjectProviderRegistrySupport.getParserPool());
        decoder.setHttpServletRequest(httpServletRequest);
        decoder.initialize();
        decoder.decode();

        MessageContext<SAMLObject> messageContext = decoder.getMessageContext();

        if (!(messageContext.getMessage() instanceof LogoutRequest)) {
            throw new RuntimeException("Expected LogoutRequest; received: " + messageContext.getMessage());
        }

        LogoutRequest logoutRequest = (LogoutRequest) messageContext.getMessage();

        SAML2HTTPRedirectDeflateSignatureSecurityHandler signatureSecurityHandler = new SAML2HTTPRedirectDeflateSignatureSecurityHandler();
        SignatureValidationParameters validationParams = new SignatureValidationParameters();
        SecurityParametersContext securityParametersContext = messageContext
                .getSubcontext(SecurityParametersContext.class, true);

        SAMLPeerEntityContext peerEntityContext = messageContext.getSubcontext(SAMLPeerEntityContext.class, true);
        peerEntityContext.setEntityId(idpEntityId);
        peerEntityContext.setRole(org.opensaml.saml.saml2.metadata.SPSSODescriptor.DEFAULT_ELEMENT_NAME);

        SAMLProtocolContext protocolContext = messageContext.getSubcontext(SAMLProtocolContext.class, true);
        protocolContext.setProtocol(SAMLConstants.SAML20P_NS);

        validationParams.setSignatureTrustEngine(buildSignatureTrustEngine(this.spSignatureCertificate));
        securityParametersContext.setSignatureValidationParameters(validationParams);
        signatureSecurityHandler.setHttpServletRequest(httpServletRequest);
        signatureSecurityHandler.initialize();
        signatureSecurityHandler.invoke(messageContext);

        if (!this.authenticateUser.equals(logoutRequest.getNameID().getValue())) {
            throw new RuntimeException("Unexpected NameID in LogoutRequest: " + logoutRequest);
        }

    } catch (URISyntaxException | ComponentInitializationException | MessageDecodingException
            | MessageHandlerException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: AbstractSamlObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 3 votes vote down vote up
/**
 * Build the saml object based on its QName.
 *
 * @param objectType the object
 * @param qName the QName
 * @param <T> the object type
 * @return the saml object
 */
private <T extends SAMLObject> T newSamlObject(final Class<T> objectType, final QName qName) {
    final SAMLObjectBuilder<T> builder = (SAMLObjectBuilder<T>) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName);
    if (builder == null) {
        throw new IllegalStateException("No SAMLObjectBuilder registered for class " + objectType.getName());
    }
    return objectType.cast(builder.buildObject());
}
 
Example #30
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 3 votes vote down vote up
public XSAny createXSAny(QName elementName, String textContent) {

        XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory();

        XSAny result = (XSAny) builderFactory.getBuilder(XSAny.TYPE_NAME).buildObject(elementName);

        result.setTextContent(textContent);

        return result;
    }