org.apache.wss4j.common.saml.OpenSAMLUtil Java Examples

The following examples show how to use org.apache.wss4j.common.saml.OpenSAMLUtil. 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: SAMLUtil.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * Check the holder-of-key requirements against the received assertion. The subject
 * credential of the SAML Assertion must match a client certificate credential when
 * 2-way TLS is used.
 * @param assertionWrapper the SAML Assertion wrapper object
 * @param tlsCerts The client certificates
 */
public static boolean checkHolderOfKey(
    SamlAssertionWrapper assertionWrapper,
    Certificate[] tlsCerts
) {
    List<String> confirmationMethods = assertionWrapper.getConfirmationMethods();
    for (String confirmationMethod : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(confirmationMethod)) {
            if (tlsCerts == null || tlsCerts.length == 0) {
                return false;
            }
            SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (!compareCredentials(subjectKeyInfo, tlsCerts)) {
                return false;
            }
        }
    }
    return true;
}
 
Example #2
Source File: SAMLLogoutTest.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: 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 #4
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssuePublicKeySAML2TokenShortKeyType() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .query("keyType", "PublicKey")
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getCerts());
}
 
Example #5
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssuePublicKeySAML2Token() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .query("keyType", STSConstants.PUBLIC_KEY_KEYTYPE)
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getCerts());
}
 
Example #6
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueSymmetricKeySaml1ShortKeyType() throws Exception {
    WebClient client = webClient()
        .path("saml1.1")
        .query("keyType", "SymmetricKey")
        .accept(MediaType.APPLICATION_XML);

    Document assertionDoc = client.get(Document.class);

    SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
    assertTrue(assertion.getSaml2() == null && assertion.getSaml1() != null);

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getSecret());
}
 
Example #7
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 #8
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCreateLogoutRequest() throws Exception {
    Document doc = DOMUtils.createDocument();

    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer("http://localhost:9001/app");

    NameIDBean nameIdBean = new NameIDBean();
    nameIdBean.setNameValue("uid=joe,ou=people,ou=saml-demo,o=example.com");
    nameIdBean.setNameQualifier("www.example.com");
    NameID nameID = SAML2ComponentBuilder.createNameID(nameIdBean);

    Date notOnOrAfter = new Date();
    notOnOrAfter.setTime(notOnOrAfter.getTime() + 60L * 1000L);
    LogoutRequest logoutRequest =
        SamlpRequestComponentBuilder.createLogoutRequest(SAMLVersion.VERSION_20, issuer, null, null,
                                                         notOnOrAfter, null, nameID);

    Element policyElement = OpenSAMLUtil.toDom(logoutRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example #9
Source File: AuthnRequestBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testAuthnRequestBuilder() throws Exception {
    Document doc = DOMUtils.createDocument();

    AuthnRequestBuilder authnRequestBuilder = new DefaultAuthnRequestBuilder();
    Message message = new MessageImpl();

    AuthnRequest authnRequest =
        authnRequestBuilder.createAuthnRequest(
            message, "http://localhost:9001/app", "http://localhost:9001/sso"
        );
    Element policyElement = OpenSAMLUtil.toDom(authnRequest, doc);
    doc.appendChild(policyElement);
    // String outputString = DOM2Writer.nodeToString(policyElement);
    assertNotNull(policyElement);
}
 
Example #10
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Test
public void validateIdpInitiatedLoginResponse() 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-B");

    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");
    SAML2LoginResponseTO loginResponse = saml2Service.validateLoginResponse(response);
    assertNotNull(loginResponse.getAccessToken());
    assertEquals("puccini", loginResponse.getNameID());
}
 
Example #11
Source File: SamlResponseCreator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected Element createResponse(Idp idp, String requestID, Assertion assertion) throws Exception {
    Document doc = DOMUtils.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );
    String issuer = isUseRealmForIssuer() ? idp.getRealm() : idp.getIdpUrl().toString();
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID, issuer, status);

    response.getAssertions().add(assertion);

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

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

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML1_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);

    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 SAML code");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example #13
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 #14
Source File: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static XMLObject read(final boolean useDeflateEncoding, final String response)
        throws DataFormatException, UnsupportedEncodingException, XMLStreamException, WSSecurityException {

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

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

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

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

    return responseObject;
}
 
Example #15
Source File: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public void sign(final SignableSAMLObject signableObject) throws SecurityException {
    org.opensaml.xmlsec.signature.Signature signature = OpenSAMLUtil.buildSignature();
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    signature.setSignatureAlgorithm(sigAlgo);
    signature.setSigningCredential(loader.getCredential());
    signature.setKeyInfo(keyInfoGenerator.generate(loader.getCredential()));

    signableObject.setSignature(signature);
    signableObject.releaseDOM();
    signableObject.releaseChildrenDOM(true);
}
 
Example #16
Source File: IssueUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the Public Key SAML2 case
 */
@org.junit.Test
public void testPublicKeySaml2() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    // Get a token
    SecurityToken token =
        requestSecurityToken(SAML2_TOKEN_TYPE, PUBLIC_KEY_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertTrue(token.getSecret() == null && token.getX509Certificate() != null);
    assertEquals(SAML2_TOKEN_TYPE, token.getTokenType());
    assertNotNull(token.getToken());

    // Process the token
    List<WSSecurityEngineResult> results = processToken(token);
    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper)results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertNotNull(assertion);
    assertTrue(assertion.getSaml1() == null && assertion.getSaml2() != null);
    assertTrue(assertion.isSigned());

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && !methods.isEmpty()) {
        confirmMethod = methods.get(0);
    }
    assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
    SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
    assertNotNull(subjectKeyInfo.getCerts());

    bus.shutdown(true);
}
 
Example #17
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private static String encodeAuthnRequest(XMLObject request) throws WSSecurityException {
    Document doc = DOMUtils.createDocument();
    doc.appendChild(doc.createElement("root"));
    String requestMessage = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(request, doc));

    DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
    byte[] deflatedBytes = encoder.deflateToken(requestMessage.getBytes(UTF_8));

    return Base64Utility.encode(deflatedBytes);
}
 
Example #18
Source File: AbstractSamlInHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Check the sender-vouches requirements against the received assertion. The SAML
 * Assertion and the request body must be signed by the same signature.
 */
protected boolean checkSenderVouches(
    Message message,
    SamlAssertionWrapper assertionWrapper,
    Certificate[] tlsCerts
) {
    //
    // If we have a 2-way TLS connection, then we don't have to check that the
    // assertion + body are signed

    // If no body is available (ex, with GET) then consider validating that
    // the base64-encoded token is signed by the same signature
    //
    if (tlsCerts != null && tlsCerts.length > 0) {
        return true;
    }
    List<String> confirmationMethods = assertionWrapper.getConfirmationMethods();
    for (String confirmationMethod : confirmationMethods) {
        if (OpenSAMLUtil.isMethodSenderVouches(confirmationMethod)) {

            Element signedElement = message.getContent(Element.class);
            Node assertionParent = assertionWrapper.getElement().getParentNode();

            // if we have a shared parent signed node then we can assume both
            // this SAML assertion and the main payload have been signed by the same
            // signature
            if (assertionParent != signedElement) {
                // if not then try to compare if the same cert/key was used to sign SAML token
                // and the payload
                SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSignatureKeyInfo();
                if (!compareCredentials(subjectKeyInfo, message, tlsCerts)) {
                    return false;
                }
            }
        }
    }
    return true;
}
 
Example #19
Source File: AbstractSamlInHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected boolean checkHolderOfKey(Message message,
                                SamlAssertionWrapper assertionWrapper,
                                Certificate[] tlsCerts) {
    List<String> confirmationMethods = assertionWrapper.getConfirmationMethods();
    for (String confirmationMethod : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(confirmationMethod)) {
            SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSubjectKeyInfo();
            if (!compareCredentials(subjectKeyInfo, message, tlsCerts)) {
                return false;
            }
        }
    }
    return true;
}
 
Example #20
Source File: SAMLSSOResponseValidatorTest.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 #21
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 #22
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 #23
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreateAndValidateResponse() 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);

    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();
    validator.validateSamlResponse(marshalledResponse, null, null);
}
 
Example #24
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testRequestDeniedStatusCode() throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:RequestDenied", 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);

    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 SAML code");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example #25
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 #26
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnsignedRequest() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML 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");

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    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);
    final HtmlPage idpPage = webClient.getPage(url);

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

    webClient.close();
}
 
Example #27
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testMissingRelayState() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML 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");
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    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);
    try {
        webClient.getPage(url);
        Assert.fail("Failure expected on not sending the RelayState");
    }  catch (FailingHttpStatusCodeException ex) {
        Assert.assertEquals(ex.getStatusCode(), 400);
    }

    webClient.close();
}
 
Example #28
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadIssuer() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld-xyz", consumerURL
        );
    authnRequest.setDestination("https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml");
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    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);
    final HtmlPage idpPage = webClient.getPage(url);

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

    webClient.close();
}
 
Example #29
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testMissingDestination() throws Exception {
    OpenSAMLUtil.initSamlEngine();

    // Create SAML AuthnRequest
    String consumerURL = "https://localhost:" + getRpHttpsPort() + "/"
        + getServletContextName() + "/secure/fedservlet";
    AuthnRequest authnRequest =
        new DefaultAuthnRequestBuilder().createAuthnRequest(
            null, "urn:org:apache:cxf:fediz:fedizhelloworld", consumerURL
        );
    signAuthnRequest(authnRequest);

    String authnRequestEncoded = encodeAuthnRequest(authnRequest);

    String relayState = UUID.randomUUID().toString();
    String url = "https://localhost:" + getIdpHttpsPort() + "/fediz-idp/saml?"
            + SSOConstants.RELAY_STATE + "=" + relayState
            + "&" + SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(authnRequestEncoded, UTF_8.name());

    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);
    final HtmlPage idpPage = webClient.getPage(url);

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

    webClient.close();
}
 
Example #30
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;
}