You are viewing a plain text version of this content. The canonical link for it is here.
Posted to java-commits@axis.apache.org by am...@apache.org on 2012/03/08 09:11:33 UTC

svn commit: r1298292 [1/3] - in /axis/axis2/java/rampart/trunk/modules/rampart-trust/src: main/java/org/apache/rahas/ main/java/org/apache/rahas/client/ main/java/org/apache/rahas/impl/ main/java/org/apache/rahas/impl/util/ test/java/org/apache/rahas/i...

Author: amilaj
Date: Thu Mar  8 08:11:32 2012
New Revision: 1298292

URL: http://svn.apache.org/viewvc?rev=1298292&view=rev
Log:
Refactored SAML2TokenIssuer and cleaned up code. Created a test framework to write unit tests for trust scenarios. Fixed documentation errors. Reduced code duplication. Added more tests.

Added:
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/AbstractTestCase.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestCallbackHandler.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSAMLCallbackHandler.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSTSClient.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/resources/repo/
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/resources/repo/conf/
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/resources/repo/conf/client.axis2.xml
Modified:
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/Rahas.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasConstants.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/TokenIssuer.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/client/STSClient.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/errors.properties
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAML2TokenIssuer.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/CommonUtilTest.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/SAMLUtilsTest.java
    axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestUtil.java

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/Rahas.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/Rahas.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/Rahas.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/Rahas.java Thu Mar  8 08:11:32 2012
@@ -36,6 +36,9 @@ public class Rahas implements Module {
 
         try {
             RampartSAMLBootstrap.bootstrap();
+
+            // Initialize XML security
+            org.apache.xml.security.Init.init();
         } catch (ConfigurationException ex) {
             throw new AxisFault("Failed to bootstrap OpenSAML", ex);
         }

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasConstants.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasConstants.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasConstants.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasConstants.java Thu Mar  8 08:11:32 2012
@@ -84,6 +84,7 @@ public class RahasConstants {
     public static final String KEY_TYPE_SYMM_KEY = "/SymmetricKey";
     public static final String KEY_TYPE_PUBLIC_KEY = "/PublicKey";
     public static final String KEY_TYPE_BEARER = "/Bearer";
+    public static final String KEY_TYPE_HOK = "/Bearer";
 
     //Attr values
     public static final String BIN_SEC_TYPE_NONCE = "/Nonce";

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java Thu Mar  8 08:11:32 2012
@@ -35,6 +35,7 @@ import javax.xml.namespace.QName;
 
 import java.security.Principal;
 import java.security.cert.X509Certificate;
+import java.util.Date;
 import java.util.List;
 
 /**
@@ -56,7 +57,7 @@ public class RahasData {
     
     private String tokenId;
 
-    private int keysize = -1;
+    private int keySize = -1;
 
     private String computedKeyAlgo;
 
@@ -85,6 +86,11 @@ public class RahasData {
     private String  claimDialect;
     
     private Assertion assertion;
+
+    private Date assertionCreatedDate;
+
+    private Date assertionExpiringDate;
+
     /**
      * Create a new RahasData instance and populate it with the information from
      * the request.
@@ -138,6 +144,10 @@ public class RahasData {
 
     }
 
+    public RahasData() {
+
+    }
+
     /**
      * Processes the authenticated user information from the WSS4J security
      * results.
@@ -284,17 +294,17 @@ public class RahasData {
             if (text != null && !"".equals(text.trim())) {
                 try {
                     //Set key size
-                    this.keysize = Integer.parseInt(text.trim());
+                    this.keySize = Integer.parseInt(text.trim());
 
                     //Create an empty array to hold the key
-                    this.ephmeralKey = new byte[this.keysize/8];
+                    this.ephmeralKey = new byte[this.keySize/8];
                 } catch (NumberFormatException e) {
                     throw new TrustException(TrustException.INVALID_REQUEST,
                                              new String[]{"invalid wst:Keysize value"}, e);
                 }
             }
         }
-        this.keysize = -1;
+        this.keySize = -1;
     }
     
     /**
@@ -379,7 +389,7 @@ public class RahasData {
     private void processEntropy() throws TrustException {
         OMElement entropyElem = this.rstElement
                 .getFirstChildWithName(new QName(this.wstNs,
-                                                 RahasConstants.IssuanceBindingLocalNames.ENTROPY));
+                        RahasConstants.IssuanceBindingLocalNames.ENTROPY));
 
         if (entropyElem != null) {
             OMElement binSecElem = entropyElem.getFirstElement();
@@ -430,13 +440,39 @@ public class RahasData {
     }
 
     /**
+     * Sets the given message context as in message context.
+     * @param context The message context.
+     */
+    public void setInMessageContext(MessageContext context) {
+        this.inMessageContext = context;
+    }
+
+    /**
+     * @deprecated  As of Rampart 1.7. Use {@code getKeySize}.
      * @return Returns the keysize.
      */
+    @Deprecated
     public int getKeysize() {
-        return keysize;
+        return keySize;
+    }
+
+    /**
+     * @return Returns the keySize.
+     */
+    public int getKeySize() {
+        return keySize;
+    }
+
+    /**
+     * Sets the key size.
+     * @param size Size of the key.
+     */
+    public void setKeySize(int size) {
+        this.keySize = size;
     }
 
     /**
+     * // TODO changes this keytype to an enumeration
      * @return Returns the keyType.
      */
     public String getKeyType() {
@@ -546,5 +582,19 @@ public class RahasData {
         return appliesToEpr;
     }
 
+    public Date getAssertionCreatedDate() {
+        return assertionCreatedDate;
+    }
+
+    public void setAssertionCreatedDate(Date assertionCreatedDate) {
+        this.assertionCreatedDate = assertionCreatedDate;
+    }
 
+    public Date getAssertionExpiringDate() {
+        return assertionExpiringDate;
+    }
+
+    public void setAssertionExpiringDate(Date assertionExpiringDate) {
+        this.assertionExpiringDate = assertionExpiringDate;
+    }
 }

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/TokenIssuer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/TokenIssuer.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/TokenIssuer.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/TokenIssuer.java Thu Mar  8 08:11:32 2012
@@ -31,7 +31,7 @@ public interface TokenIssuer {
      * @param data A populated <code>RahasData</code> instance
      * @return The response <code>soap:Envelope</code> for the given issue
      *         request.
-     * @throws TrustException
+     * @throws TrustException If an error occurred while creating the token.
      */
     SOAPEnvelope issue(RahasData data) throws TrustException;
 
@@ -40,7 +40,7 @@ public interface TokenIssuer {
      *
      * @param data A populated <code>RahasData</code> instance
      * @return Returns the <code>wsa:Action</code> of the response
-     * @throws TrustException
+     * @throws TrustException If an error occurred while during operation.
      */
     String getResponseAction(RahasData data) throws TrustException;
 
@@ -50,7 +50,7 @@ public interface TokenIssuer {
      * This is the text value of the &lt;configuration-file&gt; element of the
      * token-dispatcher-configuration
      *
-     * @param configFile
+     * @param configFile Sets the token issuer configuration file.
      */
     void setConfigurationFile(String configFile);
 
@@ -71,7 +71,7 @@ public interface TokenIssuer {
      * <code>org.apache.axis2.description.Parameter</code> object available in
      * the via the messageContext when the <code>TokenIssuer</code> is called.
      *
-     * @param configParamName
+     * @param configParamName  The configuration parameter to be set.
      * @see org.apache.axis2.description.Parameter
      */
     void setConfigurationParamName(String configParamName);

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/client/STSClient.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/client/STSClient.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/client/STSClient.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/client/STSClient.java Thu Mar  8 08:11:32 2012
@@ -124,9 +124,7 @@ public class STSClient {
                                       String appliesTo) throws TrustException {
         try {
             QName rstQn = new QName("requestSecurityToken");
-            String requestType =
-                    TrustUtil.getWSTNamespace(version) + RahasConstants.REQ_TYPE_ISSUE;
-            
+
             ServiceClient client = getServiceClient(rstQn, issuerAddress);
             
             for (int i = 0; i < parameters.size(); i++) {
@@ -137,9 +135,6 @@ public class STSClient {
             client.getServiceContext().setProperty(RAMPART_POLICY, issuerPolicy);
             client.getOptions().setSoapVersionURI(this.soapVersion);
 
-            //TODO Remove later
-            client.getOptions().setTimeOutInMilliSeconds(300000);
-
             if(this.addressingNs != null) {
                 client.getOptions().setProperty(AddressingConstants.WS_ADDRESSING_VERSION, this.addressingNs);
             }
@@ -151,7 +146,7 @@ public class STSClient {
             
             try {
                 OMElement response = client.sendReceive(rstQn,
-                                                        createIssueRequest(requestType, appliesTo));
+                                                        createIssueRequest(appliesTo));
     
                 return processIssueResponse(version, response, issuerAddress);
             } finally {
@@ -389,10 +384,14 @@ public class STSClient {
     }
 
     /**
-     * @param result
-     * @return Token
+     * Processes the response from Token issuer.
+     * @param version The supported version.
+     * @param result Resulting token response from token issuer.
+     * @param issuerAddress The respective token applying entity (as a url)
+     * @return The issued token.
+     * @throws TrustException If an error occurred while extracting token from response.
      */
-    private Token processIssueResponse(int version, OMElement result, 
+    protected Token processIssueResponse(int version, OMElement result,
             String issuerAddress) throws TrustException {
         OMElement rstr = result;
 
@@ -650,15 +649,15 @@ public class STSClient {
     }
 
     /**
-     * Create the RST request.
-     *
-     * @param requestType
-     * @param appliesTo
-     * @return OMElement
-     * @throws TrustException
+     * This creates a request security token (RST) message.
+     * @param appliesTo The address which token is applicable to.
+     * @return The axiom object representation of RST.
+     * @throws TrustException If an error occurred while creating the RST.
      */
-    private OMElement createIssueRequest(String requestType,
-                                         String appliesTo) throws TrustException {
+    protected OMElement createIssueRequest(String appliesTo) throws TrustException {
+
+        String requestType =
+                    TrustUtil.getWSTNamespace(version) + RahasConstants.REQ_TYPE_ISSUE;
 
         if (log.isDebugEnabled()) {
             log.debug("Creating request with request type: " + requestType +

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/errors.properties
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/errors.properties?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/errors.properties (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/errors.properties Thu Mar  8 08:11:32 2012
@@ -75,7 +75,7 @@ samlIssuerKeyPasswdMissing = issuerKeyPa
 samlIssuerKeyAliasMissing = user value missing in the SAMLTokenIssuer configuration
 samlConverstionError = Error in converting a SAML token to DOOM 
 samlAssertionCreationError = Error in creating a SAMLToken using Opensaml library
-aliasMissingForService = Certificate alias missing for service : \"{0}\"
+aliasMissingForService = Certificate alias missing for service address : \"{0}\"
 
 samlIssuerNameMissing = issuerName value missing in the SAMLTokenIssuer configuration
 samlUnsupportedPrincipal = Unsupported principal : \"{0}\"
@@ -89,6 +89,7 @@ errorInCancelingToken = Error occurred w
 errorExtractingTokenId  = Error occurred while extracting token id from the Security Token Reference
 lifeTimeElemMissing = Lifetime element is missing in the RSTR
 unableToRetrieveCallbackHandler= Unable to retrieve callback handler
+unidentifiedKeyType= Unidentified KeyType found : \"{0}\"
 
 #SAMLUtils errors
 builderNotFound = Unable to find OpenSAML builder for object : \"{0}\"
@@ -100,4 +101,6 @@ sha1NotFound = Unable to find SHA-1 algo
 certificateEncodingError = Error encoding certificate
 
 errorLoadingCryptoProperties = An error occurred while loading crypto properties
-errorLoadingCryptoPropertiesFile = An error occurred while loading crypto properties from file : \"{0}\"
\ No newline at end of file
+errorLoadingCryptoPropertiesFile = An error occurred while loading crypto properties from file : \"{0}\"
+
+errorCallingSAMLCallback = An error occurred while calling SAML callback handler to get attributes.
\ No newline at end of file

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAML2TokenIssuer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAML2TokenIssuer.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAML2TokenIssuer.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAML2TokenIssuer.java Thu Mar  8 08:11:32 2012
@@ -16,43 +16,23 @@
 
 package org.apache.rahas.impl;
 
-import org.apache.axiom.om.OMAbstractFactory;
 import org.apache.axiom.om.OMElement;
 import org.apache.axiom.om.OMNode;
-import org.apache.axiom.om.dom.DOMMetaFactory;
 import org.apache.axiom.soap.SOAPEnvelope;
 import org.apache.axis2.context.MessageContext;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.rahas.*;
-import org.apache.rahas.impl.util.CommonUtil;
-import org.apache.rahas.impl.util.SAMLAttributeCallback;
-import org.apache.rahas.impl.util.SAMLCallbackHandler;
-import org.apache.rahas.impl.util.SignKeyHolder;
-import org.apache.ws.security.WSConstants;
-import org.apache.ws.security.WSSecurityException;
+import org.apache.rahas.impl.util.*;
 import org.apache.ws.security.components.crypto.Crypto;
-import org.apache.ws.security.message.WSSecEncryptedKey;
-import org.apache.ws.security.util.Base64;
-import org.apache.ws.security.util.Loader;
-import org.apache.ws.security.util.UUIDGenerator;
 import org.apache.ws.security.util.XmlSchemaDateFormat;
 import org.apache.xml.security.c14n.Canonicalizer;
 import org.apache.xml.security.signature.XMLSignature;
-import org.apache.xml.security.utils.EncryptionConstants;
 import org.joda.time.DateTime;
 import org.opensaml.Configuration;
 import org.opensaml.common.SAMLException;
 import org.opensaml.common.SAMLObjectBuilder;
-import org.opensaml.common.SAMLVersion;
-import org.opensaml.saml1.core.NameIdentifier;
 import org.opensaml.saml2.core.*;
-import org.opensaml.saml2.core.impl.AssertionBuilder;
-import org.opensaml.saml2.core.impl.ConditionsBuilder;
-import org.opensaml.saml2.core.impl.IssuerBuilder;
-import org.opensaml.saml2.core.impl.NameIDBuilder;
-import org.opensaml.xml.XMLObject;
-import org.opensaml.xml.XMLObjectBuilder;
 import org.opensaml.xml.XMLObjectBuilderFactory;
 import org.opensaml.xml.io.*;
 import org.opensaml.xml.schema.XSString;
@@ -60,27 +40,19 @@ import org.opensaml.xml.schema.impl.XSSt
 import org.opensaml.xml.signature.*;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-import org.w3c.dom.bootstrap.DOMImplementationRegistry;
-import org.w3c.dom.ls.DOMImplementationLS;
-import org.w3c.dom.ls.LSOutput;
-import org.w3c.dom.ls.LSSerializer;
-
-import javax.xml.namespace.QName;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
+
 import java.security.PrivateKey;
 import java.security.cert.CertificateEncodingException;
 import java.security.cert.X509Certificate;
 import java.text.DateFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Date;
 import java.util.List;
 
+/**
+ * WS-Trust based SAML2 token issuer. This issuer will generate request security token responses with SAML2
+ * assertions.
+ */
 public class SAML2TokenIssuer implements TokenIssuer {
 
     private String configParamName;
@@ -93,393 +65,351 @@ public class SAML2TokenIssuer implements
 
     private boolean isSymmetricKeyBasedHoK = false;
 
+    private SAMLTokenIssuerConfig tokenIssuerConfiguration;
+
     private static Log log = LogFactory.getLog(SAML2TokenIssuer.class);
 
+    /**
+     * This is the main method which issues SAML2 assertions as security token responses. This method will
+     * read issuer configuration and in message context properties (Basically request security token properties)
+     * and will create a security token response with SAML2 assertion. The attributes are retrieved from a callback
+     * class.
+     * @param data A populated <code>RahasData</code> instance
+     * @return A SOAP message with security token response (as per ws-trust spec) with a SAML2 assertion.
+     * @throws TrustException If an error occurred while creating the response.
+     */
     public SOAPEnvelope issue(RahasData data) throws TrustException {
         MessageContext inMsgCtx = data.getInMessageContext();
 
-        try {
-            SAMLTokenIssuerConfig tokenIssuerConfiguration = CommonUtil.getTokenIssuerConfiguration(this.configElement,
-                    this.configFile, inMsgCtx.getParameter(this.configParamName));
-
-            if (tokenIssuerConfiguration == null) {
+        this.tokenIssuerConfiguration = CommonUtil.getTokenIssuerConfiguration(this.configElement,
+                this.configFile, inMsgCtx.getParameter(this.configParamName));
 
-                if (log.isDebugEnabled()) {
-                    String parameterName;
-                    if (this.configElement != null) {
-                        parameterName = "OMElement - " + this.configElement.toString();
-                    } else if (this.configFile != null) {
-                        parameterName = "File - " + this.configFile;
-                    } else if (this.configParamName != null) {
-                        parameterName = "With message context parameter name - " + this.configParamName;
-                    } else {
-                        parameterName = "No method to build configurations";
-                    }
+        if (tokenIssuerConfiguration == null) {
 
-                    log.debug("Unable to build token configurations, " + parameterName);
+            if (log.isDebugEnabled()) {
+                String parameterName;
+                if (this.configElement != null) {
+                    parameterName = "OMElement - " + this.configElement.toString();
+                } else if (this.configFile != null) {
+                    parameterName = "File - " + this.configFile;
+                } else if (this.configParamName != null) {
+                    parameterName = "With message context parameter name - " + this.configParamName;
+                } else {
+                    parameterName = "No method to build configurations";
                 }
 
-                throw new TrustException("configurationIsNull");
-            }
-
-            SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx
-                    .getEnvelope().getNamespace().getNamespaceURI());
-
-            Crypto crypto = tokenIssuerConfiguration.getIssuerCrypto(inMsgCtx
-                        .getAxisService().getClassLoader());
-
-            // Get the document
-            Document doc = ((Element) env).getOwnerDocument();
-
-            // Get the key size and create a new byte array of that size
-            int keySize = data.getKeysize();
-            String keyType = data.getKeyType();
-
-            keySize = (keySize == -1) ? tokenIssuerConfiguration.getKeySize() : keySize;
-
-            //Build the assertion
-            AssertionBuilder assertionBuilder = new AssertionBuilder();
-            Assertion assertion = assertionBuilder.buildObject();
-            assertion.setVersion(SAMLVersion.VERSION_20);
-
-            // Set an UUID as the ID of an assertion
-            assertion.setID(UUIDGenerator.getUUID());
-
-            //Set the issuer
-            IssuerBuilder issuerBuilder = new IssuerBuilder();
-            Issuer issuer = issuerBuilder.buildObject();
-            issuer.setValue(tokenIssuerConfiguration.getIssuerName());
-            assertion.setIssuer(issuer);
-
-            // Set the issued time.
-            assertion.setIssueInstant(new DateTime());
-
-            // Validity period
-            DateTime creationDate = new DateTime();
-            DateTime expirationDate = new DateTime(creationDate.getMillis() + tokenIssuerConfiguration.getTtl());
-
-            // These variables are used to build the trust assertion
-            Date creationTime = creationDate.toDate();
-            Date expirationTime = expirationDate.toDate();
-
-            Conditions conditions = new ConditionsBuilder().buildObject();
-            conditions.setNotBefore(creationDate);
-            conditions.setNotOnOrAfter(expirationDate);
-            assertion.setConditions(conditions);
-
-            // Create the subject
-            Subject subject;
-
-            if (!data.getKeyType().endsWith(RahasConstants.KEY_TYPE_BEARER)) {
-                subject = createSubjectWithHolderOfKeySC(tokenIssuerConfiguration, doc, crypto, creationDate, expirationDate, data);
-            }
-            else{
-                subject = createSubjectWithBearerSC(data);
+                log.debug("Unable to build token configurations, " + parameterName);
             }
 
-            // Set the subject
-            assertion.setSubject(subject);
+            throw new TrustException("configurationIsNull");
+        }
 
-            // If a SymmetricKey is used build an attr stmt, if a public key is build an authn stmt. 
-            if (isSymmetricKeyBasedHoK) {
-                AttributeStatement attrStmt = createAttributeStatement(data, tokenIssuerConfiguration);
-                assertion.getAttributeStatements().add(attrStmt);
-            } else {
-                AuthnStatement authStmt = createAuthnStatement(data);
-                assertion.getAuthnStatements().add(authStmt);
-                if (data.getClaimDialect() != null && data.getClaimElem() != null) {
-                    assertion.getAttributeStatements().add(createAttributeStatement(data, tokenIssuerConfiguration));
-                }
-            }
+        SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx
+                .getEnvelope().getNamespace().getNamespaceURI());
 
-            // Create a SignKeyHolder to hold the crypto objects that are used to sign the assertion
-            SignKeyHolder signKeyHolder = createSignKeyHolder(tokenIssuerConfiguration, crypto);
+        Crypto crypto = tokenIssuerConfiguration.getIssuerCrypto(inMsgCtx
+                .getAxisService().getClassLoader());
 
-            // Sign the assertion
-            assertion = setSignature(assertion, signKeyHolder);
+        // Get the document
+        Document doc = ((Element) env).getOwnerDocument();
 
+        // Get the key size and create a new byte array of that size
+        int keySize = data.getKeySize();
+        keySize = (keySize == -1) ? tokenIssuerConfiguration.getKeySize() : keySize;
 
-            OMElement rstrElem;
-            int wstVersion = data.getVersion();
-            if (RahasConstants.VERSION_05_02 == wstVersion) {
-                rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
-                        wstVersion, env.getBody());
-            } else {
-                OMElement rstrcElem = TrustUtil
-                        .createRequestSecurityTokenResponseCollectionElement(
-                                wstVersion, env.getBody());
-                rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
-                        wstVersion, rstrcElem);
-            }
+        data.setKeySize(keySize);
 
-            TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(
-                    RahasConstants.TOK_TYPE_SAML_20);
+        // Build the assertion
+        Assertion assertion = buildAssertion(doc, crypto, data);
 
-            if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
-                TrustUtil.createKeySizeElement(wstVersion, rstrElem, keySize);
-            }
+        // Sign the assertion
+        Assertion signedAssertion = signAssertion(doc, assertion, crypto);
 
-            if (tokenIssuerConfiguration.isAddRequestedAttachedRef()) {
-                TrustUtil.createRequestedAttachedRef(wstVersion, rstrElem, "#"
-                        + assertion.getID(), RahasConstants.TOK_TYPE_SAML_20);
-            }
+        return createRequestSecurityTokenResponse(data, signedAssertion, env);
 
-            if (tokenIssuerConfiguration.isAddRequestedUnattachedRef()) {
-                TrustUtil.createRequestedUnattachedRef(wstVersion, rstrElem,
-                        assertion.getID(), RahasConstants.TOK_TYPE_SAML_20);
-            }
+    }
 
-            if (data.getAppliesToAddress() != null) {
-                TrustUtil.createAppliesToElement(rstrElem, data
-                        .getAppliesToAddress(), data.getAddressingNs());
-            }
+    /**
+     * This method prepares the final response. This method will create a request security token response as
+     * specified in WS-Trust specification. The equivalent XML would take following format,
+     * <wst:RequestSecurityTokenResponse xmlns:wst="...">
+     *       <wst:TokenType>...</wst:TokenType>
+     *       <wst:RequestedSecurityToken>...</wst:RequestedSecurityToken>
+     *       ...
+     *       <wsp:AppliesTo xmlns:wsp="...”>...</wsp:AppliesTo>
+     *       <wst:RequestedAttachedReference>
+     *       ...
+     *       </wst:RequestedAttachedReference>
+     *       <wst:RequestedUnattachedReference>
+     *       ...
+     *       </wst:RequestedUnattachedReference>
+     *       <wst:RequestedProofToken>...</wst:RequestedProofToken>
+     *       <wst:Entropy>
+     *       <wst:BinarySecret>...</wst:BinarySecret>
+     *       </wst:Entropy>
+     *       <wst:Lifetime>...</wst:Lifetime>
+     *   </wst:RequestSecurityTokenResponse>
+     *
+     *   Thus the RequestedSecurityToken will have SAML2 assertion passed.
+     * @param rahasData The configuration data which comes with RST
+     * @param assertion OpenSAM representation of SAML2 assertion.
+     * @param soapEnvelope SOAP message envelope
+     * @return SOAPEnvelope which includes RequestSecurityTokenResponse
+     * @throws TrustException If an error occurred while creating RequestSecurityTokenResponse.
+     */
+    protected SOAPEnvelope createRequestSecurityTokenResponse(RahasData rahasData,
+                                                      Assertion assertion,
+                                                      SOAPEnvelope soapEnvelope) throws TrustException {
 
-            // Use GMT time in milliseconds
-            DateFormat zulu = new XmlSchemaDateFormat();
+        OMElement requestSecurityTokenResponse;
+        int wstVersion = rahasData.getVersion();
+        if (RahasConstants.VERSION_05_02 == wstVersion) {
+            requestSecurityTokenResponse = TrustUtil.createRequestSecurityTokenResponseElement(
+                    wstVersion, soapEnvelope.getBody());
+        } else {
+            OMElement requestSecurityTokenResponseCollectionElement = TrustUtil
+                    .createRequestSecurityTokenResponseCollectionElement(
+                            wstVersion, soapEnvelope.getBody());
+            requestSecurityTokenResponse = TrustUtil.createRequestSecurityTokenResponseElement(
+                    wstVersion, requestSecurityTokenResponseCollectionElement);
+        }
 
-            // Add the Lifetime element
-            TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu
-                    .format(creationTime), zulu.format(expirationTime));
+        TrustUtil.createTokenTypeElement(wstVersion, requestSecurityTokenResponse).setText(
+                RahasConstants.TOK_TYPE_SAML_20);
 
-            // Create the RequestedSecurityToken element and add the SAML token
-            // to it
-            OMElement reqSecTokenElem = TrustUtil
-                    .createRequestedSecurityTokenElement(wstVersion, rstrElem);
-            Token assertionToken;
+        if (rahasData.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
+            TrustUtil.createKeySizeElement(wstVersion, requestSecurityTokenResponse, rahasData.getKeySize());
+        }
 
-            Node tempNode = assertion.getDOM();
+        if (tokenIssuerConfiguration.isAddRequestedAttachedRef()) {
+            TrustUtil.createRequestedAttachedRef(wstVersion, requestSecurityTokenResponse, "#"
+                    + assertion.getID(), RahasConstants.TOK_TYPE_SAML_20);
+        }
 
-            //Serializing and re-generating the AXIOM element using the DOM Element created using xerces
-            Element element = assertion.getDOM();
+        if (tokenIssuerConfiguration.isAddRequestedUnattachedRef()) {
+            TrustUtil.createRequestedUnattachedRef(wstVersion, requestSecurityTokenResponse,
+                    assertion.getID(), RahasConstants.TOK_TYPE_SAML_20);
+        }
 
-            ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
+        if (rahasData.getAppliesToAddress() != null) {
+            TrustUtil.createAppliesToElement(requestSecurityTokenResponse, rahasData
+                    .getAppliesToAddress(), rahasData.getAddressingNs());
+        }
 
-            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
+        // Use GMT time in milliseconds
+        DateFormat xmlSchemaDateFormat = new XmlSchemaDateFormat();
 
-            DOMImplementationLS impl =
-                    (DOMImplementationLS) registry.getDOMImplementation("LS");
+        // Add the Lifetime element
+        TrustUtil.createLifetimeElement(wstVersion, requestSecurityTokenResponse, xmlSchemaDateFormat
+                .format(rahasData.getAssertionCreatedDate()),
+                xmlSchemaDateFormat.format(rahasData.getAssertionExpiringDate()));
 
-            LSSerializer writer = impl.createLSSerializer();
-            LSOutput output = impl.createLSOutput();
-            output.setByteStream(byteArrayOutputStrm);
-            writer.write(element, output);
-            String elementString = byteArrayOutputStrm.toString();
+        // Create the RequestedSecurityToken element and add the SAML token
+        // to it
+        OMElement requestedSecurityTokenElement = TrustUtil
+                .createRequestedSecurityTokenElement(wstVersion, requestSecurityTokenResponse);
 
-            DocumentBuilderFactory documentBuilderFactory = ((DOMMetaFactory)OMAbstractFactory.getMetaFactory(
-                    OMAbstractFactory.FEATURE_DOM)).newDocumentBuilderFactory();
-            DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
-            Document document = docBuilder.parse(new ByteArrayInputStream(elementString.trim().getBytes()));
-            Element assertionElement = document.getDocumentElement();
+        Element assertionElement = assertion.getDOM();
 
-            reqSecTokenElem.addChild((OMNode) ((Element) rstrElem)
-                    .getOwnerDocument().importNode(tempNode, true));
+        requestedSecurityTokenElement.addChild((OMNode)assertionElement);
 
-            // Store the token
-            assertionToken = new Token(assertion.getID(),
-                    (OMElement) assertionElement, creationTime,
-                    expirationTime);
+        // Store the token
+        Token assertionToken = new Token(assertion.getID(),
+                (OMElement) assertionElement, rahasData.getAssertionCreatedDate(),
+                rahasData.getAssertionExpiringDate());
 
-            // At this point we definitely have the secret
-            // Otherwise it should fail with an exception earlier
-            assertionToken.setSecret(data.getEphmeralKey());
-            TrustUtil.getTokenStore(inMsgCtx).add(assertionToken);
+        // At this point we definitely have the secret
+        // Otherwise it should fail with an exception earlier
+        assertionToken.setSecret(rahasData.getEphmeralKey());
+        TrustUtil.getTokenStore(rahasData.getInMessageContext()).add(assertionToken);
 
-            if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
+        if (rahasData.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
                 && tokenIssuerConfiguration.getKeyComputation()
-                    != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {
-
-                // Add the RequestedProofToken
-                TokenIssuerUtil.handleRequestedProofToken(data, wstVersion,
-                                                          tokenIssuerConfiguration, rstrElem, assertionToken, doc);
-            }
+                != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {
 
-            return env;
+            Document doc = ((Element) soapEnvelope).getOwnerDocument();
 
-        } catch (Exception e) {
-            e.printStackTrace();
+            // Add the RequestedProofToken
+            TokenIssuerUtil.handleRequestedProofToken(rahasData, wstVersion,
+                    tokenIssuerConfiguration,
+                    requestSecurityTokenResponse, assertionToken, doc);
         }
 
-        return null;
+        return soapEnvelope;
+
     }
 
     /**
-     * This method is used to create the subject of an assertion
-     * @param config
-     * @param doc
-     * @param crypto
-     * @param creationTime
-     * @param expirationTime
-     * @param data
-     * @return Subject
-     * @throws Exception
-     */
-    Subject createSubjectWithHolderOfKeySC(SAMLTokenIssuerConfig config,
-                                                   Document doc, Crypto crypto,
-                                                   DateTime creationTime,
-                                                   DateTime expirationTime, RahasData data) throws Exception {
-
-
-        // TODO modify these to use proper SAML apis
-
-        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
-        SAMLObjectBuilder<Subject> subjectBuilder =
-                (SAMLObjectBuilder<Subject>) builderFactory.getBuilder(Subject.DEFAULT_ELEMENT_NAME);
-        Subject subject = subjectBuilder.buildObject();
-        Element keyInfoElem = null;
-
-        // If it is a Symmetric Key
-        if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
-
-            isSymmetricKeyBasedHoK = true;
-            Element encryptedKeyElem;
-            X509Certificate serviceCert = null;
-            try {
-
-                // Get ApliesTo to figure out which service to issue the token
-                // for
-                serviceCert = config.getServiceCert(crypto, data.getAppliesToAddress());
-
-                // Create the encrypted key
-                WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
-
-                // Use thumbprint id
-                encrKeyBuilder
-                        .setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
-
-                // SEt the encryption cert
-                encrKeyBuilder.setUseThisCert(serviceCert);
-
-                // set keysize
-                int keysize = data.getKeysize();
-                keysize = (keysize != -1) ? keysize : config.getKeySize();
-
-                // TODO setting keysize is removed with wss4j 1.6 migration - do we actually need this ?
-
-                encrKeyBuilder.setEphemeralKey(TokenIssuerUtil.getSharedSecret(
-                        data, config.getKeyComputation(), keysize));
-
-                // Set key encryption algo
-                encrKeyBuilder
-                        .setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
-
-                // Build
-                encrKeyBuilder.prepare(doc, crypto);
-
-                // Extract the base64 encoded secret value
-                byte[] tempKey = new byte[keysize / 8];
-                System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey,
-                        0, keysize / 8);
-
-                data.setEphmeralKey(tempKey);
-
-                // Extract the Encryptedkey DOM element
-                encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
-            } catch (WSSecurityException e) {
-                throw new TrustException(
-                        "errorInBuildingTheEncryptedKeyForPrincipal",
-                        new String[]{serviceCert.getSubjectDN().getName()},
-                        e);
+     * This methods builds the SAML2 assertion. The equivalent XML would look as follows,
+     * <saml:Assertion
+     *      xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
+     *      xmlns:xs="http://www.w3.org/2001/XMLSchema"
+     *      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+     *      ID="b07b804c-7c29-ea16-7300-4f3d6f7928ac"
+     *      Version="2.0"
+     *      IssueInstant="2004-12-05T09:22:05Z">
+     *      <saml:Issuer>https://idp.example.org/SAML2</saml:Issuer>
+     *      <ds:Signature
+     *        xmlns:ds="http://www.w3.org/2000/09/xmldsig#">...</ds:Signature>
+     *      <saml:Subject>
+     *        <saml:NameID
+     *          Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">
+     *          3f7b3dcf-1674-4ecd-92c8-1544f346baf8
+     *        </saml:NameID>
+     *        <saml:SubjectConfirmation
+     *          Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
+     *          <saml:SubjectConfirmationData
+     *            InResponseTo="aaf23196-1773-2113-474a-fe114412ab72"
+     *            Recipient="https://sp.example.com/SAML2/SSO/POST"
+     *            NotOnOrAfter="2004-12-05T09:27:05Z"/>
+     *        </saml:SubjectConfirmation>
+     *      </saml:Subject>
+     *      <saml:Conditions
+     *        NotBefore="2004-12-05T09:17:05Z"
+     *        NotOnOrAfter="2004-12-05T09:27:05Z">
+     *        <saml:AudienceRestriction>
+     *          <saml:Audience>https://sp.example.com/SAML2</saml:Audience>
+     *        </saml:AudienceRestriction>
+     *      </saml:Conditions>
+     *      <saml:AuthnStatement
+     *        AuthnInstant="2004-12-05T09:22:00Z"
+     *        SessionIndex="b07b804c-7c29-ea16-7300-4f3d6f7928ac">
+     *        <saml:AuthnContext>
+     *          <saml:AuthnContextClassRef>
+     *            urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
+     *         </saml:AuthnContextClassRef>
+     *        </saml:AuthnContext>
+     *      </saml:AuthnStatement>
+     *      <saml:AttributeStatement>
+     *        <saml:Attribute
+     *          xmlns:x500="urn:oasis:names:tc:SAML:2.0:profiles:attribute:X500"
+     *          x500:Encoding="LDAP"
+     *          NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
+     *          Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1"
+     *          FriendlyName="eduPersonAffiliation">
+     *          <saml:AttributeValue
+     *            xsi:type="xs:string">member</saml:AttributeValue>
+     *          <saml:AttributeValue
+     *            xsi:type="xs:string">staff</saml:AttributeValue>
+     *        </saml:Attribute>
+     *      </saml:AttributeStatement>
+     *    </saml:Assertion>
+     *
+     *    Reference - en.wikipedia.org/wiki/SAML_2.0#SAML_2.0_Assertions
+     * @param doc The Document which comprises SAML 2 assertion.
+     * @param crypto Crypto properties.
+     * @param data The RST data and other configuration information.
+     * @return OpenSAML representation of an Assertion.
+     * @throws TrustException If an error occurred while creating the Assertion.
+     */
+    protected Assertion buildAssertion(Document doc, Crypto crypto, RahasData data) throws TrustException {
+        //Build the assertion
+        Assertion assertion = SAML2Utils.createAssertion();
+
+        Issuer issuer = SAML2Utils.createIssuer(this.tokenIssuerConfiguration.getIssuerName());
+        assertion.setIssuer(issuer);
+
+        // Validity period
+        DateTime creationDate = new DateTime();
+        DateTime expirationDate = new DateTime(creationDate.getMillis() + tokenIssuerConfiguration.getTtl());
+
+        data.setAssertionCreatedDate(creationDate.toDate());
+        data.setAssertionExpiringDate(expirationDate.toDate());
+
+        // Set the issued time.
+        assertion.setIssueInstant(creationDate);
+
+        // These variables are used to build the trust assertion
+        Conditions conditions = SAML2Utils.createConditions(creationDate, expirationDate);
+        assertion.setConditions(conditions);
+
+        // Create the subject
+        Subject subject;
+
+        if (!data.getKeyType().endsWith(RahasConstants.KEY_TYPE_BEARER)) {
+            subject = createSubjectWithHolderOfKeySubjectConfirmation(doc, crypto,
+                    creationDate, expirationDate, data);
+        } else {
+            subject = createSubjectWithBearerSubjectConfirmation(data);
+        }
+
+        // Set the subject
+        assertion.setSubject(subject);
+
+        // If a SymmetricKey is used build an attr stmt, if a public key is build an authn stmt.
+        if (isSymmetricKeyBasedHoK) {
+            AttributeStatement attrStmt = createAttributeStatement(data);
+            assertion.getAttributeStatements().add(attrStmt);
+        } else {
+            AuthnStatement authStmt = createAuthenticationStatement(data);
+            assertion.getAuthnStatements().add(authStmt);
+            if (data.getClaimDialect() != null && data.getClaimElem() != null) {
+                assertion.getAttributeStatements().add(createAttributeStatement(data));
             }
-
-            keyInfoElem = doc.createElementNS(WSConstants.SIG_NS,
-                    "ds:KeyInfo");
-            ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.SIG_NS,
-                    WSConstants.SIG_PREFIX);
-            ((OMElement) encryptedKeyElem).declareNamespace(WSConstants.ENC_NS,
-                    WSConstants.ENC_PREFIX);
-
-            keyInfoElem.appendChild(encryptedKeyElem);
-
         }
 
-        // If it is a public Key
-        else if(data.getKeyType().endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)){
-            try {
-                String subjectNameId = data.getPrincipal().getName();
-
-                //Create NameID and attach it to the subject
-                NameIDBuilder nb = new NameIDBuilder();
-                NameID nameID = nb.buildObject();
-                nameID.setValue(subjectNameId);
-                nameID.setFormat(NameIdentifier.EMAIL);
-                subject.setNameID(nameID);
-
-
-                // Create the ds:KeyValue element with the ds:X509Data
-                X509Certificate clientCert = data.getClientCert();
-
-                if (clientCert == null) {
-                    // TODO are we always looking up by alias ? Dont we need to lookup by any other attribute ?
-                    clientCert = CommonUtil.getCertificateByAlias(crypto, data.getPrincipal().getName());
-                }
-
-                byte[] clientCertBytes = clientCert.getEncoded();
-
-                String base64Cert = Base64.encode(clientCertBytes);
-
-                Text base64CertText = doc.createTextNode(base64Cert);
-
-                //-----------------------------------------
-
-                Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS,
-                        "ds:X509Certificate");
-                x509CertElem.appendChild(base64CertText);
-                Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS,
-                        "ds:X509Data");
-                x509DataElem.appendChild(x509CertElem);
-
-
-                if (x509DataElem != null) {
-                    keyInfoElem = doc.createElementNS(WSConstants.SIG_NS, "ds:KeyInfo");
-                    ((OMElement) x509DataElem).declareNamespace(
-                            WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
-                    keyInfoElem.appendChild(x509DataElem);
-                }
-
-            } catch (Exception e) {
-                throw new TrustException("samlAssertionCreationError", e);
-            }
-        }
+        return assertion;
+    }
 
-        // Unmarshall the keyInfo DOM element into an XMLObject
-        String keyInfoElementString = keyInfoElem.toString();
-        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
-        documentBuilderFactory.setNamespaceAware(true);
-        DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
-        Document document = docBuilder.parse(new ByteArrayInputStream(keyInfoElementString.trim().getBytes()));
-        Element element = document.getDocumentElement();
+    /**
+     * This method will create a SAML 2 subject based on Holder of Key confirmation method.
+     * The relevant XML would look as follows,
+     * <saml2:Subject>
+     *       <saml2:NameID>
+     *           ...
+     *       </saml2:NameID>
+     *       <saml2:SubjectConfirmation
+     *               Method=”urn:oasis:names:tc:SAML:2.0:cm:holder-of-key”>
+     *           <saml2:SubjectConfirmationData
+     *                   xsi:type="saml2:KeyInfoConfirmationDataType">
+     *               <ds:KeyInfo>
+     *                   <ds:KeyValue>...</ds:KeyValue>
+     *               </ds:KeyInfo>
+     *           </saml2:SubjectConfirmationData>
+     *       </saml2:SubjectConfirmation>
+     *   </saml2:Subject>
+     *
+     * KeyInfo can be created based on public key or symmetric key. That is decided by looking at
+     * the RahasData.getKeyType. TODO make sure this implementation is correct.
+     * Theoretically we should be able to have many subject confirmation methods in a SAML2 subject.
+     * TODO - Do we need to support that ?
+     * @param doc The original XML document which we need to include the assertion.
+     * @param crypto The relevant crypto properties
+     * @param creationTime The time that assertion was created.
+     * @param expirationTime The expiring time
+     * @param data The configuration data relevant request.
+     * @return OpenSAML representation of the SAML2 object.
+     * @throws TrustException If an error occurred while creating the subject.
+     */
+    protected Subject createSubjectWithHolderOfKeySubjectConfirmation(Document doc, Crypto crypto,
+                                                            DateTime creationTime,
+                                                            DateTime expirationTime, RahasData data)
+            throws TrustException {
 
 
-        // Get appropriate unmarshaller
-        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
-        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(element);
+        // Create the subject
+        Subject subject = (Subject)CommonUtil.buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
 
-        // Unmarshall using the document root element, an keyInfo element in this case
-        XMLObject keyInfoElement = null;
-        try {
-            keyInfoElement = unmarshaller.unmarshall(element);
-        } catch (UnmarshallingException e) {
-            throw new TrustException("Error unmarshalling KeyInfo Element", e);
+        // Set the subject name identifier
+        if (data.getPrincipal() != null) {
+            setSubjectNamedIdentifierData(subject, data.getPrincipal().getName(), NameID.EMAIL);
         }
 
+        // Create KeyInfo
+        KeyInfo keyInfo = createKeyInfo(doc, crypto, data);
 
         //Build the Subject Confirmation
-        SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder =
-                (SAMLObjectBuilder<SubjectConfirmation>) builderFactory.getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
-        SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
+        SubjectConfirmation subjectConfirmation
+                = (SubjectConfirmation)CommonUtil.buildXMLObject(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
 
         //Set the subject Confirmation method
         subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:holder-of-key");
 
-        SAMLObjectBuilder<KeyInfoConfirmationDataType> keyInfoSubjectConfirmationDataBuilder =
-                (SAMLObjectBuilder<KeyInfoConfirmationDataType>) builderFactory.getBuilder(KeyInfoConfirmationDataType.TYPE_NAME);
-
         //Build the subject confirmation data element
-        KeyInfoConfirmationDataType scData = keyInfoSubjectConfirmationDataBuilder.
-                buildObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME, KeyInfoConfirmationDataType.TYPE_NAME);
+        KeyInfoConfirmationDataType scData = createKeyInfoConfirmationDataType();
 
         //Set the keyInfo element
-        scData.getKeyInfos().add(keyInfoElement);
+        scData.getKeyInfos().add(keyInfo);
 
         // Set the validity period
         scData.setNotBefore(creationTime);
@@ -495,27 +425,47 @@ public class SAML2TokenIssuer implements
         return subject;
     }
 
+    private KeyInfoConfirmationDataType createKeyInfoConfirmationDataType() {
+        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
+        @SuppressWarnings({"unchecked"}) SAMLObjectBuilder<KeyInfoConfirmationDataType> keyInfoSubjectConfirmationDataBuilder =
+                (SAMLObjectBuilder<KeyInfoConfirmationDataType>) builderFactory.getBuilder
+                        (KeyInfoConfirmationDataType.TYPE_NAME);
+
+        //Build the subject confirmation data element
+        return keyInfoSubjectConfirmationDataBuilder.
+                buildObject(SubjectConfirmationData.DEFAULT_ELEMENT_NAME, KeyInfoConfirmationDataType.TYPE_NAME);
+    }
+
     /**
-     * This method creates a subject element with the bearer subject confirmation method
+     * This method creates a subject element with the bearer subject confirmation method.
+     * <saml:Subject>
+     *       <saml:NameIdentifier
+     *                   NameQualifier="www.example.com"
+     *                   Format=“urn:oasis:names:tc:SAML:1.1:nameid-
+     *           format:X509SubjectName”>
+     *           uid=joe,ou=people,ou=saml-demo,o=baltimore.com
+     *       </saml:NameIdentifier>
+     *       <saml:SubjectConfirmation>
+     *           <saml:ConfirmationMethod>
+     *               urn:oasis:names:tc:SAML:1.0:cm:bearer
+     *           </saml:ConfirmationMethod>
+     *       </saml:SubjectConfirmation>
+     *   </saml:Subject>
      * @param data RahasData element
      * @return  SAML 2.0 Subject element with Bearer subject confirmation
+     * @throws org.apache.rahas.TrustException if an error occurred while creating the subject.
      */
-    private Subject createSubjectWithBearerSC(RahasData data){
-        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
-        SAMLObjectBuilder<Subject> subjectBuilder =
-                (SAMLObjectBuilder<Subject>) builderFactory.getBuilder(Subject.DEFAULT_ELEMENT_NAME);
-        Subject subject = subjectBuilder.buildObject();
+    protected Subject createSubjectWithBearerSubjectConfirmation(RahasData data) throws TrustException {
+
+        // Create the subject
+        Subject subject = (Subject)CommonUtil.buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
 
         //Create NameID and attach it to the subject
-        NameID nameID = new NameIDBuilder().buildObject();
-        nameID.setValue(data.getPrincipal().getName());
-        nameID.setFormat(NameIdentifier.EMAIL);
-        subject.setNameID(nameID);
+        setSubjectNamedIdentifierData(subject, data.getPrincipal().getName(), NameID.EMAIL);
 
         //Build the Subject Confirmation
-        SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder =
-                (SAMLObjectBuilder<SubjectConfirmation>) builderFactory.getBuilder(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
-        SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
+        SubjectConfirmation subjectConfirmation
+                = (SubjectConfirmation)CommonUtil.buildXMLObject(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
 
         //Set the subject Confirmation method
         subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");
@@ -526,39 +476,51 @@ public class SAML2TokenIssuer implements
 
 
     /**
-     * This method is used to sign the assertion
-     * @param assertion
-     * @param cred
-     * @return Assertion
-     * @throws Exception
+     * This method signs the given assertion with issuer's private key.
+     * @param document The original RST document.
+     * @param assertion Assertion to be signed.
+     * @param crypto  The cryptographic properties.
+     * @return The signed assertion.
+     * @throws TrustException If an error occurred while signing the assertion.
      */
-    public Assertion setSignature(Assertion assertion, SignKeyHolder cred) throws Exception {
+    protected Assertion signAssertion(Document document, Assertion assertion, Crypto crypto) throws TrustException {
+
+        // Create a SignKeyHolder to hold the crypto objects that are used to sign the assertion
+        SignKeyHolder signKeyHolder = createSignKeyHolder(crypto);
 
         // Build the signature object and set the credentials.
-        Signature signature = (Signature) buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
-        signature.setSigningCredential(cred);
-        signature.setSignatureAlgorithm(cred.getSignatureAlgorithm());
+        Signature signature = (Signature) CommonUtil.buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
+
+        signature.setSigningCredential(signKeyHolder);
+        signature.setSignatureAlgorithm(signKeyHolder.getSignatureAlgorithm());
         signature.setCanonicalizationAlgorithm(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
 
         //Build the KeyInfo element and set the certificate
         try {
-            KeyInfo keyInfo = (KeyInfo) buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
-            X509Data data = (X509Data) buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
-            org.opensaml.xml.signature.X509Certificate cert = (org.opensaml.xml.signature.X509Certificate) buildXMLObject(org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
-            String value = org.apache.xml.security.utils.Base64.encode(cred.getEntityCertificate().getEncoded());
+            KeyInfo keyInfo = (KeyInfo) CommonUtil.buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
+            X509Data x509Data = (X509Data) CommonUtil.buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
+            org.opensaml.xml.signature.X509Certificate cert
+                    = (org.opensaml.xml.signature.X509Certificate) CommonUtil.buildXMLObject
+                    (org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
+            String value
+                    = org.apache.xml.security.utils.Base64.encode(signKeyHolder.getEntityCertificate().getEncoded());
+
             cert.setValue(value);
-            data.getX509Certificates().add(cert);
-            keyInfo.getX509Datas().add(data);
+            x509Data.getX509Certificates().add(cert);
+            keyInfo.getX509Datas().add(x509Data);
+
             signature.setKeyInfo(keyInfo);
             assertion.setSignature(signature);
+
             signatureList.add(signature);
 
             //Marshall and Sign
             MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
             Marshaller marshaller = marshallerFactory.getMarshaller(assertion);
-            marshaller.marshall(assertion);
-            org.apache.xml.security.Init.init();
+            marshaller.marshall(assertion, document.getDocumentElement());
+
             Signer.signObjects(signatureList);
+
         } catch (CertificateEncodingException e) {
             throw new TrustException("Error in setting the signature", e);
         } catch (SignatureException e) {
@@ -572,45 +534,30 @@ public class SAML2TokenIssuer implements
         return assertion;
     }
 
-
-    /**
-     * This method is used to build the assertion elements
-     * @param objectQName
-     * @return
-     * @throws Exception
-     */
-    protected static XMLObject buildXMLObject(QName objectQName) throws Exception {
-        XMLObjectBuilder builder = org.opensaml.xml.Configuration.getBuilderFactory().getBuilder(objectQName);
-        if (builder == null) {
-            throw new TrustException("Unable to retrieve builder for object QName "
-                    + objectQName);
-        }
-        return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(),
-                objectQName.getPrefix());
-    }
-
     /**
      * This method is used to create SignKeyHolder instances that contains the credentials required for signing the
      * assertion
-     * @param config
-     * @param crypto
-     * @return
-     * @throws TrustException
+     * @param crypto The crypto properties associated with the issuer.
+     * @return  SignKeyHolder object.
+     * @throws TrustException  If an error occurred while creating SignKeyHolder object.
      */
-    private SignKeyHolder createSignKeyHolder(SAMLTokenIssuerConfig config, Crypto crypto) throws TrustException {
+    private SignKeyHolder createSignKeyHolder(Crypto crypto) throws TrustException {
 
         SignKeyHolder signKeyHolder = new SignKeyHolder();
 
         try {
-            X509Certificate[] issuerCerts = CommonUtil.getCertificatesByAlias(crypto,config.getIssuerKeyAlias());
+            X509Certificate[] issuerCerts = CommonUtil.getCertificatesByAlias(crypto,
+                    this.tokenIssuerConfiguration.getIssuerKeyAlias());
 
             String sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA;
             String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
             if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
                 sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
             }
+
             java.security.Key issuerPK = crypto.getPrivateKey(
-                    config.getIssuerKeyAlias(), config.getIssuerKeyPassword());
+                    this.tokenIssuerConfiguration.getIssuerKeyAlias(),
+                    this.tokenIssuerConfiguration.getIssuerKeyPassword());
 
             signKeyHolder.setIssuerCerts(issuerCerts);
             signKeyHolder.setIssuerPK((PrivateKey) issuerPK);
@@ -626,62 +573,57 @@ public class SAML2TokenIssuer implements
     }
 
     /**
-     * Creates the Attribute Statement
-     * @param data
-     * @param config
-     * @return
-     * @throws SAMLException
+     * This method creates an AttributeStatement. The relevant XML would look like as follows,
+     * <saml:AttributeStatement>
+     *    <saml:Attribute
+     *      xmlns:x500="urn:oasis:names:tc:SAML:2.0:profiles:attribute:X500"
+     *      x500:Encoding="LDAP"
+     *      NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
+     *      Name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1"
+     *      FriendlyName="eduPersonAffiliation">
+     *      <saml:AttributeValue
+     *        xsi:type="xs:string">member</saml:AttributeValue>
+     *      <saml:AttributeValue
+     *        xsi:type="xs:string">staff</saml:AttributeValue>
+     *    </saml:Attribute>
+     *  </saml:AttributeStatement>
+     *  Reference -  http://en.wikipedia.org/wiki/SAML_2.0#SAML_2.0_Assertions
+     * @param data The RahasData which carry information about RST.
+     * @return An AttributeStatement with filled attributes retrieved by calling callback class.
+     * @throws TrustException If an error occurred while creating the AttributeStatement.
      */
-    private AttributeStatement createAttributeStatement(RahasData data, SAMLTokenIssuerConfig config) throws SAMLException, TrustException {
+    protected AttributeStatement createAttributeStatement(RahasData data) throws TrustException {
 
-        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
-        SAMLObjectBuilder<AttributeStatement> attrStmtBuilder =
-                (SAMLObjectBuilder<AttributeStatement>) builderFactory.getBuilder(AttributeStatement.DEFAULT_ELEMENT_NAME);
 
-        SAMLObjectBuilder<Attribute> attrBuilder =
-                    (SAMLObjectBuilder<Attribute>) builderFactory.getBuilder(Attribute.DEFAULT_ELEMENT_NAME);
+        AttributeStatement attributeStatement
+                = (AttributeStatement) CommonUtil.buildXMLObject(AttributeStatement.DEFAULT_ELEMENT_NAME);
 
-        AttributeStatement attrstmt = attrStmtBuilder.buildObject();
+        Attribute[] attributes;
 
-        Attribute[] attributes = null;
+        SAMLCallbackHandler handler = CommonUtil.getSAMLCallbackHandler(this.tokenIssuerConfiguration, data);
 
-        //Call the attribute callback handlers to get any attributes if exists
-        if (config.getCallbackHandler() != null) {
-            SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
-            SAMLCallbackHandler handler = config.getCallbackHandler();
-            handler.handle(cb);
-            attributes = cb.getSAML2Attributes();
-        }
-        else if (config.getCallbackHandlerName() != null
-                && config.getCallbackHandlerName().trim().length() > 0) {
-            SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
-            SAMLCallbackHandler handler = null;
-            MessageContext msgContext = data.getInMessageContext();
-            ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
-            Class cbClass = null;
+        SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
+        if (handler != null) {
             try {
-                cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
-            } catch (ClassNotFoundException e) {
-                throw new TrustException("cannotLoadPWCBClass", new String[]{config
-                        .getCallbackHandlerName()}, e);
-            }
-            try {
-                handler = (SAMLCallbackHandler) cbClass.newInstance();
-            } catch (java.lang.Exception e) {
-                throw new TrustException("cannotCreatePWCBInstance", new String[]{config
-                        .getCallbackHandlerName()}, e);
+                handler.handle(cb);
+            } catch (SAMLException e) {
+                throw new TrustException(
+                            "errorCallingSAMLCallback",
+                            e);
             }
-            handler.handle(cb);
+
             attributes = cb.getSAML2Attributes();
-            // else add the attribute with a default value
-        } 
+        } else { //else add the attribute with a default value
+
+            log.debug("No callback registered to get attributes ... Using default attributes");
 
-        //else add the attribute with a default value
-        else {
-            Attribute attribute = attrBuilder.buildObject();
+            // TODO do we need to remove this ?
+            Attribute attribute = (Attribute) CommonUtil.buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
             attribute.setName("Name");
             attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified");
 
+            XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
+
             XSStringBuilder attributeValueBuilder = (XSStringBuilder) builderFactory
                     .getBuilder(XSString.TYPE_NAME);
 
@@ -693,69 +635,172 @@ public class SAML2TokenIssuer implements
             attributes[0] = attribute;
         }
         //add attributes to the attribute statement
-        attrstmt.getAttributes().addAll(Arrays.asList(attributes));
+        attributeStatement.getAttributes().addAll(Arrays.asList(attributes));
 
         log.debug("SAML2.0 attribute statement is constructed successfully.");
 
-        return attrstmt;
+        return attributeStatement;
     }
 
     /**
-     * build the authentication statement
-     * @param data
-     * @return
+     * This method creates an authentication statement. The equivalent XML would look as follows,
+     * <saml:AuthnStatement
+     *    AuthnInstant="2004-12-05T09:22:00Z"
+     *    SessionIndex="b07b804c-7c29-ea16-7300-4f3d6f7928ac">
+     *    <saml:AuthnContext>
+     *      <saml:AuthnContextClassRef>
+     *        urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport
+     *     </saml:AuthnContextClassRef>
+     *    </saml:AuthnContext>
+     *  </saml:AuthnStatement>
+     * @param data The RahasData which carry information about RST.
+     * @return OpenSAML representation of an AuthnStatement class.
+     * @throws TrustException If an error occurred while creating the authentication statement.
      */
-    private AuthnStatement createAuthnStatement(RahasData data) {
-        XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
-        MessageContext inMsgCtx = data.getInMessageContext();
+    protected AuthnStatement createAuthenticationStatement(RahasData data) throws TrustException {
 
-        SAMLObjectBuilder<AuthnStatement> authStmtBuilder =
-                (SAMLObjectBuilder<AuthnStatement>) builderFactory.getBuilder(AuthnStatement.DEFAULT_ELEMENT_NAME);
+        MessageContext inMsgCtx = data.getInMessageContext();
 
         //build the auth stmt
-        AuthnStatement authStmt = authStmtBuilder.buildObject();
+        AuthnStatement authenticationStatement
+                = (AuthnStatement)CommonUtil.buildXMLObject(AuthnStatement.DEFAULT_ELEMENT_NAME);
 
         // set the authn instance
-        authStmt.setAuthnInstant(new DateTime());
+        // TODO do we need to use the same time as specified in the conditions ?
+        authenticationStatement.setAuthnInstant(new DateTime());
 
-        SAMLObjectBuilder<AuthnContext> authCtxBuilder =
-                (SAMLObjectBuilder<AuthnContext>) builderFactory.getBuilder(AuthnContext.DEFAULT_ELEMENT_NAME);
-        AuthnContext authContext = authCtxBuilder.buildObject();
-
-        SAMLObjectBuilder<AuthnContextClassRef> authCtxClassRefBuilder =
-                (SAMLObjectBuilder<AuthnContextClassRef>) builderFactory.getBuilder(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
-        AuthnContextClassRef authCtxClassRef = authCtxClassRefBuilder.buildObject();
+        // Create authentication context
+        AuthnContext authContext = (AuthnContext)CommonUtil.buildXMLObject(AuthnContext.DEFAULT_ELEMENT_NAME);
+
+        // Create authentication context class reference
+        AuthnContextClassRef authCtxClassRef
+                = (AuthnContextClassRef)CommonUtil.buildXMLObject(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
         
         //if username/password based authn
         if (inMsgCtx.getProperty(RahasConstants.USERNAME) != null) {
             authCtxClassRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX);
-        }
-        //if X.509 cert based authn
-        else if (inMsgCtx.getProperty(RahasConstants.X509_CERT) != null) {
+        } else if (inMsgCtx.getProperty(RahasConstants.X509_CERT) != null) { //if X.509 cert based authn
             authCtxClassRef.setAuthnContextClassRef(AuthnContext.X509_AUTHN_CTX);
         }
 
         authContext.setAuthnContextClassRef(authCtxClassRef);
-        authStmt.setAuthnContext(authContext);
+        authenticationStatement.setAuthnContext(authContext);
 
         log.debug("SAML2.0 authentication statement is constructed successfully.");
 
-        return authStmt;
+        return authenticationStatement;
     }
 
+    /**
+     * This method will set the subject principal details to the given subject.
+     * @param subject The subject.
+     * @param subjectNameId Subject name id, to identify the principal
+     * @param format Format of the subjectNameId, i.e. email, x509subject etc ...
+     * @throws TrustException If an error occurred while building NameID.
+     */
+    protected static void setSubjectNamedIdentifierData(Subject subject, String subjectNameId, String format)
+            throws TrustException {
 
+        //Create NameID and attach it to the subject
+        NameID nameID = SAML2Utils.createNamedIdentifier(subjectNameId, format);
+        subject.setNameID(nameID);
+    }
+
+    /**
+     * This method creates the KeyInfo relevant for the assertion. The KeyInfo could be created in 2 ways.
+     * 1. Using symmetric key - KeyInfo is created using a symmetric key
+     * 2. Using a public key - KeyInfo created using a public key
+     * The methodology is decided by looking at RahasData.getKeyType() method.
+     * @param doc The document which we are processing.
+     * @param crypto Includes crypto properties relevant to issuer.
+     * @param data Includes metadata about the RST.
+     * @return OpenSAML representation of KeyInfo.
+     * @throws TrustException If an error occurred while creating the KeyInfo object.
+     */
+    protected KeyInfo createKeyInfo(Document doc, Crypto crypto, RahasData data)
+            throws TrustException {
+
+        KeyInfo keyInfo;
+
+        // If it is a Symmetric Key
+        if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
+
+            isSymmetricKeyBasedHoK = true;
+            X509Certificate serviceCert = null;
+            try {
+
+                // Get AppliesTo to figure out which service to issue the token
+                // for
+                serviceCert = this.tokenIssuerConfiguration.getServiceCert(crypto, data.getAppliesToAddress());
+
+                keyInfo = CommonUtil.getSymmetricKeyBasedKeyInfo(doc, data, serviceCert, data.getKeySize(), crypto,
+                        tokenIssuerConfiguration.getKeyComputation());
+
+            } catch (Exception e) {
+                if (serviceCert != null) {
+                    throw new TrustException(
+                            "errorInBuildingTheEncryptedKeyForPrincipal",
+                            new String[]{serviceCert.getSubjectDN().getName()},
+                            e);
+                } else {
+                    throw new TrustException(
+                            "errorInBuildingTheEncryptedKeyForPrincipal",
+                            new String[]{"UnknownSubjectDN"},
+                            e);
+                }
+            }
+
+        } else if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) {    // If it is a public Key
+
+            try {
+                // Create the ds:KeyValue element with the ds:X509Data
+                X509Certificate clientCert = data.getClientCert();
+
+                if (clientCert == null) {
+                    // TODO are we always looking up by alias ? Dont we need to lookup by any other attribute ?
+                    clientCert = CommonUtil.getCertificateByAlias(crypto, data.getPrincipal().getName());
+                }
+
+                keyInfo = CommonUtil.getCertificateBasedKeyInfo(clientCert);
+
+            } catch (Exception e) {
+                throw new TrustException("samlAssertionCreationError", e);
+            }
+        } else {
+            log.error("Unidentified key type " + data.getKeyType());
+            throw new TrustException(
+                            "unidentifiedKeyType",
+                            new String[]{data.getKeyType()});
+        }
+
+        return keyInfo;
+
+    }
+
+    /**
+     * @inheritDoc
+     */
     public String getResponseAction(RahasData data) throws TrustException {
         return null;
     }
 
+    /**
+     * @inheritDoc
+     */
     public void setConfigurationFile(String configFile) {
         this.configFile = configFile;
     }
 
+    /**
+     * @inheritDoc
+     */
     public void setConfigurationElement(OMElement configElement) {
         this.configElement = configElement;
     }
 
+    /**
+     * @inheritDoc
+     */
     public void setConfigurationParamName(String configParamName) {
         this.configParamName = configParamName;
     }

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java Thu Mar  8 08:11:32 2012
@@ -283,7 +283,7 @@ public class SAMLTokenIssuer implements 
 
                 // Create the encrypted key
                 KeyInfo encryptedKeyInfoElement
-                        = SAMLUtils.getSymmetricKeyBasedKeyInfo(doc, data, serviceCert, keySize,
+                        = CommonUtil.getSymmetricKeyBasedKeyInfo(doc, data, serviceCert, keySize,
                         crypto, config.getKeyComputation());
 
                 return this.createAttributeAssertion(data, encryptedKeyInfoElement, nameIdentifier, config,
@@ -331,7 +331,7 @@ public class SAMLTokenIssuer implements 
                     clientCert = CommonUtil.getCertificateByAlias(crypto,data.getPrincipal().getName());;
                 }
 
-                KeyInfo keyInfo = SAMLUtils.getCertificateBasedKeyInfo(clientCert);
+                KeyInfo keyInfo = CommonUtil.getCertificateBasedKeyInfo(clientCert);
 
                 return this.createAuthAssertion(RahasConstants.SAML11_SUBJECT_CONFIRMATION_HOK, nameId, keyInfo,
                         config, crypto, creationTime, expirationTime, data);
@@ -393,41 +393,22 @@ public class SAMLTokenIssuer implements 
             Subject subject
                     = SAMLUtils.createSubject(subjectNameId, RahasConstants.SAML11_SUBJECT_CONFIRMATION_HOK, keyInfo);
 
-            Attribute[] attrs;
-            if (config.getCallbackHandler() != null) {
-                SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
-                SAMLCallbackHandler handler = config.getCallbackHandler();
-                handler.handle(cb);
-                attrs = cb.getAttributes();
-            } else if (config.getCallbackHandlerName() != null
-                    && config.getCallbackHandlerName().trim().length() > 0) {
-                SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
-                SAMLCallbackHandler handler = null;
-                MessageContext msgContext = data.getInMessageContext();
-                ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
-                Class cbClass;
-                try {
-                    cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
-                } catch (ClassNotFoundException e) {
-                    throw new TrustException("cannotLoadPWCBClass", new String[]{config
-                            .getCallbackHandlerName()}, e);
-                }
-                try {
-                    handler = (SAMLCallbackHandler) cbClass.newInstance();
-                } catch (java.lang.Exception e) {
-                    throw new TrustException("cannotCreatePWCBInstance", new String[]{config
-                            .getCallbackHandlerName()}, e);
-                }
+            Attribute[] attributes;
+
+            SAMLCallbackHandler handler = CommonUtil.getSAMLCallbackHandler(config, data);
+
+            SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
+            if (handler != null) {
                 handler.handle(cb);
-                attrs = cb.getAttributes();
+                attributes = cb.getAttributes();
             } else {
                 //TODO Remove this after discussing
                 Attribute attribute = SAMLUtils.createAttribute("Name", "https://rahas.apache.org/saml/attrns",
                         "Colombo/Rahas");
-                attrs = new Attribute[]{attribute};
+                attributes = new Attribute[]{attribute};
             }
 
-            AttributeStatement attributeStatement = SAMLUtils.createAttributeStatement(subject, Arrays.asList(attrs));
+            AttributeStatement attributeStatement = SAMLUtils.createAttributeStatement(subject, Arrays.asList(attributes));
 
 
             List<Statement> attributeStatements = new ArrayList<Statement>();

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java Thu Mar  8 08:11:32 2012
@@ -462,14 +462,24 @@ public class SAMLTokenIssuerConfig exten
         if (serviceAddress != null && !"".equals(serviceAddress)) {
             String alias = (String) this.trustedServices.get(serviceAddress);
             if (alias != null) {
-                return CommonUtil.getCertificateByAlias(crypto,alias);
+                return CommonUtil.getCertificateByAlias(crypto, alias);
             } else {
                 alias = (String) this.trustedServices.get("*");
-                return CommonUtil.getCertificateByAlias(crypto,alias);
+
+                if (alias == null) {
+                    throw new TrustException("aliasMissingForService", new String[]{serviceAddress});
+                }
+
+                return CommonUtil.getCertificateByAlias(crypto, alias);
             }
         } else {
             String alias = (String) this.trustedServices.get("*");
-            return CommonUtil.getCertificateByAlias(crypto,alias);
+
+            if (alias == null) {
+                throw new TrustException("aliasMissingForService", new String[]{serviceAddress});
+            }
+
+            return CommonUtil.getCertificateByAlias(crypto, alias);
         }
 
     }

Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java Thu Mar  8 08:11:32 2012
@@ -15,6 +15,7 @@ import org.apache.rahas.TokenRenewer;
 import org.apache.rahas.TokenStorage;
 import org.apache.rahas.TrustException;
 import org.apache.rahas.TrustUtil;
+import org.apache.rahas.impl.util.CommonUtil;
 import org.apache.rahas.impl.util.SAMLUtils;
 import org.apache.ws.security.components.crypto.Crypto;
 import org.apache.ws.security.util.XmlSchemaDateFormat;
@@ -115,7 +116,7 @@ public class SAMLTokenRenewer implements
         samlAssertion = SAMLUtils.buildAssertion((Element) assertionOMElement);
 
         if (samlAssertion.getConditions() == null) {
-            samlAssertion.setConditions((Conditions) SAMLUtils.buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME));
+            samlAssertion.setConditions((Conditions) CommonUtil.buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME));
 
         }