org.apache.wss4j.common.util.DOM2Writer Java Examples

The following examples show how to use org.apache.wss4j.common.util.DOM2Writer. 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: FederationResponseTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
/**
 * Validate FederationRequest with unknown action
 */
@org.junit.Test
public void validateRequestUnknownAction() throws Exception {
    Document doc = STSUtil.toSOAPPart(STSUtil.SAMPLE_RSTR_COLL_MSG);

    FedizRequest wfReq = new FedizRequest();
    wfReq.setAction("gugus");
    wfReq.setResponseToken(DOM2Writer.nodeToString(doc));

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

    FedizProcessor wfProc = new FederationProcessorImpl();
    try {
        wfProc.processRequest(wfReq, config);
        fail("Failure expected due to invalid action");
    } catch (ProcessingException ex) {
        if (!TYPE.INVALID_REQUEST.equals(ex.getType())) {
            fail("Expected ProcessingException with INVALID_REQUEST type");
        }
    }
}
 
Example #2
Source File: SAMLProviderCustomTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a custom Saml1 Attribute Assertion.
 */
@org.junit.Test
public void testCustomSaml1AttributeAssertion() 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());
    ((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 #3
Source File: SCTProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a SecurityContextToken with a different namespace
 */
@org.junit.Test
public void testCreateSCTDifferentNamespace() throws Exception {
    TokenProvider sctTokenProvider = new SCTProvider();

    TokenProviderParameters providerParameters =
        createProviderParameters(STSUtils.TOKEN_TYPE_SCT_05_02);

    assertTrue(sctTokenProvider.canHandleToken(STSUtils.TOKEN_TYPE_SCT_05_02));
    TokenProviderResponse providerResponse = sctTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(ConversationConstants.WSC_NS_05_02));
    assertFalse(tokenString.contains(ConversationConstants.WSC_NS_05_12));
}
 
Example #4
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 #5
Source File: SCTProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a SecurityContextToken
 */
@org.junit.Test
public void testCreateSCT() throws Exception {
    TokenProvider sctTokenProvider = new SCTProvider();

    TokenProviderParameters providerParameters =
        createProviderParameters(STSUtils.TOKEN_TYPE_SCT_05_12);

    assertTrue(sctTokenProvider.canHandleToken(STSUtils.TOKEN_TYPE_SCT_05_12));
    TokenProviderResponse providerResponse = sctTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(ConversationConstants.WSC_NS_05_12));
    assertFalse(tokenString.contains(ConversationConstants.WSC_NS_05_02));
}
 
Example #6
Source File: RESTSecurityTokenServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Response getPlainToken(String tokenType, String keyType,
                         List<String> requestedClaims, String appliesTo) {
    RequestSecurityTokenResponseType response =
        issueToken(tokenType, keyType, requestedClaims, appliesTo);

    RequestedSecurityTokenType requestedToken = getRequestedSecurityToken(response);

    if ("jwt".equals(tokenType)) {
        // Discard the wrapper here
        return Response.ok(((Element)requestedToken.getAny()).getTextContent()).build();
    }
    // Base-64 encode the token + return it
    try {
        String encodedToken =
            encodeToken(DOM2Writer.nodeToString((Element)requestedToken.getAny()));
        return Response.ok(encodedToken).build();
    } catch (Exception ex) {
        LOG.warning(ex.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
}
 
Example #7
Source File: JAXRSOAuth2Test.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSAML2BearerGrant() throws Exception {
    String address = "https://localhost:" + port + "/oauth2/token";
    WebClient wc = createWebClient(address);

    Crypto crypto = new CryptoLoader().loadCrypto(CRYPTO_RESOURCE_PROPERTIES);
    SelfSignInfo signInfo = new SelfSignInfo(crypto, "alice", "password");

    SamlCallbackHandler samlCallbackHandler = new SamlCallbackHandler(false);
    String audienceURI = "https://localhost:" + port + "/oauth2/token";
    samlCallbackHandler.setAudience(audienceURI);
    SamlAssertionWrapper assertionWrapper = SAMLUtils.createAssertion(samlCallbackHandler,
                                                                      signInfo);
    Document doc = DOMUtils.newDocument();
    Element assertionElement = assertionWrapper.toDOM(doc);
    String assertion = DOM2Writer.nodeToString(assertionElement);

    Saml2BearerGrant grant = new Saml2BearerGrant(assertion);
    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc,
                                    new Consumer("alice", "alice"),
                                    grant,
                                    false);
    assertNotNull(at.getTokenKey());
}
 
Example #8
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 #9
Source File: SAMLProviderCustomTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a custom Saml1 Authentication Assertion.
 */
@org.junit.Test
public void testCustomSaml1AuthenticationAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);

    List<AuthenticationStatementProvider> customProviderList =
        new ArrayList<>();
    customProviderList.add(new CustomAuthenticationProvider());
    ((SAMLTokenProvider)samlTokenProvider).setAuthenticationStatementProviders(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()));
    assertFalse(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("AuthenticationStatement"));
    assertTrue(tokenString.contains(SAML1Constants.AUTH_METHOD_X509));
    assertTrue(tokenString.contains("alice"));
}
 
Example #10
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 #11
Source File: SAMLProviderCustomTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a custom Saml2 AuthDecision Assertion.
 */
@org.junit.Test
public void testCustomSaml2AuthDecisionAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);

    List<AuthDecisionStatementProvider> customProviderList =
        new ArrayList<>();
    customProviderList.add(new CustomAuthDecisionProvider());
    ((SAMLTokenProvider)samlTokenProvider).setAuthDecisionStatementProviders(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"));
    assertFalse(tokenString.contains("AuthnStatement"));
    assertTrue(tokenString.contains("AuthzDecisionStatement"));
    assertTrue(tokenString.contains("alice"));
}
 
Example #12
Source File: SAMLProviderCustomTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Saml1 Assertion with a custom NameID Format of the Subject
 */
@org.junit.Test
public void testCustomSaml1SubjectNameIDFormat() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);

    DefaultSubjectProvider subjectProvider = new DefaultSubjectProvider();
    subjectProvider.setSubjectNameIDFormat(SAML1Constants.NAMEID_FORMAT_EMAIL_ADDRESS);
    ((SAMLTokenProvider)samlTokenProvider).setSubjectProvider(subjectProvider);

    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.NAMEID_FORMAT_EMAIL_ADDRESS));
}
 
Example #13
Source File: MetadataDocumentHandler.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
    LOG.debug("Metadata document requested");
    FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedizConfig.getProtocol());
    try (PrintWriter out = response.getWriter()) {
        Document metadata = wfProc.getMetaData(request, fedizConfig);
        out.write(DOM2Writer.nodeToString(metadata));
        response.setContentType("text/xml");
        return true;
    } catch (Exception ex) {
        LOG.error("Failed to get metadata document: {}", ex.getMessage());
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            LOG.error("Failed to send error response: {}", e.getMessage());
        }
        return false;
    }
}
 
Example #14
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 #15
Source File: SAMLProviderKeyTypeTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a default Saml1 Bearer Assertion that uses a KeyValue to sign the Assertion.
 */
@org.junit.Test
public void testDefaultSaml1BearerKeyValueAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);

    providerParameters.getStsProperties().getSignatureProperties().setUseKeyValue(true);
    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));
    assertTrue(tokenString.contains("KeyValue"));
}
 
Example #16
Source File: SAMLProviderKeyTypeTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a default Saml2 Unsigned Bearer Assertion.
 */
@org.junit.Test
public void testDefaultSaml2BearerUnsignedAssertion() 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));

    providerParameters.getStsProperties().setSignatureCrypto(null);
    ((SAMLTokenProvider)samlTokenProvider).setSignToken(false);

    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));
    assertFalse(tokenString.contains("Signature"));
}
 
Example #17
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 #18
Source File: SAMLProviderCustomTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a Saml1 Attribute Assertion with a custom Subject
 */
@org.junit.Test
public void testCustomSaml1SubjectAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE);

    ((SAMLTokenProvider)samlTokenProvider).setSubjectProvider(new CustomSubjectProvider());

    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 #19
Source File: SAMLProviderLifetimeTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Issue SAML 2 token with a lifetime configured in SAMLTokenProvider
 * No specific lifetime requested
 */
@org.junit.Test
public void testSaml2ProviderLifetime() throws Exception {

    long providerLifetime = 10 * 600L;
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider();
    conditionsProvider.setLifetime(providerLifetime);
    samlTokenProvider.setConditionsProvider(conditionsProvider);

    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);
    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(providerLifetime, duration);
    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
}
 
Example #20
Source File: SAMLProviderKeyTypeTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Create a default Saml1 Bearer Assertion.
 */
@org.junit.Test
public void testDefaultSaml1BearerAssertion() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(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 #21
Source File: SamlHeaderOutInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    try {
        SamlAssertionWrapper assertionWrapper = createAssertion(message);

        Document doc = DOMUtils.newDocument();
        Element assertionElement = assertionWrapper.toDOM(doc);
        String encodedToken = encodeToken(DOM2Writer.nodeToString(assertionElement));

        Map<String, List<String>> headers = getHeaders(message);

        StringBuilder builder = new StringBuilder();
        builder.append("SAML").append(' ').append(encodedToken);
        headers.put("Authorization",
            CastUtils.cast(Collections.singletonList(builder.toString()), String.class));

    } catch (Exception ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        LOG.warning(sw.toString());
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example #22
Source File: SamlSso.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
protected String encodeResponse(Element response, boolean redirect) throws IOException {
    String responseMessage = DOM2Writer.nodeToString(response);
    System.out.println("RESP: " + responseMessage);

    byte[] deflatedBytes = null;
    if (redirect) {
        DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
        deflatedBytes = encoder.deflateToken(responseMessage.getBytes(StandardCharsets.UTF_8));
    } else {
        deflatedBytes = responseMessage.getBytes(StandardCharsets.UTF_8);
    }

    return Base64Utility.encode(deflatedBytes);
}
 
Example #23
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 #24
Source File: MetadataWriterTest.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteIDPMetadata() {
    ConfigService config = (ConfigService)applicationContext.getBean("config");
    Assert.notNull(config, "ConfigService must not be null");
    Idp idpConfig = config.getIDP("urn:org:apache:cxf:fediz:idp:realm-A");
    Assert.notNull(idpConfig, "IDPConfig must not be null");

    IdpMetadataWriter writer = new IdpMetadataWriter();
    Document doc = writer.getMetaData(idpConfig);
    Assert.notNull(doc, "doc must not be null");

    System.out.println(DOM2Writer.nodeToString(doc));

}
 
Example #25
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 #26
Source File: SAMLProviderLifetimeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Issue SAML 2 token with no Expires element. This will be rejected, but will default to the
 * configured TTL and so the request will pass.
 */
@org.junit.Test
public void testSaml2NoExpires() throws Exception {

    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider();
    conditionsProvider.setAcceptClientLifetime(true);
    conditionsProvider.setFutureTimeToLive(180L);
    samlTokenProvider.setConditionsProvider(conditionsProvider);

    TokenProviderParameters providerParameters =
        createProviderParameters(
            WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE
        );

    // Set expected lifetime to 1 minute
    Instant creationTime = Instant.now().plusSeconds(120L);

    Lifetime lifetime = new Lifetime();
    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));

    providerParameters.getTokenRequirements().setLifetime(lifetime);

    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));

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

    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(conditionsProvider.getLifetime(), duration);
    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
}
 
Example #27
Source File: FedizRedirectBindingFilter.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private boolean isMetadataRequest(ContainerRequestContext context, FedizContext fedConfig) {
    String requestPath = context.getUriInfo().getPath();
    // See if it is a Metadata request
    if (requestPath.indexOf(FederationConstants.METADATA_PATH_URI) != -1
        || requestPath.indexOf(getMetadataURI(fedConfig)) != -1) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Metadata document requested");
        }

        FedizProcessor wfProc =
            FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
        try {
            HttpServletRequest request = messageContext.getHttpServletRequest();
            Document metadata = wfProc.getMetaData(request, fedConfig);
            String metadataStr = DOM2Writer.nodeToString(metadata);

            ResponseBuilder response = Response.ok(metadataStr, "text/xml");
            context.abortWith(response.build());
            return true;
        } catch (Exception ex) {
            LOG.error("Failed to get metadata document: " + ex.getMessage());
            throw ExceptionUtils.toInternalServerErrorException(ex, null);
        }
    }

    return false;
}
 
Example #28
Source File: SAMLProviderLifetimeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Issue SAML 2 token with a near future Created Lifetime. This should pass as we allow a future
 * dated Lifetime up to 60 seconds to avoid clock skew problems.
 */
@org.junit.Test
public void testSaml2NearFutureCreatedLifetime() throws Exception {

    int requestedLifetime = 60;
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider();
    conditionsProvider.setAcceptClientLifetime(true);
    samlTokenProvider.setConditionsProvider(conditionsProvider);

    TokenProviderParameters providerParameters =
        createProviderParameters(
            WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE
        );

    // Set expected lifetime to 1 minute
    Instant creationTime = Instant.now();
    Instant expirationTime = creationTime.plusSeconds(requestedLifetime);
    creationTime = creationTime.plusSeconds(10L);

    Lifetime lifetime = new Lifetime();
    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));

    providerParameters.getTokenRequirements().setLifetime(lifetime);

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

    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(50, duration);
    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
}
 
Example #29
Source File: SAMLProviderLifetimeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Issue SAML 2 token with a valid requested lifetime
 */
@org.junit.Test
public void testSaml2ValidLifetime() throws Exception {

    int requestedLifetime = 60;
    SAMLTokenProvider samlTokenProvider = new SAMLTokenProvider();
    DefaultConditionsProvider conditionsProvider = new DefaultConditionsProvider();
    conditionsProvider.setAcceptClientLifetime(true);
    samlTokenProvider.setConditionsProvider(conditionsProvider);

    TokenProviderParameters providerParameters =
        createProviderParameters(
            WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE
        );

    // Set expected lifetime to 1 minute
    Lifetime lifetime = new Lifetime();
    Instant creationTime = Instant.now();
    Instant expirationTime = creationTime.plusSeconds(requestedLifetime);

    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    providerParameters.getTokenRequirements().setLifetime(lifetime);

    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);
    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(requestedLifetime, duration);
    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
}
 
Example #30
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());
}