Java Code Examples for org.apache.cxf.ws.security.tokenstore.SecurityToken#setToken()

The following examples show how to use org.apache.cxf.ws.security.tokenstore.SecurityToken#setToken() . 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: IssuedTokenInterceptorProvider.java    From steady with Apache License 2.0 6 votes vote down vote up
private SecurityToken createSecurityToken(
    AssertionWrapper assertionWrapper
) {
    SecurityToken token = new SecurityToken(assertionWrapper.getId());

    SAMLKeyInfo subjectKeyInfo = assertionWrapper.getSubjectKeyInfo();
    if (subjectKeyInfo != null) {
        token.setSecret(subjectKeyInfo.getSecret());
        X509Certificate[] certs = subjectKeyInfo.getCerts();
        if (certs != null && certs.length > 0) {
            token.setX509Certificate(certs[0], null);
        }
    }
    if (assertionWrapper.getSaml1() != null) {
        token.setTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
    } else if (assertionWrapper.getSaml2() != null) {
        token.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
    }
    token.setToken(assertionWrapper.getElement());

    return token;
}
 
Example 2
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Store a SAML Assertion as a SecurityToken
 */
protected void storeAssertionAsSecurityToken(AssertionWrapper assertion) {
    String id = findIDFromSamlToken(assertion.getElement());
    if (id == null) {
        return;
    }
    SecurityToken secToken = new SecurityToken(id);
    if (assertion.getSaml2() != null) {
        secToken.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
    } else {
        secToken.setTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
    }
    secToken.setToken(assertion.getElement());
    getTokenStore().add(secToken);
    message.setContextualProperty(SecurityConstants.TOKEN_ID, secToken.getId());
}
 
Example 3
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Store a SAML Assertion as a SecurityToken
 */
protected void storeAssertionAsSecurityToken(AssertionWrapper assertion) {
    String id = findIDFromSamlToken(assertion.getElement());
    if (id == null) {
        return;
    }
    SecurityToken secToken = new SecurityToken(id);
    if (assertion.getSaml2() != null) {
        secToken.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
    } else {
        secToken.setTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
    }
    secToken.setToken(assertion.getElement());
    getTokenStore().add(secToken);
    message.setContextualProperty(SecurityConstants.TOKEN_ID, secToken.getId());
}
 
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: 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 6
Source File: AbstractBindingBuilder.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Store a SAML Assertion as a SecurityToken
 */
protected void storeAssertionAsSecurityToken(AssertionWrapper assertion) {
    String id = findIDFromSamlToken(assertion.getElement());
    if (id == null) {
        return;
    }
    SecurityToken secToken = new SecurityToken(id);
    if (assertion.getSaml2() != null) {
        secToken.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
    } else {
        secToken.setTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
    }
    secToken.setToken(assertion.getElement());
    getTokenStore().add(secToken);
    message.setContextualProperty(SecurityConstants.TOKEN_ID, secToken.getId());
}
 
Example 7
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 8
Source File: CustomUsernameTokenProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
    try {
        Document doc = DOMUtils.getEmptyDocument();

        // Mock up a UsernameToken
        UsernameToken usernameToken = new UsernameToken(true, doc, WSS4JConstants.PASSWORD_TEXT);
        usernameToken.setName("alice");
        usernameToken.setPassword("password");
        String id = "UT-1234";
        usernameToken.addWSSENamespace();
        usernameToken.addWSUNamespace();
        usernameToken.setID(id);

        TokenProviderResponse response = new TokenProviderResponse();
        response.setToken(usernameToken.getElement());
        response.setTokenId(id);

        // Store the token in the cache
        if (tokenParameters.getTokenStore() != null) {
            SecurityToken securityToken = new SecurityToken(usernameToken.getID());
            securityToken.setToken(usernameToken.getElement());
            int hashCode = usernameToken.hashCode();
            String identifier = Integer.toString(hashCode);
            securityToken.setTokenHash(hashCode);
            tokenParameters.getTokenStore().add(identifier, securityToken);
        }

        return response;
    } catch (Exception e) {
        e.printStackTrace();
        throw new STSException("Can't serialize SAML assertion", e, STSException.REQUEST_FAILED);
    }
}
 
Example 9
Source File: BinarySecurityTokenTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBinarySecurityToken() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = BinarySecurityTokenTest.class.getResource("client.xml");

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

    URL wsdl = BinarySecurityTokenTest.class.getResource("DoubleItTokens.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);

    // Successful invocation
    QName portQName = new QName(NAMESPACE, "DoubleItBinarySecurityTokenPort");
    DoubleItPortType port = service.getPort(portQName, DoubleItPortType.class);
    updateAddressPort(port, PORT);

    // Mock up a BinarySecurityToken to add
    SecurityToken securityToken = new SecurityToken();
    securityToken.setId("_" + UUID.randomUUID().toString());

    Document doc = DOMUtils.newDocument();
    BinarySecurity binarySecurity = new BinarySecurity(doc);
    binarySecurity.setValueType("http://custom-value-type");
    binarySecurity.setToken("This is a token".getBytes());

    securityToken.setToken(binarySecurity.getElement());

    ((BindingProvider)port).getRequestContext().put(SecurityConstants.TOKEN, securityToken);

    assertEquals(50, port.doubleIt(25));

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 10
Source File: NegotiationUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Return true on successfully parsing a SecurityContextToken result
 */
static boolean parseSCTResult(SoapMessage message) {
    List<WSHandlerResult> results = 
        CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
    if (results == null) {
        return false;
    }
    
    for (WSHandlerResult rResult : results) {
        List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults();

        for (WSSecurityEngineResult wser : wsSecEngineResults) {
            Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
            if (actInt.intValue() == WSConstants.SCT) {
                SecurityContextToken tok = 
                    (SecurityContextToken)wser.get(WSSecurityEngineResult.TAG_SECURITY_CONTEXT_TOKEN);
                message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getIdentifier());
                
                byte[] secret = (byte[])wser.get(WSSecurityEngineResult.TAG_SECRET);
                if (secret != null) {
                    SecurityToken token = new SecurityToken(tok.getIdentifier());
                    token.setToken(tok.getElement());
                    token.setSecret(secret);
                    token.setTokenType(tok.getTokenType());
                    getTokenStore(message).add(token);
                }
                return true;
            }
        }
    }
    return false;
}
 
Example 11
Source File: IssuedTokenInterceptorProvider.java    From steady with Apache License 2.0 5 votes vote down vote up
private SecurityToken createSecurityToken(BinarySecurity binarySecurityToken) {
    SecurityToken token = new SecurityToken(binarySecurityToken.getID());
    token.setToken(binarySecurityToken.getElement());
    token.setSecret(binarySecurityToken.getToken());
    token.setTokenType(binarySecurityToken.getValueType());
    
    return token;
}
 
Example 12
Source File: STSStaxTokenValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static void validateTokenToSTS(Element tokenElement, SoapMessage message)
    throws WSSecurityException {
    SecurityToken token = new SecurityToken();
    token.setToken(tokenElement);

    STSClient c = STSUtils.getClient(message, "sts");
    synchronized (c) {
        System.setProperty("noprint", "true");
        try {
            c.validateSecurityToken(token);
        } catch (Exception e) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION, e);
        }
    }
}
 
Example 13
Source File: NegotiationUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Return true on successfully parsing a SecurityContextToken result
 */
static boolean parseSCTResult(SoapMessage message) {
    List<WSHandlerResult> results = 
        CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
    if (results == null) {
        return false;
    }
    
    for (WSHandlerResult rResult : results) {
        List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults();

        for (WSSecurityEngineResult wser : wsSecEngineResults) {
            Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
            if (actInt.intValue() == WSConstants.SCT) {
                SecurityContextToken tok = 
                    (SecurityContextToken)wser.get(WSSecurityEngineResult.TAG_SECURITY_CONTEXT_TOKEN);
                message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getIdentifier());
                
                byte[] secret = (byte[])wser.get(WSSecurityEngineResult.TAG_SECRET);
                if (secret != null) {
                    SecurityToken token = new SecurityToken(tok.getIdentifier());
                    token.setToken(tok.getElement());
                    token.setSecret(secret);
                    token.setTokenType(tok.getTokenType());
                    getTokenStore(message).add(token);
                }
                return true;
            }
        }
    }
    return false;
}
 
Example 14
Source File: NegotiationUtils.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Return true on successfully parsing a SecurityContextToken result
 */
static boolean parseSCTResult(SoapMessage message) {
    List<WSHandlerResult> results = 
        CastUtils.cast((List<?>)message.get(WSHandlerConstants.RECV_RESULTS));
    if (results == null) {
        return false;
    }
    
    for (WSHandlerResult rResult : results) {
        List<WSSecurityEngineResult> wsSecEngineResults = rResult.getResults();

        for (WSSecurityEngineResult wser : wsSecEngineResults) {
            Integer actInt = (Integer)wser.get(WSSecurityEngineResult.TAG_ACTION);
            if (actInt.intValue() == WSConstants.SCT) {
                SecurityContextToken tok = 
                    (SecurityContextToken)wser.get(WSSecurityEngineResult.TAG_SECURITY_CONTEXT_TOKEN);
                message.getExchange().put(SecurityConstants.TOKEN_ID, tok.getIdentifier());
                
                byte[] secret = (byte[])wser.get(WSSecurityEngineResult.TAG_SECRET);
                if (secret != null) {
                    SecurityToken token = new SecurityToken(tok.getIdentifier());
                    token.setToken(tok.getElement());
                    token.setSecret(secret);
                    token.setTokenType(tok.getTokenType());
                    getTokenStore(message).add(token);
                }
                return true;
            }
        }
    }
    return false;
}
 
Example 15
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 16
Source File: KerberosTokenInterceptorProvider.java    From steady with Apache License 2.0 4 votes vote down vote up
private static SecurityToken createSecurityToken(KerberosSecurity binarySecurityToken) {
    SecurityToken token = new SecurityToken(binarySecurityToken.getID());
    token.setToken(binarySecurityToken.getElement());
    token.setTokenType(binarySecurityToken.getValueType());
    return token;
}
 
Example 17
Source File: ServerCachingTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testServerSideSAMLTokenCaching() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = ServerCachingTest.class.getResource("cxf-client.xml");

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

    URL wsdl = ServerCachingTest.class.getResource("DoubleIt.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItTransportSAML1AlternativePort");
    DoubleItPortType port =
        service.getPort(portQName, DoubleItPortType.class);
    ((BindingProvider)port).getRequestContext().put("thread.local.request.context", "true");
    updateAddressPort(port, PORT);

    // Make an initial successful invocation
    doubleIt(port, 25);

    // Store the SAML Assertion that was obtained from the STS
    Client client = ClientProxy.getClient(port);
    Endpoint ep = client.getEndpoint();
    String id = (String)ep.get(SecurityConstants.TOKEN_ID);
    TokenStore store = (TokenStore)ep.getEndpointInfo().getProperty(TokenStore.class.getName());
    SecurityToken tok = store.getToken(id);
    assertNotNull(tok);
    Element storedToken = tok.getToken();

    // Get another security token by invoking on the STS directly and save it on the client port
    SecurityToken token =
        requestSecurityToken(SAML1_TOKEN_TYPE, PUBLIC_KEY_KEYTYPE, bus, DEFAULT_ADDRESS);
    assertNotNull(token);
    tok.setToken(token.getToken());

    // Try another invocation - this will fail as the STSClient on the server side is disabled
    // after the first invocation
    try {
        doubleIt(port, 30);
        fail("Failure expected as the STSClient on the server side is null");
    } catch (Exception ex) {
        // expected
    }
    // Try again using the original SAML token - this should work as it should be cached by the service
    tok.setToken(storedToken);
    doubleIt(port, 35);

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
Example 18
Source File: SimpleBatchSTSClient.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected List<SecurityToken> validateBatchSecurityTokens(
    List<BatchRequest> batchRequestList, String action, String requestType
) throws Exception {
    createClient();
    BindingOperationInfo boi = findOperation("/BatchValidate");

    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);

        addTokenType(writer, batchRequest.getTokenType());

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

        Element el = batchRequest.getValidateTarget();
        StaxUtils.copy(el, writer);

        writer.writeEndElement();

        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())) {
            Element rstrChild = DOMUtils.getFirstElement(child);
            while (rstrChild != null) {
                if ("Status".equals(rstrChild.getLocalName())) {
                    Element e2 =
                        DOMUtils.getFirstChildWithName(rstrChild, rstrChild.getNamespaceURI(), "Code");
                    String s = DOMUtils.getContent(e2);
                    if (!s.endsWith("/status/valid")) {
                        throw new TrustException(LOG, "VALIDATION_FAILED");
                    }

                } else if ("RequestedSecurityToken".equals(rstrChild.getLocalName())) {
                    Element requestedSecurityTokenElement = DOMUtils.getFirstElement(rstrChild);
                    String id = findID(null, null, requestedSecurityTokenElement);
                    if (StringUtils.isEmpty(id)) {
                        throw new TrustException("NO_ID", LOG);
                    }
                    SecurityToken requestedSecurityToken = new SecurityToken(id);
                    requestedSecurityToken.setToken(requestedSecurityTokenElement);
                    tokens.add(requestedSecurityToken);
                }
                rstrChild = DOMUtils.getNextElement(rstrChild);
            }
        }
        child = child.getNextSibling();
    }

    return tokens;
}
 
Example 19
Source File: KerberosTokenInterceptorProvider.java    From steady with Apache License 2.0 4 votes vote down vote up
private static SecurityToken createSecurityToken(KerberosSecurity binarySecurityToken) {
    SecurityToken token = new SecurityToken(binarySecurityToken.getID());
    token.setToken(binarySecurityToken.getElement());
    token.setTokenType(binarySecurityToken.getValueType());
    return token;
}
 
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();
    }
}