Java Code Examples for org.apache.wss4j.common.util.DOM2Writer#nodeToString()

The following examples show how to use org.apache.wss4j.common.util.DOM2Writer#nodeToString() . 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: SAMLProviderKeyTypeTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a default Saml1 Bearer Assertion signed by a PKCS12 keystore
 */
@org.junit.Test
public void testDefaultSaml1BearerAssertionPKCS12() throws Exception {
    if (!TestUtilities.checkUnrestrictedPoliciesInstalled()) {
        return;
    }
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParametersPKCS12(
            WSS4JConstants.WSS_SAML_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE
        );
    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertFalse(tokenString.contains("AuthenticationStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML1Constants.CONF_BEARER));
    assertFalse(tokenString.contains(SAML1Constants.CONF_HOLDER_KEY));
}
 
Example 2
Source File: SAMLTokenValidatorOldTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private String createSamlToken(SamlAssertionWrapper assertion, String alias, boolean sign, String rstr)
    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);
    }
    Document doc = STSUtil.toSOAPPart(rstr);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    return DOM2Writer.nodeToString(doc);
}
 
Example 3
Source File: SAMLProviderCustomTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a custom Saml2 Authentication Assertion.
 */
@org.junit.Test
public void testCustomSaml2AuthenticationAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);

    List<AuthenticationStatementProvider> customProviderList =
        new ArrayList<>();
    customProviderList.add(new CustomAuthenticationProvider());
    ((SAMLTokenProvider)samlTokenProvider).setAuthenticationStatementProviders(customProviderList);

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

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertFalse(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("AuthnStatement"));
    assertTrue(tokenString.contains(SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509));
    assertTrue(tokenString.contains("alice"));
}
 
Example 4
Source File: SAMLProviderCustomTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a custom Saml1 (Multiple) Attribute Assertion.
 */
@org.junit.Test
public void testCustomSaml1MultipleAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);

    List<AttributeStatementProvider> customProviderList = new ArrayList<>();
    customProviderList.add(new CustomAttributeProvider());
    customProviderList.add(new CustomAttributeProvider());
    ((SAMLTokenProvider)samlTokenProvider).setAttributeStatementProviders(customProviderList);

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

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertFalse(tokenString.contains("AuthenticationStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains("http://cxf.apache.org/sts/custom"));
}
 
Example 5
Source File: SAMLProviderKeyTypeTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a default Saml2 Bearer Assertion.
 */
@org.junit.Test
public void testDefaultSaml2BearerAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);
    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertFalse(tokenString.contains("AuthenticationStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
    assertFalse(tokenString.contains(SAML2Constants.CONF_HOLDER_KEY));
}
 
Example 6
Source File: SAMLProviderOnBehalfOfTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a default Saml1 Bearer Assertion with OnBehalfOf from a UsernameToken
 */
@org.junit.Test
public void testDefaultSaml1OnBehalfOfUsernameToken() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();

    UsernameTokenType usernameToken = new UsernameTokenType();
    AttributedString username = new AttributedString();
    username.setValue("bob");
    usernameToken.setUsername(username);
    JAXBElement<UsernameTokenType> usernameTokenType =
        new JAXBElement<UsernameTokenType>(
            QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameToken
        );

    TokenProviderParameters providerParameters =
        createProviderParameters(
            WSS4JConstants.WSS_SAML_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, usernameTokenType
        );
    //Principal must be set in ReceivedToken/OnBehalfOf
    providerParameters.getTokenRequirements().getOnBehalfOf().setPrincipal(
            new CustomTokenPrincipal(username.getValue()));

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

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("bob"));
}
 
Example 7
Source File: SAMLClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a SAML2 Assertion with various Attributes set by a ClaimsHandler.
 */
@org.junit.Test
public void testSaml2Claims() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = createClaims();
    providerParameters.setRequestedPrimaryClaims(claims);

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

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));
    assertTrue(tokenString.contains(ClaimTypes.EMAILADDRESS.toString()));
    assertTrue(tokenString.contains(ClaimTypes.FIRSTNAME.toString()));
    assertTrue(tokenString.contains(ClaimTypes.LASTNAME.toString()));
}
 
Example 8
Source File: AbstractSamlResponseCreator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected String encodeResponse(Element response) throws IOException {
    String responseMessage = DOM2Writer.nodeToString(response);
    LOG.debug("Created Response: {}", responseMessage);

    if (supportDeflateEncoding) {
        DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
        byte[] deflatedBytes = encoder.deflateToken(responseMessage.getBytes(StandardCharsets.UTF_8));

        return Base64Utility.encode(deflatedBytes);
    }

    return Base64Utility.encode(responseMessage.getBytes());
}
 
Example 9
Source File: SAMLProviderKeyTypeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a default Saml1 PublicKey Assertion.
 */
@org.junit.Test
public void testDefaultSaml1PublicKeyAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.SAML_NS, STSConstants.PUBLIC_KEY_KEYTYPE);
    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.SAML_NS));

    try {
        samlTokenProvider.createToken(providerParameters);
        fail("Failure expected on no certificate");
    } catch (STSException ex) {
        // expected as no certificate is provided
    }

    // Now get a certificate and set it on the key requirements of the provider parameter
    Crypto crypto = providerParameters.getStsProperties().getEncryptionCrypto();
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("myclientkey");
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    ReceivedCredential receivedCredential = new ReceivedCredential();
    receivedCredential.setX509Cert(certs[0]);
    providerParameters.getKeyRequirements().setReceivedCredential(receivedCredential);

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

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertFalse(tokenString.contains("AuthenticationStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML1Constants.CONF_HOLDER_KEY));
    assertFalse(tokenString.contains(SAML1Constants.CONF_BEARER));
}
 
Example 10
Source File: SAMLProviderOnBehalfOfTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a default Saml2 Bearer Assertion with OnBehalfOf from a SAML Assertion
 */
@org.junit.Test
public void testDefaultSaml2OnBehalfOfAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();

    String user = "alice";
    Element saml1Assertion = getSAMLAssertion(user);

    TokenProviderParameters providerParameters =
        createProviderParameters(
            WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, saml1Assertion
        );
    //Principal must be set in ReceivedToken/OnBehalfOf
    providerParameters.getTokenRequirements().getOnBehalfOf().setPrincipal(
            new CustomTokenPrincipal(user));

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

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains(user));
}
 
Example 11
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void unsignedAssertionInLoginResponse() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    // Get a valid login request for the Fediz realm
    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);
    SAML2RequestTO loginRequest = saml2Service.createLoginRequest(ADDRESS, "urn:org:apache:cxf:fediz:idp:realm-A");
    assertNotNull(loginRequest);

    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");
    response.setRelayState(loginRequest.getRelayState());

    // Create a SAML Response using WSS4J
    JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
    String inResponseTo = relayState.getJwtClaims().getSubject();

    org.opensaml.saml.saml2.core.Response samlResponse =
            createResponse(inResponseTo, false, SAML2Constants.CONF_SENDER_VOUCHES,
                    "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()));
    try {
        saml2Service.validateLoginResponse(response);
        fail("Failure expected on an unsigned Assertion");
    } catch (SyncopeClientException e) {
        assertNotNull(e);
    }
}
 
Example 12
Source File: IdpTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulSSOInvokeOnIdP() 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 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.addRequestHeader("Authorization", "Basic "
        + Base64.getEncoder().encodeToString((USER + ":" + PWD).getBytes(UTF_8)));

    //
    // First invocation
    //

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

    //
    // Second invocation - change the credentials to make sure the session is set up correctly
    //

    webClient.removeRequestHeader("Authorization");
    webClient.addRequestHeader("Authorization", "Basic "
        + Base64.getEncoder().encodeToString(("mallory" + ":" + PWD).getBytes(UTF_8)));

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

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

    // Check claims
    parsedResponse = DOM2Writer.nodeToString(samlResponse.getDOM().getOwnerDocument());
    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 13
Source File: IdpMetadataWriter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
public Document getMetaData(Idp config, boolean saml) {
    try {
        //Return as text/xml
        Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());

        W3CDOMStreamWriter writer = new W3CDOMStreamWriter();

        writer.writeStartDocument("UTF-8", "1.0");

        String referenceID = IDGenerator.generateID("_");
        writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS);
        writer.writeAttribute("ID", referenceID);

        writer.writeAttribute("entityID", config.getIdpUrl().toString());

        writer.writeNamespace("md", SAML2_METADATA_NS);
        writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);

        if (saml) {
            writeSAMLSSOMetadata(writer, config, crypto);
        } else {
            writeFederationMetadata(writer, config, crypto);
        }

        writer.writeEndElement(); // EntityDescriptor

        writer.writeEndDocument();

        writer.close();

        if (LOG.isDebugEnabled()) {
            String out = DOM2Writer.nodeToString(writer.getDocument());
            LOG.debug("***************** unsigned ****************");
            LOG.debug(out);
            LOG.debug("***************** unsigned ****************");
        }

        Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(),
                                                      writer.getDocument(), referenceID);
        if (result != null) {
            return result;
        } else {
            throw new RuntimeException("Failed to sign the metadata document: result=null");
        }
    } catch (Exception e) {
        LOG.error("Error creating service metadata information ", e);
        throw new RuntimeException("Error creating service metadata information: " + e.getMessage());
    }

}
 
Example 14
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testUnsignedAssertionAfterSignedAssertion() throws Exception {
    // First assertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

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

    // Second assertion
    SAML2CallbackHandler callbackHandler2 = new SAML2CallbackHandler();
    callbackHandler2.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler2.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler2.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler2.setSubjectName("bob");
    ConditionsBean cp2 = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction2 = new AudienceRestrictionBean();
    audienceRestriction2.getAudienceURIs().add(TEST_AUDIENCE);
    cp2.setAudienceRestrictions(Collections.singletonList(audienceRestriction2));
    callbackHandler2.setConditions(cp2);

    SAMLCallback samlCallback2 = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler2, samlCallback2);
    SamlAssertionWrapper assertion2 = new SamlAssertionWrapper(samlCallback2);

    Element rstrElement =
        createResponseWithMultipleAssertions(assertion1, true, assertion2, false, "mystskey");
    String rstr = DOM2Writer.nodeToString(rstrElement);
    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    // Load and update the config to enforce an error
    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    FedizResponse fedizResponse = wfProc.processRequest(wfReq, config);
    Assert.assertEquals(TEST_USER, fedizResponse.getUsername());
}
 
Example 15
Source File: TomcatPluginTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Test
public void testModifiedSignatureValue() throws Exception {

    String url = "https://localhost:" + getRpHttpsPort() + "/" + getServletContextName()
        + "/secure/fedservlet";
    String user = "alice";
    String password = "ecila";

    // Get the initial token
    CookieManager cookieManager = new CookieManager();
    final WebClient webClient = new WebClient();
    webClient.setCookieManager(cookieManager);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getCredentialsProvider().setCredentials(
        new AuthScope("localhost", Integer.parseInt(getIdpHttpsPort())),
        new UsernamePasswordCredentials(user, password));

    webClient.getOptions().setJavaScriptEnabled(false);
    final HtmlPage idpPage = webClient.getPage(url);
    webClient.getOptions().setJavaScriptEnabled(true);
    Assert.assertEquals("IDP SignIn Response Form", idpPage.getTitleText());

    // Parse the form to get the token (wresult)
    DomNodeList<DomElement> results = idpPage.getElementsByTagName("input");

    for (DomElement result : results) {
        if (getTokenName().equals(result.getAttributeNS(null, "name"))) {
            String value = result.getAttributeNS(null, "value");

            // Decode response
            byte[] deflatedToken = Base64Utility.decode(value);
            InputStream inputStream = new ByteArrayInputStream(deflatedToken);

            Document responseDoc = StaxUtils.read(new InputStreamReader(inputStream, "UTF-8"));

            // Modify SignatureValue
            String signatureNamespace = "http://www.w3.org/2000/09/xmldsig#";
            Node signatureValue =
                responseDoc.getElementsByTagNameNS(signatureNamespace, "SignatureValue").item(0);
            signatureValue.setTextContent("H" + signatureValue.getTextContent());

            // Re-encode response
            String responseMessage = DOM2Writer.nodeToString(responseDoc);
            result.setAttributeNS(null, "value", Base64Utility.encode(responseMessage.getBytes()));
        }
    }

    // Invoke back on the RP

    final HtmlForm form = idpPage.getFormByName(getLoginFormName());
    final HtmlSubmitInput button = form.getInputByName("_eventId_submit");

    try {
        button.click();
        Assert.fail("Failure expected on a modified signature");
    } catch (FailingHttpStatusCodeException ex) {
        // expected
        Assert.assertTrue(401 == ex.getStatusCode() || 403 == ex.getStatusCode());
    }

    webClient.close();
}
 
Example 16
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testModifiedSignature() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

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

    WSPasswordCallback[] cb = {
        new WSPasswordCallback("mystskey", WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    assertion.signAssertion("mystskey", password, crypto, false);
    Document doc = STSUtil.toSOAPPart(STSUtil.SAMPLE_RSTR_COLL_MSG);
    Element token = assertion.toDOM(doc);

    // Change IssueInstant attribute
    String issueInstance = token.getAttributeNS(null, "IssueInstant");
    DateTime issueDateTime = new DateTime(issueInstance, DateTimeZone.UTC);
    issueDateTime = issueDateTime.plusSeconds(1);
    token.setAttributeNS(null, "IssueInstant", issueDateTime.toString());

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                   FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                               FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);
    String rstr = DOM2Writer.nodeToString(doc);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on signature validation");
    } catch (ProcessingException ex) {
        // expected
    }
}
 
Example 17
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignedAssertionAfterUnsignedAssertion() throws Exception {
    // First assertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

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

    // Second assertion
    SAML2CallbackHandler callbackHandler2 = new SAML2CallbackHandler();
    callbackHandler2.setStatement(SAML2CallbackHandler.Statement.ATTR);
    callbackHandler2.setConfirmationMethod(SAML2Constants.CONF_BEARER);
    callbackHandler2.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler2.setSubjectName("bob");
    ConditionsBean cp2 = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction2 = new AudienceRestrictionBean();
    audienceRestriction2.getAudienceURIs().add(TEST_AUDIENCE);
    cp2.setAudienceRestrictions(Collections.singletonList(audienceRestriction2));
    callbackHandler2.setConditions(cp2);

    SAMLCallback samlCallback2 = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler2, samlCallback2);
    SamlAssertionWrapper assertion2 = new SamlAssertionWrapper(samlCallback2);

    Element rstrElement =
        createResponseWithMultipleAssertions(assertion2, false, assertion1, true, "mystskey");
    String rstr = DOM2Writer.nodeToString(rstrElement);
    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    // Load and update the config to enforce an error
    configurator = null;
    FedizContext config = getFederationConfigurator().getFedizContext("ROOT");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        Assert.fail("Processing must fail because of missing signature");
    } catch (ProcessingException ex) {
        if (!TYPE.TOKEN_NO_SIGNATURE.equals(ex.getType())) {
            fail("Expected ProcessingException with TOKEN_NO_SIGNATURE type");
        }
    }
}
 
Example 18
Source File: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Validate a HolderOfKey SAML 2 token
 */
@org.junit.Test
public void validateHOKSAML2Token() throws Exception {
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_HOLDER_KEY);
    callbackHandler.setIssuer(TEST_RSTR_ISSUER);
    callbackHandler.setSubjectName(TEST_USER);
    ConditionsBean cp = new ConditionsBean();
    AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
    audienceRestriction.getAudienceURIs().add(TEST_AUDIENCE);
    cp.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    callbackHandler.setConditions(cp);

    Crypto clientCrypto = CryptoFactory.getInstance("client-crypto.properties");
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("myclientkey");
    X509Certificate[] certs = clientCrypto.getX509Certificates(cryptoType);
    callbackHandler.setCerts(certs);

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

    WSPasswordCallback[] cb = {
        new WSPasswordCallback("mystskey", WSPasswordCallback.SIGNATURE)
    };
    cbPasswordHandler.handle(cb);
    String password = cb[0].getPassword();

    assertion.signAssertion("mystskey", password, crypto, false);

    Document doc = STSUtil.toSOAPPart(STSUtil.SAMPLE_RSTR_COLL_MSG);
    Element token = assertion.toDOM(doc);

    Element e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                    FederationConstants.WS_TRUST_13_NS);
    if (e == null) {
        e = XMLUtils.findElement(doc, "RequestedSecurityToken",
                                                FederationConstants.WS_TRUST_2005_02_NS);
    }
    e.appendChild(token);

    String rstr = DOM2Writer.nodeToString(doc);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction(FederationConstants.ACTION_SIGNIN);
    wfReq.setResponseToken(rstr);

    configurator = null;
    FedizContext config =
        getFederationConfigurator().getFedizContext("ROOT_DECRYPTION");

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected on missing client certs");
    } catch (ProcessingException ex) {
        // expected
    }

    // Now set client certs
    wfReq.setCerts(certs);
    wfProc.processRequest(wfReq, config);
}
 
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: TrustedIdpSAMLProtocolHandler.java    From cxf-fediz with Apache License 2.0 3 votes vote down vote up
private String encodeAuthnRequest(Element authnRequest) throws IOException {
    String requestMessage = DOM2Writer.nodeToString(authnRequest);

    LOG.debug(requestMessage);

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

    return Base64Utility.encode(deflatedBytes);
}