WSO2 Identity Server and CarbonContextHolder issue
===

I developed a simple java client to test the dialog with a WSO2 Identity server.

On the request of the security token I got an exception:

> java.lang.NoClassDefFoundError: Could not initialize class
> org.wso2.carbon.utils.multitenancy.CarbonContextHolder

I have verified that the class CarbonContextHolder is in one of the jar included int the classpath. 

I verified that the identity server reecieve and send a correct message. The problem arise during the treatment of the received token.

the instruction that throws the Exception is 
<code>
responseToken = stsClient.requestSecurityToken(servicePolicy, STS_EPR, stsPolicy, RELYING_PARTY_SERVICE_EPR); 
</code>

The complete code:

    import org.apache.axiom.om.OMAbstractFactory;  
    import org.apache.axiom.om.OMElement;  
    import org.apache.axiom.om.OMFactory;  
    import org.apache.axiom.om.impl.builder.StAXOMBuilder;  
    import org.apache.axis2.AxisFault;
    import org.apache.axis2.client.Options;
    import org.apache.axis2.client.ServiceClient;
    import org.apache.axis2.client.Stub;
    import org.apache.axis2.context.ConfigurationContext;  
    import org.apache.axis2.context.ConfigurationContextFactory;  
    import org.apache.log4j.Level;
    import org.apache.log4j.LogManager;
    import org.apache.log4j.Logger;
    import org.apache.neethi.Policy;  
    import org.apache.neethi.PolicyEngine;  
    import org.apache.rahas.RahasConstants;  
    import org.apache.rahas.Token;  
    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.ws.secpolicy.Constants;  
    import org.wso2.carbon.utils.multitenancy.CarbonContextHolder; 
    import org.apache.ws.security.WSPasswordCallback;
    import javax.security.auth.callback.Callback;
    import javax.security.auth.callback.CallbackHandler;
    import javax.security.auth.callback.UnsupportedCallbackException;
    import java.io.IOException;
    import java.util.Collections;
    import java.util.List;  
    
    public class IdentitySTSClient {  
      
    class PWCBHandler implements CallbackHandler {
    
        public void handle(Callback[] callbacks) throws IOException,
                UnsupportedCallbackException {
            for (int i = 0; i < callbacks.length; i++) {
                WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
                String id = pwcb.getIdentifier();
                    pwcb.setPassword("prova");
            }
        }
    }
    
    
    /** 
    * @param args 
    */  
    final static String RELYING_PARTY_SERVICE_EPR = "http://10.118.37.40:9763/services/echo";  
    final static String STS_EPR = "https://10.118.37.40:9443/services/wso2carbon-sts";  
    final static String USER = "prova";
    final static String PASSWORD = "prova";
    
    /** 
    * @param args 
    * @throws Exception 
    */  
    public static void main(String[] args) throws Exception {  
    
    	List<Logger> loggers = Collections.<Logger>list(LogManager.getCurrentLoggers());
    	loggers.add(LogManager.getRootLogger());
    	for ( Logger logger : loggers ) {
    	    logger.setLevel(Level.OFF);
    	}
    	
    	ConfigurationContext confContext = null;  
    Policy stsPolicy = null;  
    STSClient stsClient = null;  
    Policy servicePolicy = null;  
    Token responseToken = null;  
    String trustStore = null;  
    String wsopath="D:/CSI/PRJ/AccessControl/wso2is-3.2.3/";
    // You need to import the Identity Server, public certificate to this key store.  
    trustStore = "D:/CSI/PRJ/AccessControl/wso2is-3.2.3/repository/resources/security/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  7
    confContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(wsopath+"repository/conf",null);  
    //confContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null,null);  
    
    stsClient = new STSClient(confContext);  
      
    stsClient.setRstTemplate(getRSTTemplate());  
    stsClient.setAction(RahasConstants.WST_NS_05_02 + RahasConstants.RST_ACTION_ISSUE);  
    
    // This is the security policy we applied to Identity Server STS.  
    // You can see it by https://[IDENTITY_SERVER]/services/wso2carbon-sts?wsdl  
    stsPolicy = loadPolicy(wsopath+"repository\\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 = loadPolicy(wsopath+"repository\\service.policy.xml");  
    
    Options options = new Options();
    options.setUserName(USER);
    options.setPassword(PASSWORD);
     
    options.setProperty(RampartMessageData.KEY_RAMPART_POLICY,
    		stsPolicy);
    
    stsClient.setOptions(options);
     
    //HERE WE GOT THE PROBLEM!!!!
    responseToken = stsClient.requestSecurityToken(servicePolicy, STS_EPR, stsPolicy, RELYING_PARTY_SERVICE_EPR);    
    
    
    System.out.println(responseToken.getToken());  
      
    }  
      
    private static Policy loadPolicy(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();  
    rc.setUser("prova");    
    // 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 OMElement getRSTTemplate() throws Exception {  
    OMFactory fac = OMAbstractFactory.getOMFactory();  
    OMElement elem = fac.createOMElement(Constants.RST_TEMPLATE);  
    
    
    TrustUtil.createTokenTypeElement(RahasConstants.VERSION_05_02, elem).setText(RahasConstants.TOK_TYPE_SAML_20);
    TrustUtil.createKeyTypeElement(RahasConstants.VERSION_05_02, elem, RahasConstants.KEY_TYPE_SYMM_KEY);
    TrustUtil.createKeySizeElement(RahasConstants.VERSION_05_02, elem, 256);
    
    
    
    return elem;  
    }  
    
    }  



The Exception

 

    Exception in thread "main" java.lang.NoClassDefFoundError: Could not initialize class org.wso2.carbon.utils.multitenancy.CarbonContextHolder
    	at org.wso2.carbon.core.multitenancy.TenantDomainHandler.invoke(TenantDomainHandler.java:38)
    	at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
    	at org.apache.axis2.engine.Phase.invoke(Phase.java:313)
    	at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:262)
    	at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:168)
    	at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:364)
    	at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:421)
    	at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
    	at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
    	at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:555)
    	at org.apache.rahas.client.STSClient.requestSecurityToken(STSClient.java:154)
    	at IdentitySTSClient.main(IdentitySTSClient.java:132)
     

and finally the response of the Identity server (grabbed from the SOAP message tracer)
 

       <soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
          <soapenv:Header xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
             <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="true">
                <wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Timestamp-6">
                   <wsu:Created>2012-07-18T14:54:44.608Z</wsu:Created>
                   <wsu:Expires>2012-07-18T14:59:44.608Z</wsu:Expires>
                </wsu:Timestamp>
             </wsse:Security>
             <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
             <wsa:MessageID>urn:uuid:0912f452-ac12-4797-83f6-c51e23e279c4</wsa:MessageID>
             <wsa:Action>urn:IssueTokenResponse</wsa:Action>
             <wsa:RelatesTo>urn:uuid:9a6a6015-c1e5-4c5e-b82d-da7a6b996a50</wsa:RelatesTo>
          </soapenv:Header>
          <soapenv:Body>
             <wst:RequestSecurityTokenResponse xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust">
                <wst:TokenType>http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0</wst:TokenType>
                <wst:KeySize>256</wst:KeySize>
                <wst:RequestedAttachedReference>
                   <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                      <wsse:Reference URI="#urn:uuid:0ECA142E3AA83D38571342623284597" ValueType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
                   </wsse:SecurityTokenReference>
                </wst:RequestedAttachedReference>
                <wst:RequestedUnattachedReference>
                   <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                      <wsse:Reference URI="urn:uuid:0ECA142E3AA83D38571342623284597" ValueType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
                   </wsse:SecurityTokenReference>
                </wst:RequestedUnattachedReference>
                <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
                   <wsa:EndpointReference xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
                      <wsa:Address>http://10.118.37.40:9763/services/echo</wsa:Address>
                   </wsa:EndpointReference>
                </wsp:AppliesTo>
                <wst:Lifetime>
                   <wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2012-07-18T14:54:44.591Z</wsu:Created>
                   <wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2012-07-18T14:59:44.591Z</wsu:Expires>
                </wst:Lifetime>
                <wst:RequestedSecurityToken>
                   <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="urn:uuid:0ECA142E3AA83D38571342623284597" IssueInstant="2012-07-18T14:54:44.591Z" Version="2.0">
                      <saml:Issuer>10.118.37.40</saml:Issuer>
                      <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                         <ds:SignedInfo>
                            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                            <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
                            <ds:Reference URI="#urn:uuid:0ECA142E3AA83D38571342623284597">
                               <ds:Transforms>
                                  <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                                  <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                                     <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="ds saml wsse xenc xs" />
                                  </ds:Transform>
                               </ds:Transforms>
                               <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                               <ds:DigestValue>uzDTgQ9YA6nh3c+9mU7mSdb5xYg=</ds:DigestValue>
                            </ds:Reference>
                         </ds:SignedInfo>
                         <ds:SignatureValue>SrA9B9x4Rg1uCBI9swFDi/nuo99y4Q776sIk3u1uwSqwp0A4qZyOIk1J2FMqAz3woCd9Ds7BU8ExbRhq+5eN4Ww/PXeC1zOl4OeIISyO9cp2heu5o2PRqgbTB+SCoO1IC0PDfHLtjFZ8uzCQnpIPUBshjtZP0ZOTWTIng/kJ2T8=</ds:SignatureValue>
                         <ds:KeyInfo>
                            <ds:X509Data>
                               <ds:X509Certificate>MIICNTCCAZ6gAwIBAgIES343gjANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxDTALBgNVBAoMBFdTTzIxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xMDAyMTkwNzAyMjZaFw0zNTAyMTMwNzAyMjZaMFUxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzENMAsGA1UECgwEV1NPMjESMBAGA1UEAwwJbG9jYWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUp/oV1vWc8/TkQSiAvTousMzOM4asB2iltr2QKozni5aVFu818MpOLZIr8LMnTzWllJvvaA5RAAdpbECb+48FjbBe0hseUdN5HpwvnH/DW8ZccGvk53I6Orq7hLCv1ZHtuOCokghz/ATrhyPq+QktMfXnRS4HrKGJTzxaCcU7OQIDAQABoxIwEDAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEFBQADgYEAW5wPR7cr1LAdq+IrR44iQlRG5ITCZXY9hI0PygLP2rHANh+PYfTmxbuOnykNGyhM6FjFLbW2uZHQTY1jMrPprjOrmyK5sjJRO4d1DeGHT/YnIjs9JogRKv4XHECwLtIVdAbIdWHEtVZJyMSktcyysFcvuhPQK8Qc/E/Wq8uHSCo=</ds:X509Certificate>
                            </ds:X509Data>
                         </ds:KeyInfo>
                      </ds:Signature>
                      <saml:Subject>
                         <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">prova</saml:NameID>
                         <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:holder-of-key">
                            <saml:SubjectConfirmationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" NotBefore="2012-07-18T14:54:44.591Z" NotOnOrAfter="2012-07-18T14:59:44.591Z" xsi:type="saml:KeyInfoConfirmationDataType">
                               <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                                  <xenc:EncryptedKey Id="EncKeyId-2D53CE51F660C26766134262328459212">
                                     <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
                                     <ds:KeyInfo>
                                        <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                                           <wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1">a/jhNus21KVuoFx65LmkW2O/l10=</wsse:KeyIdentifier>
                                        </wsse:SecurityTokenReference>
                                     </ds:KeyInfo>
                                     <xenc:CipherData>
                                        <xenc:CipherValue>awlJKSSuuAFgXFQwZ6xacQrHHKVKN2lJE6Yglbv+IfJt/KpWMbCj8D1tl7y78vFlNU9Ogn48NKGISCSSZp3yEWZrbTHMUEEdzO04IkPCZ/dqFk1xHWL9JeQq1DLwDuWLeXzW1rotmzAGenotwBcZudvoY48FdRdQOmcTyfQ6sGE=</xenc:CipherValue>
                                     </xenc:CipherData>
                                  </xenc:EncryptedKey>
                               </ds:KeyInfo>
                            </saml:SubjectConfirmationData>
                         </saml:SubjectConfirmation>
                      </saml:Subject>
                      <saml:Conditions NotBefore="2012-07-18T14:54:44.591Z" NotOnOrAfter="2012-07-18T14:59:44.591Z" />
                      <saml:AttributeStatement>
                         <saml:Attribute Name="Name" NameFormat="https://rahas.apache.org/saml/attrns">
                            <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Colombo</saml:AttributeValue>
                         </saml:Attribute>
                      </saml:AttributeStatement>
                   </saml:Assertion>
                </wst:RequestedSecurityToken>
                <wst:RequestedProofToken>
                   <wst:BinarySecret>mLp93tRQrAxEgbfu7AroIDLtncnkEe4wR+C0BB8oSZI=</wst:BinarySecret>
                </wst:RequestedProofToken>
             </wst:RequestSecurityTokenResponse>
          </soapenv:Body>    </soapenv:Envelope>

 
Thanks