Java Code Examples for org.apache.cxf.helpers.DOMUtils#createDocument()

The following examples show how to use org.apache.cxf.helpers.DOMUtils#createDocument() . 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: WSSUsernameCallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof DelegationCallback) {
            DelegationCallback callback = (DelegationCallback) callbacks[i];
            Message message = callback.getCurrentMessage();
            
            String username = 
                (String)message.getContextualProperty(SecurityConstants.USERNAME);
            if (username != null) {
                Node contentNode = message.getContent(Node.class);
                Document doc = null;
                if (contentNode != null) {
                    doc = contentNode.getOwnerDocument();
                } else {
                    doc = DOMUtils.createDocument();
                }
                UsernameToken usernameToken = createWSSEUsernameToken(username, doc);
                callback.setToken(usernameToken.getElement());
            }
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example 2
Source File: SonosFaultInterceptor.java    From subsonic with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void handleMessage(SoapMessage message) throws Fault {
    Fault fault = (Fault) message.getContent(Exception.class);
    LOG.warn("Error: " + fault, fault);

    if (fault.getCause() instanceof SonosSoapFault) {
        SonosSoapFault cause = (SonosSoapFault) fault.getCause();
        fault.setFaultCode(new QName(cause.getFaultCode()));
        fault.setMessage(cause.getFaultCode());

        Document document = DOMUtils.createDocument();
        Element details = document.createElement("detail");
        fault.setDetail(details);

        details.appendChild(document.createElement("ExceptionInfo"));

        Element sonosError = document.createElement("SonosError");
        sonosError.setTextContent(String.valueOf(cause.getSonosError()));
        details.appendChild(sonosError);
    }
}
 
Example 3
Source File: UsernameTokenInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
private Header findSecurityHeader(SoapMessage message, boolean create) {
    for (Header h : message.getHeaders()) {
        QName n = h.getName();
        if (n.getLocalPart().equals("Security")
            && (n.getNamespaceURI().equals(WSConstants.WSSE_NS) 
                || n.getNamespaceURI().equals(WSConstants.WSSE11_NS))) {
            return h;
        }
    }
    if (!create) {
        return null;
    }
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Security");
    el.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
    SoapHeader sh = new SoapHeader(new QName(WSConstants.WSSE_NS, "Security"), el);
    sh.setMustUnderstand(true);
    message.getHeaders().add(sh);
    return sh;
}
 
Example 4
Source File: KerberosClient.java    From steady with Apache License 2.0 6 votes vote down vote up
public SecurityToken requestSecurityToken() throws Exception {
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Requesting Kerberos ticket for " + serviceName 
                + " using JAAS Login Module: " + getContextName());
    }
    KerberosSecurity bst = new KerberosSecurity(DOMUtils.createDocument());
    bst.retrieveServiceTicket(getContextName(), callbackHandler, serviceName);
    bst.addWSUNamespace();
    bst.setID(wssConfig.getIdAllocator().createSecureId("BST-", bst));
    
    SecurityToken token = new SecurityToken(bst.getID());
    token.setToken(bst.getElement());
    token.setWsuId(bst.getID());
    SecretKey secretKey = bst.getSecretKey();
    if (secretKey != null) {
        token.setSecret(secretKey.getEncoded());
    }
    String sha1 = Base64.encode(WSSecurityUtil.generateDigest(bst.getToken()));
    token.setSHA1(sha1);
    token.setTokenType(bst.getValueType());

    return token;
}
 
Example 5
Source File: WSSUsernameCallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof DelegationCallback) {
            DelegationCallback callback = (DelegationCallback) callbacks[i];
            Message message = callback.getCurrentMessage();
            
            String username = 
                (String)message.getContextualProperty(SecurityConstants.USERNAME);
            if (username != null) {
                Node contentNode = message.getContent(Node.class);
                Document doc = null;
                if (contentNode != null) {
                    doc = contentNode.getOwnerDocument();
                } else {
                    doc = DOMUtils.createDocument();
                }
                UsernameToken usernameToken = createWSSEUsernameToken(username, doc);
                callback.setToken(usernameToken.getElement());
            }
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example 6
Source File: UsernameTokenInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
private Header findSecurityHeader(SoapMessage message, boolean create) {
    for (Header h : message.getHeaders()) {
        QName n = h.getName();
        if (n.getLocalPart().equals("Security")
            && (n.getNamespaceURI().equals(WSConstants.WSSE_NS) 
                || n.getNamespaceURI().equals(WSConstants.WSSE11_NS))) {
            return h;
        }
    }
    if (!create) {
        return null;
    }
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Security");
    el.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
    SoapHeader sh = new SoapHeader(new QName(WSConstants.WSSE_NS, "Security"), el);
    sh.setMustUnderstand(true);
    message.getHeaders().add(sh);
    return sh;
}
 
Example 7
Source File: SamlRetrievalInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void handleMessage(Message message) throws Fault {

    // Create a SAML Token
    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(new SamlCallbackHandler(), samlCallback);

    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
        Document doc = DOMUtils.createDocument();
        Element token = assertion.toDOM(doc);
        message.put(SAMLConstants.SAML_TOKEN_ELEMENT, token);
    } catch (WSSecurityException ex) {
        StringWriter sw = new StringWriter();
        ex.printStackTrace(new PrintWriter(sw));
        throw new Fault(new RuntimeException(ex.getMessage() + ", stacktrace: " + sw.toString()));
    }

}
 
Example 8
Source File: SCTValidatorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Test an invalid SecurityContextToken
 */
@org.junit.Test
public void testInvalidSecurityContextToken() throws Exception {
    TokenValidator sctValidator = new SCTValidator();
    TokenValidatorParameters validatorParameters = createValidatorParameters();
    TokenRequirements tokenRequirements = validatorParameters.getTokenRequirements();

    // Create a ValidateTarget consisting of a SecurityContextToken
    Document doc = DOMUtils.createDocument();
    SecurityContextToken sct = new SecurityContextToken(doc);
    ReceivedToken validateTarget = new ReceivedToken(sct.getElement());
    tokenRequirements.setValidateTarget(validateTarget);
    validatorParameters.setToken(validateTarget);

    assertTrue(sctValidator.canHandleToken(validateTarget));

    TokenValidatorResponse validatorResponse =
        sctValidator.validateToken(validatorParameters);
    assertNotNull(validatorResponse);
    assertNotNull(validatorResponse.getToken());
    assertTrue(validatorResponse.getToken().getState() == STATE.INVALID);
}
 
Example 9
Source File: SamlTokenInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
private Header findSecurityHeader(SoapMessage message, boolean create) {
    for (Header h : message.getHeaders()) {
        QName n = h.getName();
        if (n.getLocalPart().equals("Security")
            && (n.getNamespaceURI().equals(WSConstants.WSSE_NS) 
                || n.getNamespaceURI().equals(WSConstants.WSSE11_NS))) {
            return h;
        }
    }
    if (!create) {
        return null;
    }
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(WSConstants.WSSE_NS, "wsse:Security");
    el.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:wsse", WSConstants.WSSE_NS);
    SoapHeader sh = new SoapHeader(new QName(WSConstants.WSSE_NS, "Security"), el);
    sh.setMustUnderstand(true);
    message.getHeaders().add(sh);
    return sh;
}
 
Example 10
Source File: WSSUsernameCallbackHandler.java    From steady with Apache License 2.0 6 votes vote down vote up
public void handle(Callback[] callbacks)
    throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof DelegationCallback) {
            DelegationCallback callback = (DelegationCallback) callbacks[i];
            Message message = callback.getCurrentMessage();
            
            String username = 
                (String)message.getContextualProperty(SecurityConstants.USERNAME);
            if (username != null) {
                Node contentNode = message.getContent(Node.class);
                Document doc = null;
                if (contentNode != null) {
                    doc = contentNode.getOwnerDocument();
                } else {
                    doc = DOMUtils.createDocument();
                }
                UsernameToken usernameToken = createWSSEUsernameToken(username, doc);
                callback.setToken(usernameToken.getElement());
            }
        } else {
            throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
        }
    }
}
 
Example 11
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 12
Source File: XSLTResourceTransformer.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public ResourceValidator transform(Representation newRepresentation, Representation oldRepresentation) {
    Document doc = DOMUtils.createDocument();
    Node representation = (Node) newRepresentation.getAny();
    Node importedNode = doc.importNode(representation, true);
    doc.appendChild(importedNode);
    Document result = XSLTUtils.transform(templates, doc);
    newRepresentation.setAny(result.getDocumentElement());
    return validator;
}
 
Example 13
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 14
Source File: SamlElementCallbackHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof SAMLCallback) {
            SAMLCallback callback = (SAMLCallback) callbacks[i];
            Element assertionElement;
            try {
                Document doc = DOMUtils.createDocument();
                assertionElement = getSAMLAssertion(doc);
            } catch (Exception e) {
                throw new IOException(e.getMessage());
            }
            callback.setAssertionElement(assertionElement);
        }
    }
}
 
Example 15
Source File: SAMLTokenProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Create a token given a TokenProviderParameters
 */
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    testKeyType(tokenParameters);
    KeyRequirements keyRequirements = tokenParameters.getKeyRequirements();
    TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Handling token of type: " + tokenRequirements.getTokenType());
    }

    byte[] secret = null;
    byte[] entropyBytes = null;
    long keySize = 0;
    boolean computedKey = false;
    if (STSConstants.SYMMETRIC_KEY_KEYTYPE.equals(keyRequirements.getKeyType())) {
        SymmetricKeyHandler keyHandler = new SymmetricKeyHandler(tokenParameters);
        keyHandler.createSymmetricKey();
        secret = keyHandler.getSecret();
        entropyBytes = keyHandler.getEntropyBytes();
        keySize = keyHandler.getKeySize();
        computedKey = keyHandler.isComputedKey();
    }

    try {
        Document doc = DOMUtils.createDocument();
        SamlAssertionWrapper assertion = createSamlToken(tokenParameters, secret, doc);
        Element token = assertion.toDOM(doc);

        // set the token in cache (only if the token is signed)
        byte[] signatureValue = assertion.getSignatureValue();
        if (tokenParameters.getTokenStore() != null && signatureValue != null
            && signatureValue.length > 0) {

            SecurityToken securityToken =
                CacheUtils.createSecurityTokenForStorage(token, assertion.getId(),
                    assertion.getNotOnOrAfter(), tokenParameters.getPrincipal(), tokenParameters.getRealm(),
                    tokenParameters.getTokenRequirements().getRenewing());
            CacheUtils.storeTokenInCache(
                securityToken, tokenParameters.getTokenStore(), signatureValue);
        }

        TokenProviderResponse response = new TokenProviderResponse();

        String tokenType = tokenRequirements.getTokenType();
        if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
            || WSS4JConstants.SAML2_NS.equals(tokenType)) {
            response.setTokenId(token.getAttributeNS(null, "ID"));
        } else {
            response.setTokenId(token.getAttributeNS(null, "AssertionID"));
        }

        if (tokenParameters.isEncryptToken()) {
            token = TokenProviderUtils.encryptToken(token, response.getTokenId(),
                                                    tokenParameters.getStsProperties(),
                                                    tokenParameters.getEncryptionProperties(),
                                                    keyRequirements,
                                                    tokenParameters.getMessageContext());
        }
        response.setToken(token);

        DateTime validFrom = null;
        DateTime validTill = null;
        if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
            validFrom = assertion.getSaml2().getConditions().getNotBefore();
            validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
        } else {
            validFrom = assertion.getSaml1().getConditions().getNotBefore();
            validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
        }
        response.setCreated(validFrom.toDate().toInstant());
        response.setExpires(validTill.toDate().toInstant());

        response.setEntropy(entropyBytes);
        if (keySize > 0) {
            response.setKeySize(keySize);
        }
        response.setComputedKey(computedKey);

        LOG.fine("SAML Token successfully created");
        if (secret != null) {
            Arrays.fill(secret, (byte) 0);
        }
        return response;
    } catch (Exception e) {
        LOG.log(Level.WARNING, "", e);
        throw new STSException("Can't serialize SAML assertion", e, STSException.REQUEST_FAILED);
    }
}
 
Example 16
Source File: SAMLResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testResponseIssueInstant() throws Exception {
    Document doc = DOMUtils.createDocument();

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

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

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

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

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

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

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

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    try {
        validator.validateSamlResponse(marshalledResponse, null, null);
        fail("Expected failure on an invalid Response IssueInstant");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 17
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Renew a token given a TokenRenewerParameters
 */
public TokenRenewerResponse renewToken(TokenRenewerParameters tokenParameters) {
    TokenRenewerResponse response = new TokenRenewerResponse();
    ReceivedToken tokenToRenew = tokenParameters.getToken();
    if (tokenToRenew == null || tokenToRenew.getToken() == null
        || (tokenToRenew.getState() != STATE.EXPIRED && tokenToRenew.getState() != STATE.VALID)) {
        LOG.log(Level.WARNING, "The token to renew is null or invalid");
        throw new STSException(
            "The token to renew is null or invalid", STSException.INVALID_REQUEST
        );
    }

    TokenStore tokenStore = tokenParameters.getTokenStore();
    if (tokenStore == null) {
        LOG.log(Level.FINE, "A cache must be configured to use the SAMLTokenRenewer");
        throw new STSException("Can't renew SAML assertion", STSException.REQUEST_FAILED);
    }

    try {
        SamlAssertionWrapper assertion = new SamlAssertionWrapper((Element)tokenToRenew.getToken());

        byte[] oldSignature = assertion.getSignatureValue();
        int hash = Arrays.hashCode(oldSignature);
        SecurityToken cachedToken = tokenStore.getToken(Integer.toString(hash));
        if (cachedToken == null) {
            LOG.log(Level.FINE, "The token to be renewed must be stored in the cache");
            throw new STSException("Can't renew SAML assertion", STSException.REQUEST_FAILED);
        }

        // Validate the Assertion
        validateAssertion(assertion, tokenToRenew, cachedToken, tokenParameters);

        SamlAssertionWrapper renewedAssertion = new SamlAssertionWrapper(assertion.getSamlObject());
        String oldId = createNewId(renewedAssertion);
        // Remove the previous token (now expired) from the cache
        tokenStore.remove(oldId);
        tokenStore.remove(Integer.toString(hash));

        // Create new Conditions & sign the Assertion
        createNewConditions(renewedAssertion, tokenParameters);
        signAssertion(renewedAssertion, tokenParameters);

        Document doc = DOMUtils.createDocument();
        Element token = renewedAssertion.toDOM(doc);
        if (renewedAssertion.getSaml1() != null) {
            token.setIdAttributeNS(null, "AssertionID", true);
        } else {
            token.setIdAttributeNS(null, "ID", true);
        }
        doc.appendChild(token);

        // Cache the token
        storeTokenInCache(
            tokenStore, renewedAssertion, tokenParameters.getPrincipal(), tokenParameters
        );

        response.setToken(token);
        response.setTokenId(renewedAssertion.getId());

        DateTime validFrom = null;
        DateTime validTill = null;
        if (renewedAssertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
            validFrom = renewedAssertion.getSaml2().getConditions().getNotBefore();
            validTill = renewedAssertion.getSaml2().getConditions().getNotOnOrAfter();
        } else {
            validFrom = renewedAssertion.getSaml1().getConditions().getNotBefore();
            validTill = renewedAssertion.getSaml1().getConditions().getNotOnOrAfter();
        }
        response.setCreated(validFrom.toDate().toInstant());
        response.setExpires(validTill.toDate().toInstant());

        LOG.fine("SAML Token successfully renewed");
        return response;
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "", ex);
        throw new STSException("Can't renew SAML assertion", ex, STSException.REQUEST_FAILED);
    }
}
 
Example 18
Source File: CombinedValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulSignedValidation() throws Exception {

    Document doc = DOMUtils.createDocument();
    Response response = createResponse(doc);

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

    signResponse(response, "alice", "password", issuerCrypto, true);

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

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

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    validator.validateSamlResponse(
        marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
    );

    // Test SSO validation
    SAMLSSOResponseValidator ssoValidator = new SAMLSSOResponseValidator();
    ssoValidator.setIssuerIDP("http://cxf.apache.org/issuer");
    ssoValidator.setAssertionConsumerURL("http://recipient.apache.org");
    ssoValidator.setClientAddress("http://apache.org");
    ssoValidator.setRequestId("12345");
    ssoValidator.setSpIdentifier("http://service.apache.org");

    // Parse the response
    SSOValidatorResponse ssoResponse =
        ssoValidator.validateSamlResponse(marshalledResponse, false);
    SamlAssertionWrapper parsedAssertion =
        new SamlAssertionWrapper(ssoResponse.getAssertionElement());

    assertEquals("alice", parsedAssertion.getSubjectName());
}
 
Example 19
Source File: MemoryResourceManagerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void beforeClass() throws ParserConfigurationException {
    document = DOMUtils.createDocument();
}
 
Example 20
Source File: CombinedValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSuccessfulValidation() throws Exception {

    Document doc = DOMUtils.createDocument();

    Response response = createResponse(doc);

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

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

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

    // Validate the Response
    SAMLProtocolResponseValidator validator = new SAMLProtocolResponseValidator();
    validator.validateSamlResponse(
        marshalledResponse, issuerCrypto, new KeystorePasswordCallback()
    );

    // Test SSO validation
    SAMLSSOResponseValidator ssoValidator = new SAMLSSOResponseValidator();
    ssoValidator.setIssuerIDP("http://cxf.apache.org/issuer");
    ssoValidator.setAssertionConsumerURL("http://recipient.apache.org");
    ssoValidator.setClientAddress("http://apache.org");
    ssoValidator.setRequestId("12345");
    ssoValidator.setSpIdentifier("http://service.apache.org");

    // Parse the response
    SSOValidatorResponse ssoResponse =
        ssoValidator.validateSamlResponse(marshalledResponse, false);
    SamlAssertionWrapper parsedAssertion =
        new SamlAssertionWrapper(ssoResponse.getAssertionElement());

    assertEquals("alice", parsedAssertion.getSubjectName());
}