Showing posts with label ESB. Show all posts
Showing posts with label ESB. Show all posts

WSO2 ESB Property Mediator - Different Scopes

Properties are name value pairs. Properties are a way to convey information across different processing units. For example user may need to set a transport property from the message mediation. Or user may need to remove a property which is set by the transport. This mediator sets or removes properties for a particular message.

Property mediator has no direct impact on the message but rather on the message context flowing through Synapse. The properties set on a message can be later retrieved through the synapse:get-property(prop-name) XPath extension function. If a scope is specified for a property, the property could be set as a transport header property or an (underlying) Axis2 message context property, or as a Axis2 client option. If a scope is not specified, it will default to the Synapse message context scope. Using the property element with action specified as "remove" you can remove any existing message context properties.

The above extracted from the WSO2 ESB documentation...

This blog post focuses on different types of scopes available while setting properties.

1. Default - or the Synapse
Once you set a property under this scope - the value of it will be available through out both the in/out sequences.

To access this property inside the mediate() method of a mediator...
public boolean mediate(org.apache.synapse.MessageContext mc) {
// Available in both in-sequence and out-sequenc
String propValue = (String) mc.getProperty("PropName");
System.out.println("SCOPE_SYNAPSE : " + propValue);
return true;
}
2. Axis2
Once you set a property under this scope - the value of it will be available only through out the the sequence it's been set. If you set the Property mediator to the in-sequence, you cannot access it in the out-sequence.To access this property inside the mediate() method of a mediator...
public boolean mediate(org.apache.synapse.MessageContext mc) {
org.apache.axis2.context.MessageContext axis2MsgContext;
axis2MsgContext = ((Axis2MessageContext) mc).getAxis2MessageContext();

// Available only in the sequence the property is defined.
String propValue = (String) axis2MsgContext.getProperty("PropName");
System.out.println("SCOPE_AXIS2 : " + propValue);
return true;
}
3. Axis2-Client
This is similar to Synapse scope. The difference is - you can access it in following two ways..
public boolean mediate(org.apache.synapse.MessageContext mc) {
org.apache.axis2.context.MessageContext axis2MsgContext;
axis2MsgContext = ((Axis2MessageContext) mc).getAxis2MessageContext();
String propValue = (String) axis2MsgContext.getProperty("PropName");
System.out.println("SCOPE_AXIS2_CLIENT - 1 : " + propValue);

propValue = (String) axis2MsgContext.getOptions().getProperty("PropName");
System.out.println("SCOPE_AXIS2_CLIENT - 2: " + propValue);
return true;
}
4. Transport
Once you set a property under this scope - it will be added to the transport header of the out going message from the ESB.

Accessing the HTTP method within a WSO2 ESB Mediator

I couldn't find this in the ESB property documentation - so thought of keeping a note here.

Also - there is a chance that you can confuse the constant "HTTP_METHOD" with org.apache.axis2.transport.http.HTTPConstants.HTTP_METHOD - which internally refers to ""HTTP_METHOD_OBJECT""
public boolean mediate(org.apache.synapse.MessageContext synCtx) {
org.apache.synapse.core.axis2.Axis2MessageContext.Axis2MessageContext axis2Msgcontext = null;
org.apache.axis2.context.MessageContext msgContext  = null;
axis2Msgcontext = (Axis2MessageContext) synCtx;
msgContext = axis2Msgcontext.getAxis2MessageContext();
String httpMethod = (String) msgContext.getProperty("HTTP_METHOD");
}

[WSO2 ESB] Invoking a Web Service via HTTPS from a Proxy Service

1. Get the public certificate of the Web Service deployed over HTTPS

2. Import the certificate from [1] to [ESB_HOM]/resources/security/client_truststore.jks

:\>keytool import public_cert.crt -alias myservice -keystore client_truststore.jks

The default password is wso2carbon. You can put any name to alias [e.g. myservice] and need to replace public_cert.crt with name of the certificate you have from [1].

3.You may be using an IP address as the web service end point or the CN of the certificate issued for the end point may not match its server url. This could cause a host name verification error.

To overcome that, find the following in [ESB_HOME]/repository/conf/axis2.xml ..

<parameter name="HostnameVerifier">DefaultAndLocalhost</parameter>

uncomment it and change it to the following...

<parameter name="HostnameVerifier">AllowAll</parameter>

4. If the Web Service or it's WSLD - or the both enabled for mutual authentication - you need export the public certificate of WSO2 ESB out and import it to the trust store of the Web Service.

To export out the ESB public certificate you can use the following.

:\>keytool export -file esb_public_cert.crt -alias wso2carbon -keystore wso2carbon.jks

You can find wso2carbon.jks at [ESB_HOM]/resources/security/wso2carbon.jks and it default password is wso2carbon.

That's it..

ERROR - ProxyService Error reading from wsdl URI

$subject could be a common error for many new ESB users - so, thought of keeping a note here.

This could easily happen if you create a proxy service against the sample echo service which ships with WSO2 ESB - and WSDL was pointed with an URI - and the corresponding WSDL is unavailable at the time proxy service been deployed [i.e. When the ESB is restarted]

<publishWSDL uri="http://localhost:8280/services/echo?wsdl"/>

To recover from this error - you need to edit the file [ESB_HOME]/repository/conf/synapse-config/proxy-services/your_service_name.xml and add the following parameter..
<proxy name="test" transports="https http" startOnLoad="true" trace="disable">
         ..............
         ..................
        <parameter name="enablePublishWSDLSafeMode">true</parameter>
    </proxy>

Now restart the ESB and you will notice that this particular proxy service is not loaded - but the ESB starts fine.

To handle this issue in a more generic way - a fail-safe mode to be introduced in to the upcoming release of WSO2 ESB - further details here...

Invoking a WCF service secured with Kerberos via WSO2 ESB

1. Set up WCF service secured with Kerberos - explained in this blog post.

2. Set up the WSO2 ESB to work with Kerberos - explained in this blog post - follow the steps 0,1,2,3 and 4.

3. Create a resource in the WSO2 ESB - embedded registry with the following content - this is the security policy we will be applying to the out going messages from the ESB to the WCF service.

In this example, I created a Resource Collection called 'policies' under /_system/governance and created a Resource called krbpolicy with the following content under /_system/governance/policies.

So, my security policy from the registry is /_system/governance/policies/krbpolicy
<?xml version="1.0" encoding="UTF-8"?>
<wsp:Policy wsu:Id="kerberossignandencrypt"
 xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
 xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
 <wsp:ExactlyOne>
  <wsp:All>
   <sp:SymmetricBinding
    xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
    <wsp:Policy>
     <sp:ProtectionToken>
      <wsp:Policy>
       <sp:KerberosToken
        sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
        <wsp:Policy>
         <sp:WssKerberosV5ApReqToken11 />
        </wsp:Policy>
       </sp:KerberosToken>
      </wsp:Policy>
     </sp:ProtectionToken>
     <sp:AlgorithmSuite>
      <wsp:Policy>
       <sp:Basic256 />
      </wsp:Policy>
     </sp:AlgorithmSuite>
     <sp:Layout>
      <wsp:Policy>
       <sp:Lax />
      </wsp:Policy>
     </sp:Layout>
     <sp:IncludeTimestamp />
     <sp:OnlySignEntireHeadersAndBody />
    </wsp:Policy>
   </sp:SymmetricBinding>
   <sp:SignedParts
    xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
    <sp:Body />
   </sp:SignedParts>
   <sp:Wss11 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
    <sp:Policy>
     <sp:MustSupportRefKeyIdentifier />
     <sp:MustSupportRefIssuerSerial />
     <sp:MustSupportRefThumbprint />
     <sp:RequireSignatureConfirmation />
    </sp:Policy>
   </sp:Wss11>
   <sp:Trust10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
    <wsp:Policy>
     <sp:RequireClientEntropy />
     <sp:RequireServerEntropy />
     <sp:MustSupportIssuedTokens />
    </wsp:Policy>
   </sp:Trust10>
   <rampart:RampartConfig xmlns:rampart="http://ws.apache.org/rampart/policy">
    <rampart:timestampPrecisionInMilliseconds>true
    </rampart:timestampPrecisionInMilliseconds>
    <rampart:timestampTTL>300</rampart:timestampTTL>
    <rampart:timestampMaxSkew>300</rampart:timestampMaxSkew>
    <rampart:kerberosConfig>
     <rampart:property name="client.principal.name">client</rampart:property>
     <rampart:property name="client.principal.password">1qaz2wsx$
     </rampart:property>
     <rampart:property name="service.principal.name">service/myserver@WSO2.COM
     </rampart:property>
     <rampart:property name="java.security.auth.login.config">jaas.conf
     </rampart:property>
     <rampart:property name="javax.security.auth.useSubjectCredsOnly">true</rampart:property>
     <rampart:property name="kdc.des.aes.factor">4</rampart:property>
     <rampart:property name="java.security.krb5.conf">/Users/prabath/clients/wso2esb-3.0.1/repository/conf/krb.conf
     </rampart:property>
    </rampart:kerberosConfig>
   </rampart:RampartConfig>
  </wsp:All>
 </wsp:ExactlyOne>
</wsp:Policy>
In the policy we have to set the absolute path to the krb.conf - at the same time we need to set the username and password of the client who invokes the WCF service appropriately - and this account should be in the Active Directory.

4. Now create a proxy service - and in the InSequence - in the Endpoint pointing to the WCF service, enable security and pick the security policy we set before, from the registry.

The endpoint configuration in the synapse config will look like,
<endpoint name="endpoint_urn_uuid_81768417D4430798591291451112900558002-585115135">
                <address uri="http://192.168.2.13/EchoServices/EchoService.svc">
                    <enableSec policy="gov:/policies/krbpolicy"/>
                </address>
</endpoint>
5. Also in the InSequence we need to add a Property mediator and set the following.
<property name="PRESERVE_WS_ADDRESSING" value="true"/>
6. Now in the OutSequence - we need to remove the Security Header coming from the WCF service before the Send mediator in the OutSequence - you can do it with a Header mediator.
<header xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" name="wsse:Security" action="remove"/>
7. Also in the OutSequence we need to add a Property mediator and set the following.
<property name="disableAddressingForOutMessages" value="true" scope="axis2"/>
These two properties [5 & 7] are needed if the back end service is WCF and it is secured using WS-Security and ESB is acting as a passthrough. When communicating with WCF, wsa:to should point to WCF service endpoint (In axis2, it can can point to some other place, still axis2 will dispatch correctly using URL). For the pass through with security case, client should sign wsa:headers (WS-Security requirement) and hence wsa:to cannot be changed by ESB (violation of signature); Hence, the requirement for "preserve addressing". When the response comes from WCF->ESB, ESB adds addressing header regardless of whether the original message (from WCF) has addressing or not. In above case, since wsa:headers of request is signed by client, response from WCF will contain a signed wsa headers. If ESB adds one more set of addressing headers, then it will be violating protocol. Hence the requirement for "disable addressing for out messages"

8. Now your InSquence will like,
<inSequence>
                <property name="PRESERVE_WS_ADDRESSING" value="true" scope="default" type="STRING"/>
            </inSequence>
9. OutSequence will look like,
<outSequence>
                <property name="disableAddressingForOutMessages" value="true" scope="axis2"/>
                <header xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" name="wsse:Security" action="remove"/>
                <send/>
            </outSequence>
10. That's it :)

Kerberos authentication with WSO2 ESB

0. Set up the Active Directory as the KDC as in my previous blog post.

1. Download WSO2 ESB 3.0.1 from here unzip and apply the patches patch0003 and patch0023.These patches are not publicly available - but will be added in to the future releases. If you interested, please contact us on bizdev@wso2.com.

2. Create a file called krb.conf inside [ESB_HOME]\repository\conf and copy the following content to it.
[libdefaults] 
        default_realm = WSO2.COM 
        default_tkt_enctypes = rc4-hmac 
        default_tgs_enctypes = rc4-hmac 
        dns_lookup_kdc = true 
        dns_lookup_realm = false 

[realms] 
        WSO2.COM = { 
            kdc = 192.168.2.10
   } 
Here, WSO2.COM is my root domain name of my Active Directory, which is acting as the KDC and 192.168.2.1 is it's IP address - so you need to change them as per your setup. Make sure that you have default_realm all caps.

3. Create a file called jaas.conf inside [ESB_HOME]\repository\conf and copy the following content to it.
Server {
com.sun.security.auth.module.Krb5LoginModule required
useKeyTab=tfalse
storeKey=true
useTicketCache=false
isInitiator=false;
};
Client {
com.sun.security.auth.module.Krb5LoginModule required
useTicketCache=false;
};
4. Start the WSO2 ESB

5. Apply security to the given proxy service [during this sample we select echo sample service which is already there by default]

6. Select 'Sign & Encrypt with Anonymous' from the Security Policy wizard.

7. After applying, edit the policy and replace both bindings with the content below.
<?xml version="1.0" encoding="UTF-8"?>
<wsp:Policy wsu:Id="kerberossignandencrypt"
  xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <wsp:ExactlyOne>
    <wsp:All>
      <sp:SymmetricBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:ProtectionToken>
            <wsp:Policy>
              <sp:KerberosToken sp:IncludeToken="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy/IncludeToken/AlwaysToRecipient">
                <wsp:Policy>
                  <sp:WssKerberosV5ApReqToken11/>
                </wsp:Policy>
              </sp:KerberosToken>
            </wsp:Policy>
          </sp:ProtectionToken>
          <sp:AlgorithmSuite>
            <wsp:Policy>
              <sp:Basic256/>
            </wsp:Policy>
          </sp:AlgorithmSuite>
          <sp:Layout>
            <wsp:Policy>
              <sp:Lax/>
            </wsp:Policy>
          </sp:Layout>
          <sp:IncludeTimestamp/>
          <sp:OnlySignEntireHeadersAndBody/>
        </wsp:Policy>
      </sp:SymmetricBinding>
      <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <sp:Body/>
      </sp:SignedParts>
      <sp:Wss11 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <sp:Policy>
          <sp:MustSupportRefKeyIdentifier/>
          <sp:MustSupportRefIssuerSerial/>
          <sp:MustSupportRefThumbprint/>
          <sp:RequireSignatureConfirmation/>
        </sp:Policy>
      </sp:Wss11>
      <sp:Trust10 xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
        <wsp:Policy>
          <sp:RequireClientEntropy/>
          <sp:RequireServerEntropy/>
          <sp:MustSupportIssuedTokens/>
        </wsp:Policy>
      </sp:Trust10>
      <rampart:RampartConfig xmlns:rampart="http://ws.apache.org/rampart/policy">
        <rampart:timestampPrecisionInMilliseconds>true</rampart:timestampPrecisionInMilliseconds>
        <rampart:timestampTTL>300</rampart:timestampTTL>
        <rampart:timestampMaxSkew>300</rampart:timestampMaxSkew>
        <rampart:kerberosConfig>
          <rampart:property name="service.principal.password">1qaz2wsx$</rampart:property>
          <rampart:property name="javax.security.auth.useSubjectCredsOnly">true</rampart:property>
          <rampart:property name="java.security.krb5.conf">/Users/prabath/clients/wso2esb-3.0.1/repository/conf/krb.conf</rampart:property> 
       </rampart:kerberosConfig>
      </rampart:RampartConfig>
    </wsp:All>
  </wsp:ExactlyOne>
</wsp:Policy>
You need to set your SPN password under service.principal.password and also the absolute path to krb.conf under java.security.krb5.conf.

8. You can write the Java client to this service as explained in my previous blog post.

Extracting SAML assertions from a proxy service and adding them back to the service behind

This blog post explains how to do the intial setup with WSO2 ESB and the Identity Server to develop claim aware web services - please go through it first.

There - we get the SAML Assertion to the proxy service.

Here what we are going to do is - to extract SAML Assertions from the Security header of the incoming message and add those as a custom header to the message going to the actual service.

First, please download the org.wso2.carbon.identity.samples.saml.mediator-2.0.0.SNAPSHOT.jar from here.

Stop - the ESB if it's running already.

Copy the above jar to [ESB_HOME]\webapps\ROOT\WEB-INF\plugins\console.

Open [ESB_HOME]\webapps\ROOT\WEB-INF\eclipse\configuration\org.eclipse.equinox.simpleconfigurator\bundles.info and add the following entry to the end [one line].

org.wso2.carbon.identity.samples.saml.mediator,2.0.0.SNAPSHOT,file:plugins/org.wso2.carbon.identity.samples.saml.mediator-2.0.0.SNAPSHOT.jar,10,true

Start the ESB with following.

\> wso2server.bat -cleanCache

Now, you need to add the above mediator to the in sequence of your proxy service as a Class mediator.

Following is the synapase configuration for the in/out sequences of the proxy service.

<syn:proxy name="test" transports="https http" startOnLoad="true" trace="disable">
  <syn:target>
    <syn:inSequence>
      <syn:class name="org.wso2.carbon.identity.samples.saml.mediator.SAMLAttrMediator"/>
      <syn:header xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" name="wsse:Security" action="remove"/>
      <syn:log level="full"/>
      <syn:send/>
    </syn:inSequence>
    <syn:outSequence>
      <syn:send/>
    </syn:outSequence>
  </syn:target>
</syn:proxy>
You can clearly see Class/Header/Log & Send mediators are in the in-sequence and Send mediator in the out-sequence.

Now - the question is how do we capture the SAML attributes from the actual service.

You can call the following method from any service method to get the attributes in a HashMap.

getAttributes(MessageContext.getCurrentMessageContext());

Following is the code for getAttributes() method.

private static final String USER_ATTRIBUTES_ELEMENT = "UserAttributes";
private static final String USER_ATTRIBUTES_NS = "http://attributes.saml.axis2.org";
private static final String ATTRIBUTE = "Attribute";
private static final String ATTRIBUTE_NS = "AttributeNamespace";
private static final String ATTRIBUTE_VALUE = "AttributeValue";
public final static String SAML10_NS = "urn:oasis:names:tc:SAML:1.0:assertion";
public final static String SAML11_NS = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1";
public final static String SAML20_NS = "urn:oasis:names:tc:SAML:2.0:assertion";

public Map getAttributes(MessageContext messageContext) {
OMElement header = null;
OMElement userAttr = null;
Iterator iterator = null;
String samlNameSpace = null;

header = messageContext.getEnvelope().getHeader();
userAttr = header.getFirstChildWithName(new QName(USER_ATTRIBUTES_NS,
USER_ATTRIBUTES_ELEMENT));
iterator = userAttr.getChildrenWithName(new QName(SAML10_NS, ATTRIBUTE));

if (iterator.hasNext()) {
samlNameSpace = SAML10_NS;
} else {
iterator = userAttr.getChildrenWithName(new QName(SAML11_NS, ATTRIBUTE));
if (iterator.hasNext()) {
samlNameSpace = SAML11_NS;
} else {
iterator = userAttr.getChildrenWithName(new QName(SAML20_NS, ATTRIBUTE));
if (iterator.hasNext()) {
samlNameSpace = SAML20_NS;
}
}
}

if (samlNameSpace == null) {
// Unsupported SAML token type;
return null;
}

Map attributes;
attributes = new HashMap();

while (iterator.hasNext()) {
OMElement attr = iterator.next();
OMElement attrValElement = null;
String attributeName = null;
String attributeValue = null;
attributeName = attr.getAttributeValue(new QName(ATTRIBUTE_NS));
attrValElement = attr.getFirstChildWithName(new QName(samlNameSpace, ATTRIBUTE_VALUE));
attributeValue = attrValElement.getText();
attributes.put(attributeName, attributeValue);
}

return attributes;
}
Also make sure you import following packages as well.

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.context.MessageContext;

WSO2 Identity Server + Claim aware proxy services with ESB

WSO2 Identity Server 2.0 is a free and open source identity and entitlement management server, available to download from here...

Let me first briefly explain the the use case.

1. A proxy service created in WSO2 ESB requires a security token issued by the WSO2 Identity Server for authentication.

2.At the same time, the security policy in the proxy service, specifies - it requires a given set of claim values with the security token.

<sp:RequestSecurityTokenTemplate xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
<t:KeyType>http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey</t:KeyType>
<t:KeySize>256</t:KeySize>
<t:Claims Dialect="http://wso2.org/claims" xmlns:ic="http://schemas.xmlsoap.org/ws/2005/05/identity">
<ic:ClaimType Uri="http://wso2.org/claims/givenname" />
</t:Claims>
</sp:RequestSecurityTokenTemplate>
3. Identity Server is connected to an LDAP user store and all user attributes reside there.

4. User needs to authenticate to Identity Server, first and obtain the Security Token with claims.

5. Then user sends it to the ESB proxy service.

Let's see how we can achieve this in a step by step manner.

Step -1

Set up LDAP server. All the detail required explained here.

Step -2
Configure WSO2 Identity Server to talk to the LDAP Server and do the claim mapping. All the detail required explained here.

Step -3
Configure WSO2 Identity Server STS. The first part of this explains all the steps you need.

Before that you need to get the public certificate [wso2carbon.cert.cer] of the ESB from here.

Login to IS as an admin, and import the above certificate to wso2carbon.jks from Configure/Key Stores. [Yes - WSO2 ESB and IS use two different key stores - that's why we need to perform this step here]

Make sure, in the first step - while adding the trusted 'Endpoint Address' - select 'wso2carbon.cert' as the 'Certificate Alias'.

Also - while applying the security policy to the STS - make sure you select the group where ldap users[ldapuserole] belong to.

Step -4

Create and apply security for the proxy service. You need to follow exact steps defined here [first part] - but need to get the service security policy[service.policy.xml] from here, when you are overriding.

That's it - now let's write the client code.

You may also need to download Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 5.0 from here and copy the two jar files from the extracted jce directory (local_policy.jar and US_export_policy.jar) to $JAVA_HOME/jre/lib/security. For JDK 6 it's here.

You need to do above, both at the client side as well as the server side - if you are running on two machines.

Also while running the client code, make sure bouncycastle jar is in the classpath.

You can download both sts.policy.xml and service.policy.xml files from here.

package org.apache.ws.axis2;

import java.util.Properties;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.rahas.RahasConstants;
import org.apache.rahas.Token;
import org.apache.rahas.TokenStorage;
import org.apache.rahas.TrustUtil;
import org.apache.rahas.client.STSClient;
import org.apache.rampart.RampartMessageData;
import org.apache.rampart.policy.model.RampartConfig;
import org.apache.rampart.policy.model.CryptoConfig;
import org.apache.ws.secpolicy.Constants;
import org.opensaml.XML;

public class IdentitySTSClient {

/**
* @param args
*/

final static String RELYING_PARTY_SERVICE_EPR = "http://localhost:8280/services/echo";
final static String ESB_TRANS_EPR = "http://localhost:8280/services/test";
final static String STS_EPR = "https://localhost:9443/services/wso2carbon-sts";

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ConfigurationContext confContext = null;
Policy stsPolicy = null;
STSClient stsClient = null;
Policy servicePolicy = null;
Token responseToken = null;
String trustStore = null;

// You need to import the Identity Server, public certificate to this key store.
// By default it's there - if you use wso2carbon.jks from [ESB_HOME]\resources\security
trustStore = "wso2carbon.jks";
// We are accessing STS over HTTPS - so need to set trustStore parameters.
System.setProperty("javax.net.ssl.trustStore", trustStore);
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");

// Create configuration context - you will have Rampart module engaged in the
// client.axis2.xml
confContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem("repo",
"repo/conf/client.axis2.xml");

stsClient = new STSClient(confContext);

stsClient.setRstTemplate(getRSTTemplate());
stsClient.setAction(RahasConstants.WST_NS_05_02 + RahasConstants.RST_ACTION_SCT);

// This is the security policy we applied to Identity Server STS.
// You can see it by https://[IDENTITY_SERVER]/services/wso2carbon-sts?wsdl
stsPolicy = loadSTSPolicy("sts.policy.xml");

// This is the security of the relying party web service.
// This policy will accept a security token issued from Identity Server STS
servicePolicy = loadServicePolicy("service.policy.xml");

responseToken = stsClient.requestSecurityToken(servicePolicy, STS_EPR, stsPolicy,
RELYING_PARTY_SERVICE_EPR);

System.out.println(responseToken.getToken());

TokenStorage store = TrustUtil.getTokenStore(confContext);
store.add(responseToken);

ServiceClient client = new ServiceClient(confContext, null);
Options options = new Options();
options.setAction("urn:echoString");
options.setTo(new EndpointReference(RELYING_PARTY_SERVICE_EPR));
options.setProperty(org.apache.axis2.Constants.Configuration.TRANSPORT_URL, ESB_TRANS_EPR);
options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, servicePolicy);
options.setProperty(RampartMessageData.KEY_CUSTOM_ISSUED_TOKEN, responseToken.getId());
client.setOptions(options);

client.engageModule("addressing");
client.engageModule("rampart");

OMElement response = client.sendReceive(getPayload("Hello world1"));
System.out.println("Response : " + response);
}

private static Policy loadSTSPolicy(String xmlPath) throws Exception {
StAXOMBuilder builder = null;
Policy policy = null;
RampartConfig rc = null;

builder = new StAXOMBuilder(xmlPath);
policy = PolicyEngine.getPolicy(builder.getDocumentElement());
rc = new RampartConfig();
// User from the LDAP user store
rc.setUser("prabath");
// You need to have password call-back class to provide the user password
rc.setPwCbClass(PWCBHandler.class.getName());
policy.addAssertion(rc);
return policy;
}

private static Policy loadServicePolicy(String xmlPath) throws Exception {
StAXOMBuilder builder = null;
Policy policy = null;
RampartConfig rc = null;
CryptoConfig sigCryptoConfig = null;
String keystore = null;
Properties merlinProp = null;
CryptoConfig encrCryptoConfig = null;

builder = new StAXOMBuilder(xmlPath);
policy = PolicyEngine.getPolicy(builder.getDocumentElement());
rc = new RampartConfig();
rc.setUser("wso2carbon");
rc.setEncryptionUser("wso2carbon");
// You need to have password call-back class to provide the user password
rc.setPwCbClass(PWCBHandler.class.getName());

keystore = "wso2carbon.jks";
merlinProp = new Properties();
merlinProp.put("org.apache.ws.security.crypto.merlin.keystore.type", "JKS");
merlinProp.put("org.apache.ws.security.crypto.merlin.file", keystore);
merlinProp.put("org.apache.ws.security.crypto.merlin.keystore.password", "wso2carbon");

sigCryptoConfig = new CryptoConfig();
sigCryptoConfig.setProvider("org.apache.ws.security.components.crypto.Merlin");
sigCryptoConfig.setProp(merlinProp);

encrCryptoConfig = new CryptoConfig();
encrCryptoConfig.setProvider("org.apache.ws.security.components.crypto.Merlin");
encrCryptoConfig.setProp(merlinProp);

rc.setSigCryptoConfig(sigCryptoConfig);
rc.setEncrCryptoConfig(encrCryptoConfig);

policy.addAssertion(rc);
return policy;
}

private static OMElement getRSTTemplate() throws Exception {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMElement element = null;
OMElement elem = fac.createOMElement(Constants.RST_TEMPLATE);
TrustUtil.createTokenTypeElement(RahasConstants.VERSION_05_02, elem).setText(XML.SAML_NS);
TrustUtil.createKeyTypeElement(RahasConstants.VERSION_05_02, elem,
RahasConstants.KEY_TYPE_SYMM_KEY);
TrustUtil.createKeySizeElement(RahasConstants.VERSION_05_02, elem, 256);
element = TrustUtil.createClaims(RahasConstants.VERSION_05_02, elem,"http://wso2.org");
addClaimType(element,"http://wso2.org/claims/givenname");
return elem;
}

private static void addClaimType(OMElement parent,String uri) {
OMElement element = null;
element = parent.getOMFactory().createOMElement(new QName("http://schemas.xmlsoap.org/ws/2005/05/identity", "ClaimType", "wsid"),
parent);
element.addAttribute( parent.getOMFactory().createOMAttribute("Uri",null,uri));
}

private static OMElement getPayload(String value) {
OMFactory factory = null;
OMNamespace ns = null;
OMElement elem = null;
OMElement childElem = null;

factory = OMAbstractFactory.getOMFactory();
ns = factory.createOMNamespace("http://echo.services.core.carbon.wso2.org", "ns1");
elem = factory.createOMElement("echoString", ns);
childElem = factory.createOMElement("in", null);
childElem.setText(value);
elem.addChild(childElem);
return elem;
}
}

package org.apache.ws.axis2;

import org.apache.ws.security.WSPasswordCallback;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

public class PWCBHandler implements CallbackHandler {

public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
WSPasswordCallback cb = (WSPasswordCallback) callbacks[0];
if ("prabath".equals(cb.getIdentifier())) {
cb.setPassword("prabath");
} else {
cb.setPassword("wso2carbon");
}
}
}

Adding Mediation to WSO2 WSAS

WSO2 Synergies: ESB and Registry - Free webinar

This webinar, on 18th November 2008, will introduce you to both the WSO2 ESB and the WSO2 Registry, then focus on how these two technologies can collaborate to achieve goals such as centralized configuration and control of a mediation network, automatic run-time enforcement of design-time policies, business activity monitoring.

You should attend this webinar if you:

- Currently use, or are thinking about using, the WSO2 Registry or WSO2 ESB

- Are curious about the relationship between design-time and run-time governance

- Want to be able to centrally manage a network of ESB instances

Your presenter, Asanka Abeysinghe, is a WSO2 architect, who focuses on vertical market capabilities, including financial services. Asanka is also a committer of the Apache Software Foundation where he contributes to the Apache Synapse ESB project, upon which the WSO2 ESB is based.