Java Code Examples for org.apache.wss4j.common.saml.OpenSAMLUtil#toDom()

The following examples show how to use org.apache.wss4j.common.saml.OpenSAMLUtil#toDom() . 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: AbstractSamlResponseCreator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected Element createLogoutResponse(Idp idp, String statusValue,
                                       String destination, String requestID) throws Exception {
    Document doc = DOMUtils.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(statusValue, null);
    String issuer = useRealmForIssuer ? idp.getRealm() : idp.getIdpUrl().toString();
    LogoutResponse response =
        SAML2PResponseComponentBuilder.createSAMLLogoutResponse(requestID, issuer, status, destination);

    // Sign the LogoutResponse
    signResponse(response, idp);

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);

    return policyElement;
}
 
Example 2
Source File: SAMLResponseTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private Element createLogoutResponse(String statusValue, String destination,
                                     boolean sign, String requestID) throws Exception {
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(statusValue, null);
    LogoutResponse response =
        SAML2PResponseComponentBuilder.createSAMLLogoutResponse(requestID, TEST_IDP_ISSUER, status, destination);

    // Sign the LogoutResponse
    if (sign) {
        signResponse(response, "mystskey");
    }

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);

    return policyElement;
}
 
Example 3
Source File: SAMLEncryptedResponseTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Element createSamlResponse(SamlAssertionWrapper assertion, String alias,
                                  boolean sign, String requestID)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }

    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID,
                                                          assertion.getIssuerString(),
                                                          status);
    response.getAssertions().add(assertion.getSaml2());

    Document doc = docBuilder.newDocument();
    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);

    return policyElement;
}
 
Example 4
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Response createResponse(
    SubjectConfirmationDataBean subjectConfirmationData,
    SAML2CallbackHandler callbackHandler
) throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    return (Response)OpenSAMLUtil.fromDom(policyElement);
}
 
Example 5
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void validateIdpInitiatedLoginResponseFailure() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);

    // Create a SAML Response using WSS4J
    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");

    org.opensaml.saml.saml2.core.Response samlResponse =
            createResponse(null, true, SAML2Constants.CONF_BEARER, "urn:org:apache:cxf:fediz:idp:realm-A");

    Document doc = DOMUtils.newDocument();
    Element responseElement = OpenSAMLUtil.toDom(samlResponse, doc);
    String responseStr = DOM2Writer.nodeToString(responseElement);

    // Validate the SAML Response
    response.setSamlResponse(Base64.getEncoder().encodeToString(responseStr.getBytes()));
    response.setRelayState("idpInitiated");
    try {
        saml2Service.validateLoginResponse(response);
        fail("Failure expected on an unsolicited login");
    } catch (SyncopeClientException e) {
        assertNotNull(e);
    }
}
 
Example 6
Source File: SAMLResponseConformanceTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private Element createSamlResponse(SamlAssertionWrapper assertion, String alias,
                                  boolean sign, String requestID, Issuer issuer)
    throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {
        new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }

    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );

    Issuer responseIssuer = issuer;
    if (responseIssuer == null) {
        responseIssuer = SAML2PResponseComponentBuilder.createIssuer(assertion.getIssuerString());
    }
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID,
                                                          responseIssuer,
                                                          status);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);

    return policyElement;
}
 
Example 7
Source File: AbstractXACMLAuthorizingInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Perform a (remote) authorization decision and return a boolean depending on the result
 */
protected boolean authorize(
    Principal principal, List<String> roles, Message message
) throws Exception {
    RequestType request = requestBuilder.createRequest(principal, roles, message);
    if (LOG.isLoggable(Level.FINE)) {
        Document doc = DOMUtils.createDocument();
        Element requestElement = OpenSAMLUtil.toDom(request, doc);
        LOG.log(Level.FINE, DOM2Writer.nodeToString(requestElement));
    }

    ResponseType response = performRequest(request, message);

    List<ResultType> results = response.getResults();

    if (results == null) {
        return false;
    }

    for (ResultType result : results) {
        // Handle any Obligations returned by the PDP
        handleObligations(request, principal, message, result);

        DECISION decision = result.getDecision() != null ? result.getDecision().getDecision() : DECISION.Deny;
        String code = "";
        String statusMessage = "";
        if (result.getStatus() != null) {
            StatusType status = result.getStatus();
            code = status.getStatusCode() != null ? status.getStatusCode().getValue() : "";
            statusMessage = status.getStatusMessage() != null ? status.getStatusMessage().getValue() : "";
        }
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("XACML authorization result: " + decision + ", code: " + code + ", message: " + statusMessage);
        }
        return decision == DECISION.Permit;
    }

    return false;
}
 
Example 8
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreateAuthnRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");
    NameIDPolicy nameIDPolicy =
        SamlpRequestComponentBuilder.createNameIDPolicy(
            true, "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent", "Issuer"
        );

    AuthnContextClassRef authnCtxClassRef =
        SamlpRequestComponentBuilder.createAuthnCtxClassRef(
            "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
        );
    RequestedAuthnContext authnCtx =
        SamlpRequestComponentBuilder.createRequestedAuthnCtxPolicy(
            AuthnContextComparisonTypeEnumeration.EXACT,
            Collections.singletonList(authnCtxClassRef), null
        );

    AuthnRequest authnRequest =
        SamlpRequestComponentBuilder.createAuthnRequest(
            "http://localhost:9001/sso", false, false,
            "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST", SAMLVersion.VERSION_20,
            issuer, nameIDPolicy, authnCtx
        );

    Element policyElement = OpenSAMLUtil.toDom(authnRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example 9
Source File: SamlResponseErrorCreator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
public String createSAMLResponse(RequestContext context, boolean logout, boolean requestor,
                                 Idp idp, String requestID, String destination) throws ProcessingException {
    Document doc = DOMUtils.newDocument();

    String statusValue = "urn:oasis:names:tc:SAML:2.0:status:Responder";
    if (requestor) {
        statusValue = "urn:oasis:names:tc:SAML:2.0:status:Requester";
    }

    Status status =
        SAML2PResponseComponentBuilder.createStatus(statusValue, null);
    Element responseElement = null;
    try {
        if (logout) {
            responseElement = createLogoutResponse(idp, statusValue, destination, requestID);
        } else {
            Response response =
                SAML2PResponseComponentBuilder.createSAMLResponse(requestID, idp.getRealm(), status);
            Element policyElement = OpenSAMLUtil.toDom(response, doc);
            doc.appendChild(policyElement);

            responseElement = policyElement;
        }

        return encodeResponse(responseElement);
    } catch (Exception e) {
        LOG.warn("Error marshalling SAML Token: {}", e.getMessage());
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }
}
 
Example 10
Source File: AbstractServiceProviderFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected SamlRequestInfo createSamlRequestInfo(Message m) throws Exception {
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));

    // Create the AuthnRequest
    AuthnRequest authnRequest =
        authnRequestBuilder.createAuthnRequest(
            m, getIssuerId(m), getAbsoluteAssertionServiceAddress(m)
        );
    if (isSignRequest()) {
        authnRequest.setDestination(getIdpServiceAddress());
        signAuthnRequest(authnRequest);
    }
    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
    String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);

    SamlRequestInfo info = new SamlRequestInfo();
    info.setSamlRequest(authnRequestEncoded);

    String webAppContext = getWebAppContext(m);
    String originalRequestURI = new UriInfoImpl(m).getRequestUri().toString();

    RequestState requestState = new RequestState(originalRequestURI,
                                                 getIdpServiceAddress(),
                                                 authnRequest.getID(),
                                                 getIssuerId(m),
                                                 webAppContext,
                                                 getWebAppDomain(),
                                                 System.currentTimeMillis(),
                                                 getStateTimeToLive());

    String relayState = URLEncoder.encode(UUID.randomUUID().toString(), StandardCharsets.UTF_8.name());
    getStateProvider().setRequestState(relayState, requestState);
    info.setRelayState(relayState);
    info.setWebAppContext(webAppContext);
    info.setWebAppDomain(getWebAppDomain());

    return info;
}
 
Example 11
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testResponseIssueInstant() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    response.setIssueInstant(new DateTime().plusMinutes(5));

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid Response IssueInstant");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 12
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testModifiedSignedResponse() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SAMLResponseValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);

    response.getAssertions().add(assertion.getSaml2());
    signResponse(response, "alice", "password", issuerCrypto, true);

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    policyElement.setAttributeNS(null, "newattr", "http://apache.org");

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        // Validate the Response
        validator.validateSamlResponse(
            marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
        );
        fail("Expected failure on a bad signature");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 13
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testInvalidSubjectLocality() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);
    callbackHandler.setSubjectLocality("xyz.123", null);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid SessionNotOnOrAfter");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 14
Source File: SAMLEncryptedResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private Element createEncryptedSamlResponse(SamlAssertionWrapper assertion, String alias,
                                   boolean sign, String requestID)
        throws IOException, UnsupportedCallbackException, WSSecurityException, Exception {
    WSPasswordCallback[] cb = {new WSPasswordCallback(alias, WSPasswordCallback.SIGNATURE)};
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    if (sign) {
        assertion.signAssertion(alias, password, crypto, false);
    }

    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Status status =
            SAML2PResponseComponentBuilder.createStatus(
                    "urn:oasis:names:tc:SAML:2.0:status:Success", null
            );
    Response response =
            SAML2PResponseComponentBuilder.createSAMLResponse(requestID,
                    assertion.getIssuerString(),
                    status);

    Document assertionDoc = docBuilder.newDocument();
    Element elem = assertion.toDOM(assertionDoc);

    Element encryptedAssertionElement =
            assertionDoc.createElementNS(WSConstants.SAML2_NS, WSConstants.ENCRYPED_ASSERTION_LN);
    encryptedAssertionElement.setAttributeNS(
            WSConstants.XMLNS_NS, "xmlns", WSConstants.SAML2_NS
    );
    encryptedAssertionElement.appendChild(elem);
    assertionDoc.appendChild(encryptedAssertionElement);

    // Encrypt the Assertion
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(256);
    SecretKey secretKey = keygen.generateKey();
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("mystskey");
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    assertTrue(certs != null && certs.length > 0 && certs[0] != null);

    encryptElement(assertionDoc, elem, WSConstants.AES_256, secretKey,
            WSConstants.KEYTRANSPORT_RSAOAEP, certs[0], false);

    Document doc = docBuilder.newDocument();
    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    Element statusElement =
            (Element)policyElement.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol",
                    "Status").item(0);
    assertNotNull(statusElement);
    policyElement.appendChild(doc.importNode(encryptedAssertionElement, true));

    return policyElement;
}
 
Example 15
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testResponseSignedAssertion() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    Crypto issuerCrypto = new Merlin();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    ClassLoader loader = Loader.getClassLoader(SAMLResponseValidatorTest.class);
    InputStream input = Merlin.loadInputStream(loader, "alice.jks");
    keyStore.load(input, "password".toCharArray());
    ((Merlin)issuerCrypto).setKeyStore(keyStore);

    assertion.signAssertion("alice", "password", issuerCrypto, false);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, new KeystorePasswordCallback());
        fail("Expected failure on no Signature Crypto");
    } catch (WSSecurityException ex) {
        // expected
    }

    // Validate the Response
    validator.validateSamlResponse(
        marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
    );
}
 
Example 16
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testFutureAuthnInstant() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);
    callbackHandler.setAuthnInstant(new DateTime().plusDays(1));

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid Assertion AuthnInstant");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 17
Source File: RequestComponentBuilderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testEnvironment() throws Exception {
    Document doc = docBuilder.newDocument();

    // Subject
    AttributeValueType subjectIdAttributeValue =
        RequestComponentBuilder.createAttributeValueType(
                "[email protected]"
        );
    AttributeType subjectIdAttribute =
        RequestComponentBuilder.createAttributeType(
                XACMLConstants.SUBJECT_ID,
                XACMLConstants.RFC_822_NAME,
                null,
                Collections.singletonList(subjectIdAttributeValue)
        );

    List<AttributeType> attributes = new ArrayList<>();
    attributes.add(subjectIdAttribute);
    SubjectType subject = RequestComponentBuilder.createSubjectType(attributes, null);

    // Resource
    AttributeValueType resourceAttributeValue =
        RequestComponentBuilder.createAttributeValueType(
                "{http://www.example.org/contract/DoubleIt}DoubleIt"
        );
    AttributeType resourceAttribute =
        RequestComponentBuilder.createAttributeType(
                XACMLConstants.RESOURCE_ID,
                XACMLConstants.XS_STRING,
                null,
                Collections.singletonList(resourceAttributeValue)
        );
    attributes.clear();
    attributes.add(resourceAttribute);
    ResourceType resource = RequestComponentBuilder.createResourceType(attributes, null);

    // Action
    AttributeValueType actionAttributeValue =
        RequestComponentBuilder.createAttributeValueType(
                "execute"
        );
    AttributeType actionAttribute =
        RequestComponentBuilder.createAttributeType(
                XACMLConstants.ACTION_ID,
                XACMLConstants.XS_STRING,
                null,
                Collections.singletonList(actionAttributeValue)
        );
    attributes.clear();
    attributes.add(actionAttribute);
    ActionType action = RequestComponentBuilder.createActionType(attributes);

    // Environment
    DateTime dateTime = new DateTime();
    AttributeValueType environmentAttributeValue =
        RequestComponentBuilder.createAttributeValueType(dateTime.toString());
    AttributeType environmentAttribute =
        RequestComponentBuilder.createAttributeType(
                XACMLConstants.CURRENT_DATETIME,
                XACMLConstants.XS_DATETIME,
                null,
                Collections.singletonList(environmentAttributeValue)
        );
    attributes.clear();
    attributes.add(environmentAttribute);
    EnvironmentType environmentType =
         RequestComponentBuilder.createEnvironmentType(attributes);

    // Request
    RequestType request =
        RequestComponentBuilder.createRequestType(
                Collections.singletonList(subject),
                Collections.singletonList(resource),
                action,
                environmentType
        );

    Element policyElement = OpenSAMLUtil.toDom(request, doc);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example 18
Source File: AbstractPolicySecurityTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void runOutInterceptorAndValidateSamlTokenAttached(String policyDoc) throws Exception {
    // create the request message
    final Document document = this.readDocument("wsse-request-clean.xml");
    final Element outPolicyElement =
        this.readDocument(policyDoc).getDocumentElement();
    final Policy policy = this.policyBuilder.getPolicy(outPolicyElement);

    AssertionInfoMap aim = new AssertionInfoMap(policy);
    SoapMessage msg = this.getOutSoapMessageForDom(document, aim);

    // add an "issued" assertion into the message exchange
    Element issuedAssertion =
        this.readDocument("example-sts-issued-saml-assertion.xml").getDocumentElement();

    Properties cryptoProps = new Properties();
    URL url = ClassLoader.getSystemResource("outsecurity.properties");
    cryptoProps.load(url.openStream());
    Crypto crypto = CryptoFactory.getInstance(cryptoProps);

    // Sign the "issued" assertion
    SamlAssertionWrapper assertionWrapper = new SamlAssertionWrapper(issuedAssertion);
    assertionWrapper.signAssertion("myalias", "myAliasPassword", crypto, false);

    Document doc = DOMUtils.newDocument();
    issuedAssertion = OpenSAMLUtil.toDom(assertionWrapper.getSaml1(), doc);
    String assertionId = issuedAssertion.getAttributeNodeNS(null, "AssertionID").getNodeValue();

    SecurityToken issuedToken =
        new SecurityToken(assertionId, issuedAssertion, null);

    String alias = cryptoProps.getProperty("org.apache.ws.security.crypto.merlin.keystore.alias");
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(alias);
    issuedToken.setX509Certificate(crypto.getX509Certificates(cryptoType)[0], crypto);

    msg.getExchange().getEndpoint().put(SecurityConstants.TOKEN_ID,
            issuedToken.getId());
    msg.getExchange().put(SecurityConstants.TOKEN_ID, issuedToken.getId());

    TokenStore tokenStore = new MemoryTokenStore();
    msg.getExchange().getEndpoint().getEndpointInfo()
        .setProperty(TokenStore.class.getName(), tokenStore);
    tokenStore.add(issuedToken);

    // fire the interceptor and verify results
    final Document signedDoc = this.runOutInterceptorAndValidate(
            msg, policy, aim, null, null);

    this.runInInterceptorAndValidate(signedDoc,
                                     policy, Collections.singletonList(SP12Constants.ISSUED_TOKEN), null,
                                     Collections.singletonList(CoverageType.SIGNED));
}
 
Example 19
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulInvokeOnIdPUsingPOST() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    // Create the AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up");
    signAuthnRequest(authnRequest);

    Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);

    // Don't inflate the token...
    String requestMessage = DOM2Writer.nodeToString(authnRequestElement);
    String authnRequestEncoded = Base64Utility.encode(requestMessage.getBytes(UTF_8.name()));

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml/up";

    final WebClient webClient = new WebClient();
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(USER, PWD));

    webClient.getOptions().setJavaScriptEnabled(false);

    WebRequest request = new WebRequest(new URL(url), HttpMethod.POST);

    request.setRequestParameters(new ArrayList<NameValuePair>());
    request.getRequestParameters().add(new NameValuePair(SSOConstants.RELAY_STATE, relayState));
    request.getRequestParameters().add(new NameValuePair(SSOConstants.SAML_REQUEST, authnRequestEncoded));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(request);

    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    org.opensaml.saml.saml2.core.Response samlResponse =
        parseSAMLResponse(idpPage, relayState, consumerURL, authnRequest.getID());
    String expected = "urn:oasis:names:tc:SAML:2.0:status:Success";
    Assert.assertEquals(expected, samlResponse.getStatus().getStatusCode().getValue());

    // Check claims
    String parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    String claim = ClaimTypes.FIRSTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.LASTNAME.toString();
    Assert.assertTrue(parsedResponse.contains(claim));
    claim = ClaimTypes.EMAILADDRESS.toString();
    Assert.assertTrue(parsedResponse.contains(claim));

    webClient.close();
}
 
Example 20
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testAssertionIssueInstant() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_SENDER_VOUCHES);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    assertion.getSaml2().setIssueInstant(new DateTime().plusMinutes(5));

    response.getAssertions().add(assertion.getSaml2());

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    Response marshalledResponse = (Response)OpenSAMLUtil.fromDom(policyElement);

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid Assertion IssueInstant");
    } catch (WSSecurityException ex) {
        // expected
    }
}