Java Code Examples for org.apache.cxf.staxutils.W3CDOMStreamWriter#writeStartElement()

The following examples show how to use org.apache.cxf.staxutils.W3CDOMStreamWriter#writeStartElement() . 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: STSRESTTest.java    From cxf with Apache License 2.0 7 votes vote down vote up
@org.junit.Test
public void testIssueSAML2TokenViaPOST() throws Exception {
    WebClient client = webClient()
        .type(MediaType.APPLICATION_XML)
        .accept(MediaType.APPLICATION_XML);

    // Create RequestSecurityToken
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", WST_NS_05_12);

    writer.writeStartElement("wst", "RequestType", WST_NS_05_12);
    writer.writeCharacters(WST_NS_05_12 + "/Issue");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", WST_NS_05_12);
    writer.writeCharacters(SAML2_TOKEN_TYPE);
    writer.writeEndElement();

    writer.writeEndElement();

    RequestSecurityTokenResponseType securityResponse = client.post(
        new DOMSource(writer.getDocument().getDocumentElement()),
        RequestSecurityTokenResponseType.class);

    validateSAMLSecurityTokenResponse(securityResponse, true);
}
 
Example 2
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 6 votes vote down vote up
protected String writeKeyType(W3CDOMStreamWriter writer, String keyTypeToWrite) 
    throws XMLStreamException {
    if (isSecureConv) {
        if (keyTypeToWrite == null) {
            writer.writeStartElement("wst", "TokenType", namespace);
            writer.writeCharacters(STSUtils.getTokenTypeSCT(namespace));
            writer.writeEndElement();
            keyTypeToWrite = namespace + "/SymmetricKey";
        }
    } else if (keyTypeToWrite == null && sendKeyType) {
        writer.writeStartElement("wst", "KeyType", namespace);
        writer.writeCharacters(namespace + "/SymmetricKey");
        writer.writeEndElement();
        keyTypeToWrite = namespace + "/SymmetricKey";
    } else if (keyTypeToWrite != null) {
        writer.writeStartElement("wst", "KeyType", namespace);
        writer.writeCharacters(keyTypeToWrite);
        writer.writeEndElement();
    }
    return keyTypeToWrite;
}
 
Example 3
Source File: STSClientAction.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private Element createClaimsElement(List<RequestClaim> realmClaims)
    throws ParserConfigurationException, XMLStreamException {
    if (realmClaims == null || realmClaims.isEmpty()) {
        return null;
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "Claims", STSUtils.WST_NS_05_12);
    writer.writeNamespace("wst", STSUtils.WST_NS_05_12);
    writer.writeNamespace("ic", HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);
    writer.writeAttribute("Dialect", HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);

    if (!realmClaims.isEmpty()) {
        for (RequestClaim item : realmClaims) {
            LOG.debug("  {}", item.getClaimType().toString());
            writer.writeStartElement("ic", "ClaimType", HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);
            writer.writeAttribute("Uri", item.getClaimType().toString());
            writer.writeAttribute("Optional", Boolean.toString(item.isOptional()));
            writer.writeEndElement();
        }
    }

    writer.writeEndElement();

    return writer.getDocument().getDocumentElement();
}
 
Example 4
Source File: SpnegoContextTokenInInterceptor.java    From steady with Apache License 2.0 6 votes vote down vote up
private void writeProofToken(
    W3CDOMStreamWriter writer,
    String prefix, 
    String namespace,
    byte[] key
) throws Exception {
    // RequestedProofToken
    writer.writeStartElement(prefix, "RequestedProofToken", namespace);
    
    // EncryptedKey
    writer.writeStartElement(WSConstants.ENC_PREFIX, "EncryptedKey", WSConstants.ENC_NS);
    writer.writeStartElement(WSConstants.ENC_PREFIX, "EncryptionMethod", WSConstants.ENC_NS);
    writer.writeAttribute("Algorithm", namespace + "/spnego#GSS_Wrap");
    writer.writeEndElement();
    writer.writeStartElement(WSConstants.ENC_PREFIX, "CipherData", WSConstants.ENC_NS);
    writer.writeStartElement(WSConstants.ENC_PREFIX, "CipherValue", WSConstants.ENC_NS);

    writer.writeCharacters(Base64.encode(key));
    
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndElement();
    
    writer.writeEndElement();
}
 
Example 5
Source File: SecurityTokenTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testLifetimeNoExpires() throws Exception {
    String key = "key";
    Element tokenElement = DOMUtils.createDocument().createElement("token");

    // Create Lifetime
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    Instant created = Instant.now().truncatedTo(ChronoUnit.MILLIS);

    writer.writeStartElement("wst", "Lifetime", WST_NS_05_12);
    writer.writeStartElement("wsu", "Created", WSU_NS);
    writer.writeCharacters(created.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    writer.writeEndElement();

    writer.writeEndElement();

    SecurityToken token = new SecurityToken(key, tokenElement, writer.getDocument().getDocumentElement());
    assertEquals(key, token.getId());
    assertEquals(created, token.getCreated());
    assertNull(token.getExpires());
}
 
Example 6
Source File: AbstractSTSTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected Element createClaimsElement(List<String> realmClaims) throws Exception {
    if (realmClaims == null || realmClaims.isEmpty()) {
        return null;
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "Claims", STSUtils.WST_NS_05_12);
    writer.writeNamespace("wst", STSUtils.WST_NS_05_12);
    writer.writeNamespace("ic", "http://schemas.xmlsoap.org/ws/2005/05/identity");
    writer.writeAttribute("Dialect", "http://schemas.xmlsoap.org/ws/2005/05/identity");

    if (realmClaims != null && !realmClaims.isEmpty()) {
        for (String item : realmClaims) {
            writer.writeStartElement("ic", "ClaimType", "http://schemas.xmlsoap.org/ws/2005/05/identity");
            writer.writeAttribute("Uri", item);
            //writer.writeAttribute("Optional", "true");
            writer.writeEndElement();
        }
    }

    writer.writeEndElement();

    return writer.getDocument().getDocumentElement();
}
 
Example 7
Source File: STSInvoker.java    From steady with Apache License 2.0 6 votes vote down vote up
void writeLifetime(
    W3CDOMStreamWriter writer,
    Date created,
    Date expires,
    String prefix,
    String namespace
) throws Exception {
    XmlSchemaDateFormat fmt = new XmlSchemaDateFormat();
    writer.writeStartElement(prefix, "Lifetime", namespace);
    writer.writeNamespace("wsu", WSConstants.WSU_NS);
    writer.writeStartElement("wsu", "Created", WSConstants.WSU_NS);
    writer.writeCharacters(fmt.format(created.getTime()));
    writer.writeEndElement();
    
    writer.writeStartElement("wsu", "Expires", WSConstants.WSU_NS);
    writer.writeCharacters(fmt.format(expires.getTime()));
    writer.writeEndElement();
    writer.writeEndElement();
}
 
Example 8
Source File: SimpleBatchSTSClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] writeElementsForRSTSymmetricKey(W3CDOMStreamWriter writer,
        boolean wroteKeySize) throws Exception {
    byte[] requestorEntropy = null;

    if (!wroteKeySize && (!isSecureConv || keySize != 256)) {
        addKeySize(keySize, writer);
    }

    if (requiresEntropy) {
        writer.writeStartElement("wst", "Entropy", namespace);
        writer.writeStartElement("wst", "BinarySecret", namespace);
        writer.writeAttribute("Type", namespace + "/Nonce");
        if (algorithmSuite == null) {
            requestorEntropy = WSSecurityUtil.generateNonce(keySize / 8);
        } else {
            AlgorithmSuiteType algType = algorithmSuite.getAlgorithmSuiteType();
            requestorEntropy = WSSecurityUtil
                .generateNonce(algType.getMaximumSymmetricKeyLength() / 8);
        }
        writer.writeCharacters(Base64.getMimeEncoder().encodeToString(requestorEntropy));

        writer.writeEndElement();
        writer.writeEndElement();
        writer.writeStartElement("wst", "ComputedKeyAlgorithm", namespace);
        writer.writeCharacters(namespace + "/CK/PSHA1");
        writer.writeEndElement();
    }
    return requestorEntropy;
}
 
Example 9
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 5 votes vote down vote up
protected byte[] writeElementsForRSTSymmetricKey(W3CDOMStreamWriter writer,
        boolean wroteKeySize) throws Exception {
    byte[] requestorEntropy = null;

    if (!wroteKeySize && (!isSecureConv || keySize != 256)) {
        addKeySize(keySize, writer);
    }

    if (requiresEntropy) {
        writer.writeStartElement("wst", "Entropy", namespace);
        writer.writeStartElement("wst", "BinarySecret", namespace);
        writer.writeAttribute("Type", namespace + "/Nonce");
        if (algorithmSuite == null) {
            requestorEntropy = WSSecurityUtil.generateNonce(keySize / 8);
        } else {
            requestorEntropy = WSSecurityUtil
                .generateNonce(algorithmSuite.getMaximumSymmetricKeyLength() / 8);
        }
        writer.writeCharacters(Base64.encode(requestorEntropy));

        writer.writeEndElement();
        writer.writeEndElement();
        writer.writeStartElement("wst", "ComputedKeyAlgorithm", namespace);
        writer.writeCharacters(namespace + "/CK/PSHA1");
        writer.writeEndElement();
    }
    return requestorEntropy;
}
 
Example 10
Source File: AbstractSTSClient.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void addBinaryExchange(
    String binaryExchange,
    W3CDOMStreamWriter writer
) throws XMLStreamException {
    writer.writeStartElement("wst", "BinaryExchange", namespace);
    writer.writeAttribute("EncodingType", WSS4JConstants.BASE64_ENCODING);
    writer.writeAttribute("ValueType", namespace + "/spnego");
    writer.writeCharacters(binaryExchange);
    writer.writeEndElement();
}
 
Example 11
Source File: STSInvoker.java    From steady with Apache License 2.0 5 votes vote down vote up
byte[] writeProofToken(String prefix, 
    String namespace,
    W3CDOMStreamWriter writer,
    byte[] clientEntropy,
    int keySize
) throws NoSuchAlgorithmException, WSSecurityException, ConversationException, XMLStreamException {
    byte secret[] = null; 
    writer.writeStartElement(prefix, "RequestedProofToken", namespace);
    if (clientEntropy == null) {
        secret = WSSecurityUtil.generateNonce(keySize / 8);

        writer.writeStartElement(prefix, "BinarySecret", namespace);
        writer.writeAttribute("Type", namespace + "/Nonce");
        writer.writeCharacters(Base64.encode(secret));
        writer.writeEndElement();
    } else {
        byte entropy[] = WSSecurityUtil.generateNonce(keySize / 8);
        P_SHA1 psha1 = new P_SHA1();
        secret = psha1.createKey(clientEntropy, entropy, 0, keySize / 8);

        writer.writeStartElement(prefix, "ComputedKey", namespace);
        writer.writeCharacters(namespace + "/CK/PSHA1");            
        writer.writeEndElement();
        writer.writeEndElement();

        writer.writeStartElement(prefix, "Entropy", namespace);
        writer.writeStartElement(prefix, "BinarySecret", namespace);
        writer.writeAttribute("Type", namespace + "/Nonce");
        writer.writeCharacters(Base64.encode(entropy));
        writer.writeEndElement();

    }
    writer.writeEndElement();
    return secret;
}
 
Example 12
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 5 votes vote down vote up
protected void writeElementsForRSTPublicKey(W3CDOMStreamWriter writer,
        X509Certificate cert) throws Exception {
    writer.writeStartElement("wst", "UseKey", namespace);
    writer.writeStartElement("ds", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
    writer.writeNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");

    boolean useCert = useCertificateForConfirmationKeyInfo;
    String useCertStr = (String)getProperty(SecurityConstants.STS_TOKEN_USE_CERT_FOR_KEYINFO);
    if (useCertStr != null) {
        useCert = Boolean.parseBoolean(useCertStr);
    }
    if (useCert) {
        X509Data certElem = new X509Data(writer.getDocument());
        certElem.addCertificate(cert);
        writer.getCurrentNode().appendChild(certElem.getElement());
    } else {
        writer.writeStartElement("ds", "KeyValue", "http://www.w3.org/2000/09/xmldsig#");
        PublicKey key = cert.getPublicKey();
        String pubKeyAlgo = key.getAlgorithm();
        if ("DSA".equalsIgnoreCase(pubKeyAlgo)) {
            DSAKeyValue dsaKeyValue = new DSAKeyValue(writer.getDocument(), key);
            writer.getCurrentNode().appendChild(dsaKeyValue.getElement());
        } else if ("RSA".equalsIgnoreCase(pubKeyAlgo)) {
            RSAKeyValue rsaKeyValue = new RSAKeyValue(writer.getDocument(), key);
            writer.getCurrentNode().appendChild(rsaKeyValue.getElement());
        }
        writer.writeEndElement();
    }

    writer.writeEndElement();
    writer.writeEndElement();
}
 
Example 13
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Validate" invocation and return the response as a STSResponse Object
 */
protected STSResponse validate(SecurityToken tok, String tokentype) 
    throws Exception {
    createClient();
    
    if (tokentype == null) {
        tokentype = tokenType;
    }
    if (tokentype == null) {
        tokentype = namespace + "/RSTR/Status";
    }

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    Policy validatePolicy = new Policy();
    ExactlyOne one = new ExactlyOne();
    validatePolicy.addPolicyComponent(one);
    All all = new All();
    one.addPolicyComponent(all);
    all.addAssertion(getAddressingAssertion());

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    BindingOperationInfo boi = findOperation("/RST/Validate");
    if (boi == null) {
        boi = findOperation("/RST/Issue");
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, validatePolicy);
    }
    
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                   namespace + "/RST/Validate");

    
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", namespace);
    writer.writeCharacters(tokentype);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", namespace);

    Element el = tok.getToken();
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object o[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    
    return new STSResponse((DOMSource)o[0], null);
}
 
Example 14
Source File: AbstractSTSClient.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void addRequestType(String requestType, W3CDOMStreamWriter writer) throws XMLStreamException {
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + requestType);
    writer.writeEndElement();
}
 
Example 15
Source File: SimpleBatchSTSClient.java    From cxf with Apache License 2.0 4 votes vote down vote up
public List<SecurityToken> requestBatchSecurityTokens(
    List<BatchRequest> batchRequestList, String action, String requestType
) throws Exception {
    createClient();
    BindingOperationInfo boi = findOperation("/BatchIssue");

    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, action);

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityTokenCollection", namespace);
    writer.writeNamespace("wst", namespace);

    for (BatchRequest batchRequest : batchRequestList) {
        writer.writeStartElement("wst", "RequestSecurityToken", namespace);
        writer.writeNamespace("wst", namespace);

        addRequestType(requestType, writer);
        if (enableAppliesTo) {
            addAppliesTo(writer, batchRequest.getAppliesTo());
        }

        writeKeyType(writer, batchRequest.getKeyType());

        addLifetime(writer);

        addTokenType(writer, batchRequest.getTokenType());

        writer.writeEndElement();
    }
    writer.writeEndElement();

    Object[] obj = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));

    Element responseCollection = getDocumentElement((DOMSource)obj[0]);
    Node child = responseCollection.getFirstChild();
    List<SecurityToken> tokens = new ArrayList<>();
    while (child != null) {
        if (child instanceof Element
            && "RequestSecurityTokenResponse".equals(((Element)child).getLocalName())) {
            SecurityToken token =
                createSecurityToken((Element)child, null);
            tokens.add(token);
        }
        child = child.getNextSibling();
    }

    return tokens;
}
 
Example 16
Source File: STSRESTTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testValidateSAML2Token() throws Exception {
    WebClient client = webClient()
        .path("saml2.0")
        .accept(MediaType.APPLICATION_XML);

    // 1. Get a token via GET
    Document assertionDoc = client.get(Document.class);
    assertNotNull(assertionDoc);

    // 2. Now validate it in the STS using POST
    client = webClient()
        .query("action", "validate")
        .type(MediaType.APPLICATION_XML)
        .accept(MediaType.APPLICATION_XML);

    // Create RequestSecurityToken
    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", WST_NS_05_12);

    writer.writeStartElement("wst", "RequestType", WST_NS_05_12);
    writer.writeCharacters(WST_NS_05_12 + "/Validate");
    writer.writeEndElement();

    writer.writeStartElement("wst", "TokenType", WST_NS_05_12);
    String tokenType = WST_NS_05_12 + "/RSTR/Status";
    writer.writeCharacters(tokenType);
    writer.writeEndElement();

    writer.writeStartElement("wst", "ValidateTarget", WST_NS_05_12);
    StaxUtils.copy(assertionDoc.getDocumentElement(), writer);
    writer.writeEndElement();

    writer.writeEndElement();

    RequestSecurityTokenResponseType securityResponse = client.post(
        new DOMSource(writer.getDocument().getDocumentElement()),
        RequestSecurityTokenResponseType.class);

    assertTrue(getValidationStatus(securityResponse));
}
 
Example 17
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Renew" invocation and return the response as a STSResponse Object
 */
public STSResponse renew(SecurityToken tok) throws Exception {
    createClient();
    BindingOperationInfo boi = findOperation("/RST/Renew");

    client.getRequestContext().putAll(ctx);
    if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/SCT/Renew");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, namespace + "/RST/Renew");
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    if (context != null) {
        writer.writeAttribute(null, "Context", context);
    }
    
    String sptt = null;
    if (template != null && DOMUtils.getFirstElement(template) != null) {
        if (this.useSecondaryParameters()) {
            writer.writeStartElement("wst", "SecondaryParameters", namespace);
        }
        
        Element tl = DOMUtils.getFirstElement(template);
        while (tl != null) {
            StaxUtils.copy(tl, writer);
            if ("TokenType".equals(tl.getLocalName())) {
                sptt = DOMUtils.getContent(tl);
            }
            tl = DOMUtils.getNextElement(tl);
        }
        
        if (this.useSecondaryParameters()) {
            writer.writeEndElement();
        }
    }
    
    if (isSpnego) {
        tokenType = STSUtils.getTokenTypeSCT(namespace);
    }

    addRequestType("/Renew", writer);
    if (enableAppliesTo) {
        addAppliesTo(writer, tok.getIssuerAddress());
    }
    
    if (sptt == null) {
        addTokenType(writer);
    }
    if (isSecureConv || enableLifetime) {
        addLifetime(writer);
    }

    writer.writeStartElement("wst", "RenewTarget", namespace);
    client.getRequestContext().put(SecurityConstants.TOKEN, tok);
    StaxUtils.copy(tok.getToken(), writer);
    writer.writeEndElement();
    
    writer.writeEndElement();

    Object obj[] = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));

    return new STSResponse((DOMSource)obj[0], null);
}
 
Example 18
Source File: SecureConversationInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
void doIssue(
    Element requestEl,
    Exchange exchange,
    Element binaryExchange,
    W3CDOMStreamWriter writer,
    String prefix, 
    String namespace
) throws Exception {
    if (STSUtils.WST_NS_05_12.equals(namespace)) {
        writer.writeStartElement(prefix, "RequestSecurityTokenResponseCollection", namespace);
    }
    writer.writeStartElement(prefix, "RequestSecurityTokenResponse", namespace);
    
    byte clientEntropy[] = null;
    int keySize = 256;
    long ttl = 300000L;
    String tokenType = null;
    Element el = DOMUtils.getFirstElement(requestEl);
    while (el != null) {
        String localName = el.getLocalName();
        if (namespace.equals(el.getNamespaceURI())) {
            if ("Entropy".equals(localName)) {
                Element bs = DOMUtils.getFirstElement(el);
                if (bs != null) {
                    clientEntropy = Base64.decode(bs.getTextContent());
                }
            } else if ("KeySize".equals(localName)) {
                keySize = Integer.parseInt(el.getTextContent());
            } else if ("TokenType".equals(localName)) {
                tokenType = el.getTextContent();
            }
        }
        
        el = DOMUtils.getNextElement(el);
    }
    
    // Check received KeySize
    if (keySize < 128 || keySize > 512) {
        keySize = 256;
    }
    
    writer.writeStartElement(prefix, "RequestedSecurityToken", namespace);
    SecurityContextToken sct =
        new SecurityContextToken(NegotiationUtils.getWSCVersion(tokenType), writer.getDocument());
    
    Date created = new Date();
    Date expires = new Date();
    expires.setTime(created.getTime() + ttl);
    
    SecurityToken token = new SecurityToken(sct.getIdentifier(), created, expires);
    token.setToken(sct.getElement());
    token.setTokenType(sct.getTokenType());
    
    writer.getCurrentNode().appendChild(sct.getElement());
    writer.writeEndElement();        
    
    writer.writeStartElement(prefix, "RequestedAttachedReference", namespace);
    token.setAttachedReference(
        writeSecurityTokenReference(writer, "#" + sct.getID(), tokenType)
    );
    writer.writeEndElement();
    
    writer.writeStartElement(prefix, "RequestedUnattachedReference", namespace);
    token.setUnattachedReference(
        writeSecurityTokenReference(writer, sct.getIdentifier(), tokenType)
    );
    writer.writeEndElement();
    
    writeLifetime(writer, created, expires, prefix, namespace);

    byte[] secret = writeProofToken(prefix, namespace, writer, clientEntropy, keySize);
    
    token.setSecret(secret);
    ((TokenStore)exchange.get(Endpoint.class).getEndpointInfo()
            .getProperty(TokenStore.class.getName())).add(token);
    
    writer.writeEndElement();
    if (STSUtils.WST_NS_05_12.equals(namespace)) {
        writer.writeEndElement();
    }
}
 
Example 19
Source File: AbstractSTSClient.java    From steady with Apache License 2.0 4 votes vote down vote up
/**
 * Make an "Cancel" invocation and return the response as a STSResponse Object
 */
protected STSResponse cancel(SecurityToken token) throws Exception {
    createClient();

    if (addressingNamespace == null) {
        addressingNamespace = "http://www.w3.org/2005/08/addressing";
    }

    client.getRequestContext().clear();
    client.getRequestContext().putAll(ctx);
    client.getRequestContext().put(SecurityConstants.TOKEN, token);
    
    BindingOperationInfo boi = findOperation("/RST/Cancel");
    boolean attachTokenDirectly = true;
    if (boi == null) {
        attachTokenDirectly = false;
        boi = findOperation("/RST/Issue");
        
        Policy cancelPolicy = new Policy();
        ExactlyOne one = new ExactlyOne();
        cancelPolicy.addPolicyComponent(one);
        All all = new All();
        one.addPolicyComponent(all);
        all.addAssertion(getAddressingAssertion());
        
        PolicyBuilder pbuilder = bus.getExtension(PolicyBuilder.class);
        SymmetricBinding binding = new SymmetricBinding(pbuilder);
        all.addAssertion(binding);
        all.addAssertion(getAddressingAssertion());
        ProtectionToken ptoken = new ProtectionToken(pbuilder);
        binding.setProtectionToken(ptoken);
        binding.setIncludeTimestamp(true);
        binding.setEntireHeadersAndBodySignatures(true);
        binding.setTokenProtection(false);
        AlgorithmSuite suite = new AlgorithmSuite();
        binding.setAlgorithmSuite(suite);
        SecureConversationToken sct = new SecureConversationToken();
        sct.setOptional(true);
        ptoken.setToken(sct);
        
        SignedEncryptedParts parts = new SignedEncryptedParts(true);
        parts.setOptional(true);
        parts.setBody(true);
        parts.addHeader(new Header("To", addressingNamespace));
        parts.addHeader(new Header("From", addressingNamespace));
        parts.addHeader(new Header("FaultTo", addressingNamespace));
        parts.addHeader(new Header("ReplyTo", addressingNamespace));
        parts.addHeader(new Header("Action", addressingNamespace));
        parts.addHeader(new Header("MessageID", addressingNamespace));
        parts.addHeader(new Header("RelatesTo", addressingNamespace));
        all.addPolicyComponent(parts);
        
        client.getRequestContext().put(PolicyConstants.POLICY_OVERRIDE, cancelPolicy);
    }
    
    if (isSecureConv) {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION,
                                       namespace + "/RST/SCT/Cancel");
    } else {
        client.getRequestContext().put(SoapBindingConstants.SOAP_ACTION, 
                                       namespace + "/RST/Cancel");            
    }

    W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
    writer.writeStartElement("wst", "RequestSecurityToken", namespace);
    writer.writeNamespace("wst", namespace);
    writer.writeStartElement("wst", "RequestType", namespace);
    writer.writeCharacters(namespace + "/Cancel");
    writer.writeEndElement();

    writer.writeStartElement("wst", "CancelTarget", namespace);
    Element el = null;
    if (attachTokenDirectly) {
        el = token.getToken();
    } else {
        el = token.getUnattachedReference();
        if (el == null) {
            el = token.getAttachedReference();
        }
    }
    StaxUtils.copy(el, writer);

    writer.writeEndElement();
    writer.writeEndElement();

    Object[] obj = client.invoke(boi, new DOMSource(writer.getDocument().getDocumentElement()));
    return new STSResponse((DOMSource)obj[0], null);
}
 
Example 20
Source File: SecureConversationInInterceptor.java    From steady with Apache License 2.0 4 votes vote down vote up
void doIssue(
    Element requestEl,
    Exchange exchange,
    Element binaryExchange,
    W3CDOMStreamWriter writer,
    String prefix, 
    String namespace
) throws Exception {
    if (STSUtils.WST_NS_05_12.equals(namespace)) {
        writer.writeStartElement(prefix, "RequestSecurityTokenResponseCollection", namespace);
    }
    writer.writeStartElement(prefix, "RequestSecurityTokenResponse", namespace);
    
    byte clientEntropy[] = null;
    int keySize = 256;
    long ttl = 300000L;
    String tokenType = null;
    Element el = DOMUtils.getFirstElement(requestEl);
    while (el != null) {
        String localName = el.getLocalName();
        if (namespace.equals(el.getNamespaceURI())) {
            if ("Entropy".equals(localName)) {
                Element bs = DOMUtils.getFirstElement(el);
                if (bs != null) {
                    clientEntropy = Base64.decode(bs.getTextContent());
                }
            } else if ("KeySize".equals(localName)) {
                keySize = Integer.parseInt(el.getTextContent());
            } else if ("TokenType".equals(localName)) {
                tokenType = el.getTextContent();
            }
        }
        
        el = DOMUtils.getNextElement(el);
    }
    
    // Check received KeySize
    if (keySize < 128 || keySize > 512) {
        keySize = 256;
    }
    
    writer.writeStartElement(prefix, "RequestedSecurityToken", namespace);
    SecurityContextToken sct =
        new SecurityContextToken(NegotiationUtils.getWSCVersion(tokenType), writer.getDocument());
    
    Date created = new Date();
    Date expires = new Date();
    expires.setTime(created.getTime() + ttl);
    
    SecurityToken token = new SecurityToken(sct.getIdentifier(), created, expires);
    token.setToken(sct.getElement());
    token.setTokenType(sct.getTokenType());
    
    writer.getCurrentNode().appendChild(sct.getElement());
    writer.writeEndElement();        
    
    writer.writeStartElement(prefix, "RequestedAttachedReference", namespace);
    token.setAttachedReference(
        writeSecurityTokenReference(writer, "#" + sct.getID(), tokenType)
    );
    writer.writeEndElement();
    
    writer.writeStartElement(prefix, "RequestedUnattachedReference", namespace);
    token.setUnattachedReference(
        writeSecurityTokenReference(writer, sct.getIdentifier(), tokenType)
    );
    writer.writeEndElement();
    
    writeLifetime(writer, created, expires, prefix, namespace);

    byte[] secret = writeProofToken(prefix, namespace, writer, clientEntropy, keySize);
    
    token.setSecret(secret);
    ((TokenStore)exchange.get(Endpoint.class).getEndpointInfo()
            .getProperty(TokenStore.class.getName())).add(token);
    
    writer.writeEndElement();
    if (STSUtils.WST_NS_05_12.equals(namespace)) {
        writer.writeEndElement();
    }
}