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 [2/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...
Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java Thu Mar 8 08:11:32 2012
@@ -23,26 +23,36 @@ import org.apache.axis2.context.MessageC
import org.apache.axis2.description.Parameter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.rahas.RahasData;
import org.apache.rahas.TrustException;
-import org.apache.rahas.TrustUtil;
import org.apache.rahas.impl.SAMLTokenIssuerConfig;
-import org.apache.ws.security.WSDocInfo;
-import org.apache.ws.security.WSSConfig;
-import org.apache.ws.security.WSSecurityEngineResult;
-import org.apache.ws.security.WSSecurityException;
+import org.apache.rahas.impl.TokenIssuerUtil;
+import org.apache.ws.security.*;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoFactory;
import org.apache.ws.security.components.crypto.CryptoType;
import org.apache.ws.security.handler.RequestData;
+import org.apache.ws.security.message.WSSecEncryptedKey;
import org.apache.ws.security.processor.EncryptedKeyProcessor;
+import org.apache.ws.security.util.Base64;
+import org.apache.ws.security.util.Loader;
+import org.apache.xml.security.utils.EncryptionConstants;
+import org.opensaml.Configuration;
+import org.opensaml.xml.XMLObject;
+import org.opensaml.xml.XMLObjectBuilder;
+import org.opensaml.xml.encryption.EncryptedKey;
+import org.opensaml.xml.signature.KeyInfo;
+import org.opensaml.xml.signature.X509Data;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.security.auth.callback.CallbackHandler;
+import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
+import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Properties;
@@ -130,8 +140,6 @@ public class CommonUtil {
public static byte[] getDecryptedBytes(CallbackHandler callbackHandler, Crypto crypto, Node encryptedKeyElement)
throws WSSecurityException {
- // TODO make this code more efficient and reader friendly
-
EncryptedKeyProcessor encryptedKeyProcessor = new EncryptedKeyProcessor();
RequestData requestData = new RequestData();
@@ -143,8 +151,7 @@ public class CommonUtil {
WSDocInfo docInfo = new WSDocInfo(encryptedKeyElement.getOwnerDocument());
- List<WSSecurityEngineResult> resultList
- = null;
+ List<WSSecurityEngineResult> resultList;
resultList = encryptedKeyProcessor.handleToken((Element) encryptedKeyElement, requestData, docInfo);
@@ -295,4 +302,176 @@ public class CommonUtil {
return null;
}
+
+ /**
+ * Builds the requested XMLObject.
+ *
+ * @param objectQName name of the XMLObject
+ * @return the build XMLObject
+ * @throws org.apache.rahas.TrustException If unable to find the appropriate builder.
+ */
+ public static XMLObject buildXMLObject(QName objectQName) throws TrustException {
+ XMLObjectBuilder builder = Configuration.getBuilderFactory().getBuilder(objectQName);
+ if (builder == null) {
+ log.debug("Unable to find OpenSAML builder for object " + objectQName);
+ throw new TrustException("builderNotFound",new Object[]{objectQName});
+ }
+ return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(), objectQName.getPrefix());
+ }
+
+ /**
+ * This method creates KeyInfo element of an assertion. This is a facade, in which it calls
+ * to other helper methods to create KeyInfo. The TokenIssuer will call this method to
+ * create the KeyInfo.
+ * @param doc An Axiom based DOM Document.
+ * @param data The ephemeral key which we use here need in encrypting the message also. Therefore
+ * we need to save the ephemeral key in RahasData passed here.
+ * @param serviceCert Public key used to encrypt the assertion is extracted from this certificate.
+ * @param keySize Size of the key to be used
+ * @param crypto The relevant private key
+ * @param keyComputation Key computation mechanism.
+ * @return OpenSAML KeyInfo representation.
+ * @throws WSSecurityException We use WSS4J to generate encrypted key. This exception will trigger if an
+ * error occurs while generating the encrypted key.
+ * @throws TrustException If an error occurred while creating KeyInfo object.
+ */
+ public static KeyInfo getSymmetricKeyBasedKeyInfo(Document doc,
+ RahasData data,
+ X509Certificate serviceCert,
+ int keySize,
+ Crypto crypto,
+ int keyComputation) throws WSSecurityException, TrustException {
+
+ byte[] ephemeralKey = TokenIssuerUtil.getSharedSecret(
+ data, keyComputation, keySize);
+
+ WSSecEncryptedKey encryptedKey = getSymmetricKeyBasedKeyInfoContent(doc, ephemeralKey, serviceCert, crypto);
+
+ // Extract the base64 encoded secret value
+ byte[] tempKey = new byte[keySize / 8];
+ System.arraycopy(encryptedKey.getEphemeralKey(), 0, tempKey,
+ 0, keySize / 8);
+
+
+ data.setEphmeralKey(tempKey);
+
+ EncryptedKey samlEncryptedKey = SAMLUtils.createEncryptedKey(serviceCert, encryptedKey);
+ return SAMLUtils.createKeyInfo(samlEncryptedKey);
+ }
+
+ static WSSecEncryptedKey getSymmetricKeyBasedKeyInfoContent(Document doc,
+ byte[] ephemeralKey,
+ X509Certificate serviceCert,
+ Crypto crypto) throws WSSecurityException,
+ TrustException {
+ // Create the encrypted key
+ WSSecEncryptedKey encryptedKeyBuilder = new WSSecEncryptedKey();
+
+ // Use thumbprint id
+ encryptedKeyBuilder
+ .setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+
+ // SEt the encryption cert
+ encryptedKeyBuilder.setUseThisCert(serviceCert);
+
+ encryptedKeyBuilder.setEphemeralKey(ephemeralKey);
+
+ // Set key encryption algo
+ encryptedKeyBuilder
+ .setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
+
+ // Build
+ encryptedKeyBuilder.prepare(doc, crypto);
+
+ return encryptedKeyBuilder;
+ }
+
+ /**
+ * Creates the certificate based KeyInfo object.
+ * @param certificate The public key certificate used to create the KeyInfo object.
+ * @return OpenSAML representation of KeyInfo object.
+ * @throws TrustException If an error occurred while creating the KeyInfo
+ */
+ public static KeyInfo getCertificateBasedKeyInfo(X509Certificate certificate) throws TrustException {
+ X509Data x509Data = CommonUtil.createX509Data(certificate);
+ return SAMLUtils.createKeyInfo(x509Data);
+ }
+
+ /**
+ * Creates the X509 data element in a SAML issuer token. Should create an element similar to following,
+ * <X509Data xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
+ * xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
+ * <X509Certificate>
+ * MIICNTCCAZ6gAwIB...
+ * </X509Certificate>
+ * </X509Data>
+ * @param clientCert Client certificate to be used when generating X509 data
+ * @return SAML X509Data representation.
+ * @throws TrustException If an error occurred while creating X509Data and X509Certificate.
+ */
+ static X509Data createX509Data(X509Certificate clientCert) throws TrustException {
+
+ byte[] clientCertBytes;
+ try {
+ clientCertBytes = clientCert.getEncoded();
+ } catch (CertificateEncodingException e) {
+ log.error("An error occurred while encoding certificate.", e);
+ throw new TrustException("An error occurred while encoding certificate.", e);
+ }
+ String base64Cert = Base64.encode(clientCertBytes);
+
+ org.opensaml.xml.signature.X509Certificate x509Certificate
+ = (org.opensaml.xml.signature.X509Certificate)CommonUtil.buildXMLObject
+ (org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
+
+ x509Certificate.setValue(base64Cert);
+
+ X509Data x509Data = (X509Data)CommonUtil.buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
+ x509Data.getX509Certificates().add(x509Certificate);
+
+ return x509Data;
+ }
+
+ /**
+ * Gets the SAML callback handler. First checks whether there is a registered callback handler in token
+ * issuer configuration. If not this will check whether there is a callback class configured in token issuer
+ * configuration. If class name is specified this method will create an object of the class and will return.
+ * If class name is also not specified this method will return null.
+ * @param tokenIssuerConfiguration The SAML token issuer configuration.
+ * @param data The RahasData.
+ * @return The SAMLCallbackHandler if configured in token issuer configuration, else null.
+ * @throws TrustException If an error occurred while loading class from class loader
+ */
+ public static SAMLCallbackHandler getSAMLCallbackHandler(SAMLTokenIssuerConfig tokenIssuerConfiguration,
+ RahasData data) throws TrustException {
+ if (tokenIssuerConfiguration.getCallbackHandler() != null) {
+
+ return tokenIssuerConfiguration.getCallbackHandler();
+
+ } else if (tokenIssuerConfiguration.getCallbackHandlerName() != null
+ && tokenIssuerConfiguration.getCallbackHandlerName().trim().length() > 0) {
+
+ SAMLCallbackHandler handler;
+ MessageContext msgContext = data.getInMessageContext();
+ ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
+ Class cbClass;
+ try {
+ cbClass = Loader.loadClass(classLoader, tokenIssuerConfiguration.getCallbackHandlerName());
+ } catch (ClassNotFoundException e) {
+ throw new TrustException("cannotLoadPWCBClass", new String[]{tokenIssuerConfiguration
+ .getCallbackHandlerName()}, e);
+ }
+ try {
+ handler = (SAMLCallbackHandler) cbClass.newInstance();
+ } catch (java.lang.Exception e) {
+ throw new TrustException("cannotCreatePWCBInstance", new String[]{tokenIssuerConfiguration
+ .getCallbackHandlerName()}, e);
+ }
+
+ return handler;
+ }
+
+ return null;
+
+ }
}
Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java Thu Mar 8 08:11:32 2012
@@ -26,12 +26,16 @@ import org.apache.rahas.TrustException;
import org.apache.ws.security.*;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.util.Base64;
+import org.apache.ws.security.util.UUIDGenerator;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.keys.content.X509Data;
import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
+import org.joda.time.DateTime;
import org.opensaml.Configuration;
import org.opensaml.DefaultBootstrap;
+import org.opensaml.common.SAMLVersion;
+import org.opensaml.saml2.core.NameID;
import org.opensaml.saml2.core.*;
import org.opensaml.xml.ConfigurationException;
import org.opensaml.xml.XMLObject;
@@ -93,16 +97,18 @@ public class SAML2Utils {
}
}
- /**
+ /**
* Extract certificates or the key available in the SAMLAssertion
*
- * @param elem
+ * @param elem The element to process.
+ * @param crypto The crypto properties.
+ * @param cb Callback class to get the Key
* @return the SAML2 Key Info
- * @throws org.apache.ws.security.WSSecurityException
+ * @throws org.apache.ws.security.WSSecurityException If an error occurred while extracting KeyInfo.
*
*/
public static SAML2KeyInfo getSAML2KeyInfo(Element elem, Crypto crypto,
- CallbackHandler cb) throws WSSecurityException, TrustException {
+ CallbackHandler cb) throws WSSecurityException {
Assertion assertion;
//build the assertion by unmarhalling the DOM element.
@@ -294,6 +300,58 @@ public class SAML2Utils {
return subjectConfirmationMethod;
}
+
+ public static Assertion createAssertion() throws TrustException {
+ try {
+ Assertion assertion = (Assertion)CommonUtil.buildXMLObject(Assertion.DEFAULT_ELEMENT_NAME);
+ assertion.setVersion(SAMLVersion.VERSION_20);
+
+ // Set an UUID as the ID of an assertion
+ assertion.setID(UUIDGenerator.getUUID());
+ return assertion;
+ } catch (TrustException e) {
+ throw new TrustException("Unable to create an Assertion object", e);
+ }
+ }
+
+ public static Issuer createIssuer(String issuerName) throws TrustException {
+ try {
+ Issuer issuer = (Issuer)CommonUtil.buildXMLObject(Issuer.DEFAULT_ELEMENT_NAME);
+ issuer.setValue(issuerName);
+ return issuer;
+ } catch (TrustException e) {
+ throw new TrustException("Unable to create an Issuer object", e);
+ }
+ }
+
+ public static Conditions createConditions(DateTime creationTime, DateTime expirationTime) throws TrustException {
+ try {
+ Conditions conditions = (Conditions)CommonUtil.buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME);
+ conditions.setNotBefore(creationTime);
+ conditions.setNotOnOrAfter(expirationTime);
+ return conditions;
+ } catch (TrustException e) {
+ throw new TrustException("Unable to create an Conditions object");
+ }
+ }
+
+/**
+ * Create named identifier.
+ * @param principalName Name of the subject.
+ * @param format Format of the subject, whether it is an email, uid etc ...
+ * @return The NamedIdentifier object.
+ * @throws org.apache.rahas.TrustException If unable to find the builder.
+ */
+ public static NameID createNamedIdentifier(String principalName, String format) throws TrustException{
+
+ NameID nameId = (NameID)CommonUtil.buildXMLObject(NameID.DEFAULT_ELEMENT_NAME);
+ nameId.setValue(principalName);
+ nameId.setFormat(format);
+
+ return nameId;
+ }
+
+
}
Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java Thu Mar 8 08:11:32 2012
@@ -3,11 +3,7 @@ package org.apache.rahas.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.RahasConstants;
-import org.apache.rahas.RahasData;
import org.apache.rahas.TrustException;
-import org.apache.rahas.impl.TokenIssuerUtil;
-import org.apache.ws.security.WSConstants;
-import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.message.WSSecEncryptedKey;
import org.apache.ws.security.util.Base64;
@@ -19,8 +15,6 @@ import org.opensaml.saml1.core.*;
import org.opensaml.ws.wssecurity.KeyIdentifier;
import org.opensaml.ws.wssecurity.SecurityTokenReference;
import org.opensaml.ws.wssecurity.WSSecurityConstants;
-import org.opensaml.xml.XMLObject;
-import org.opensaml.xml.XMLObjectBuilder;
import org.opensaml.xml.encryption.CipherData;
import org.opensaml.xml.encryption.CipherValue;
import org.opensaml.xml.encryption.EncryptedKey;
@@ -36,7 +30,6 @@ import org.opensaml.xml.signature.X509Da
import org.w3c.dom.Document;
import org.w3c.dom.Element;
-import javax.xml.namespace.QName;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
@@ -53,6 +46,7 @@ public class SAMLUtils {
private static final Log log = LogFactory.getLog(SAMLUtils.class);
+ @SuppressWarnings({"UnusedDeclaration"})
public static Collection<X509Certificate> getCertChainCollection(X509Certificate[] issuerCerts) {
ArrayList<X509Certificate> certCollection = new ArrayList<X509Certificate>();
@@ -66,22 +60,6 @@ public class SAMLUtils {
}
/**
- * Builds the requested XMLObject.
- *
- * @param objectQName name of the XMLObject
- * @return the build XMLObject
- * @throws org.apache.rahas.TrustException If unable to find the appropriate builder.
- */
- public static XMLObject buildXMLObject(QName objectQName) throws TrustException {
- XMLObjectBuilder builder = Configuration.getBuilderFactory().getBuilder(objectQName);
- if (builder == null) {
- log.debug("Unable to find OpenSAML builder for object " + objectQName);
- throw new TrustException("builderNotFound",new Object[]{objectQName});
- }
- return builder.buildObject(objectQName.getNamespaceURI(), objectQName.getLocalPart(), objectQName.getPrefix());
- }
-
- /**
* Builds an assertion from an XML element.
* @param assertionElement The XML element.
* @return An Assertion object.
@@ -136,12 +114,12 @@ public class SAMLUtils {
Credential signingCredential = SecurityHelper.getSimpleCredential(issuerPublicKey, issuerPrivateKey);
- Signature signature = (Signature) SAMLUtils.buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
+ Signature signature = (Signature) CommonUtil.buildXMLObject(Signature.DEFAULT_ELEMENT_NAME);
signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
signature.setSigningCredential(signingCredential);
signature.setSignatureAlgorithm(signatureAlgorithm);
- X509Data x509Data = createX509Data(issuerCerts);
+ X509Data x509Data = CommonUtil.createX509Data(issuerCerts);
KeyInfo keyInfo = createKeyInfo(x509Data);
signature.setKeyInfo(keyInfo);
@@ -199,7 +177,7 @@ public class SAMLUtils {
return subjectConfirmationMethod;
}
- /**
+ /**
* Create named identifier.
* @param principalName Name of the subject.
* @param format Format of the subject, whether it is an email, uid etc ...
@@ -208,7 +186,7 @@ public class SAMLUtils {
*/
public static NameIdentifier createNamedIdentifier(String principalName, String format) throws TrustException{
- NameIdentifier nameId = (NameIdentifier)SAMLUtils.buildXMLObject(NameIdentifier.DEFAULT_ELEMENT_NAME);
+ NameIdentifier nameId = (NameIdentifier)CommonUtil.buildXMLObject(NameIdentifier.DEFAULT_ELEMENT_NAME);
nameId.setNameIdentifier(principalName);
nameId.setFormat(format);
@@ -232,7 +210,7 @@ public class SAMLUtils {
throws TrustException {
ConfirmationMethod confirmationMethodObject
- = (ConfirmationMethod)SAMLUtils.buildXMLObject(ConfirmationMethod.DEFAULT_ELEMENT_NAME);
+ = (ConfirmationMethod)CommonUtil.buildXMLObject(ConfirmationMethod.DEFAULT_ELEMENT_NAME);
confirmationMethodObject.setConfirmationMethod(confirmationMethod);
return confirmationMethodObject;
@@ -254,7 +232,7 @@ public class SAMLUtils {
KeyInfo keyInfoContent) throws TrustException {
SubjectConfirmation subjectConfirmation
- = (SubjectConfirmation)SAMLUtils.buildXMLObject(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
+ = (SubjectConfirmation)CommonUtil.buildXMLObject(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
ConfirmationMethod method = SAMLUtils.createSubjectConfirmationMethod(confirmationMethod);
subjectConfirmation.getConfirmationMethods().add(method);
@@ -292,7 +270,7 @@ public class SAMLUtils {
public static Subject createSubject(final NameIdentifier nameIdentifier, final String confirmationMethod,
KeyInfo keyInfoContent) throws TrustException {
- Subject subject = (Subject)SAMLUtils.buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
+ Subject subject = (Subject)CommonUtil.buildXMLObject(Subject.DEFAULT_ELEMENT_NAME);
subject.setNameIdentifier(nameIdentifier);
SubjectConfirmation subjectConfirmation
@@ -329,7 +307,7 @@ public class SAMLUtils {
throws TrustException {
AuthenticationStatement authenticationStatement
- = (AuthenticationStatement)SAMLUtils.buildXMLObject(AuthenticationStatement.DEFAULT_ELEMENT_NAME);
+ = (AuthenticationStatement)CommonUtil.buildXMLObject(AuthenticationStatement.DEFAULT_ELEMENT_NAME);
authenticationStatement.setSubject(subject);
authenticationStatement.setAuthenticationMethod(authenticationMethod);
@@ -376,7 +354,7 @@ public class SAMLUtils {
throws TrustException {
AttributeStatement attributeStatement
- = (AttributeStatement)SAMLUtils.buildXMLObject(AttributeStatement.DEFAULT_ELEMENT_NAME);
+ = (AttributeStatement)CommonUtil.buildXMLObject(AttributeStatement.DEFAULT_ELEMENT_NAME);
attributeStatement.setSubject(subject);
attributeStatement.getAttributes().addAll(attributeList);
@@ -396,7 +374,7 @@ public class SAMLUtils {
*/
public static Conditions createConditions(DateTime notBefore, DateTime notOnOrAfter) throws TrustException {
- Conditions conditions = (Conditions)SAMLUtils.buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME);
+ Conditions conditions = (Conditions)CommonUtil.buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME);
conditions.setNotBefore(notBefore);
conditions.setNotOnOrAfter(notOnOrAfter);
@@ -453,7 +431,7 @@ public class SAMLUtils {
public static Assertion createAssertion(String issuerName, DateTime notBefore, DateTime notOnOrAfter,
List<Statement> statements) throws TrustException {
- Assertion assertion = (Assertion)SAMLUtils.buildXMLObject(Assertion.DEFAULT_ELEMENT_NAME);
+ Assertion assertion = (Assertion)CommonUtil.buildXMLObject(Assertion.DEFAULT_ELEMENT_NAME);
assertion.setIssuer(issuerName);
assertion.setConditions(SAMLUtils.createConditions(notBefore, notOnOrAfter));
@@ -477,7 +455,7 @@ public class SAMLUtils {
*/
public static Attribute createAttribute(String name, String namespace, String value) throws TrustException {
- Attribute attribute = (Attribute)SAMLUtils.buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
+ Attribute attribute = (Attribute)CommonUtil.buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
attribute.setAttributeName(name);
attribute.setAttributeNamespace(namespace);
@@ -502,7 +480,7 @@ public class SAMLUtils {
*/
public static KeyInfo createKeyInfo() throws TrustException {
- return (KeyInfo)SAMLUtils.buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
+ return (KeyInfo)CommonUtil.buildXMLObject(KeyInfo.DEFAULT_ELEMENT_NAME);
}
/**
@@ -543,128 +521,9 @@ public class SAMLUtils {
return keyInfo;
}
- /**
- * Creates the certificate based KeyInfo object.
- * @param certificate The public key certificate used to create the KeyInfo object.
- * @return OpenSAML representation of KeyInfo object.
- * @throws TrustException If an error occurred while creating the KeyInfo
- */
- public static KeyInfo getCertificateBasedKeyInfo(X509Certificate certificate) throws TrustException {
- X509Data x509Data = SAMLUtils.createX509Data(certificate);
- return SAMLUtils.createKeyInfo(x509Data);
- }
/**
- * This method creates KeyInfo element of an assertion. This is a facade, in which it calls
- * to other helper methods to create KeyInfo. The TokenIssuer will call this method to
- * create the KeyInfo.
- * @param doc An Axiom based DOM Document.
- * @param data The ephemeral key which we use here need in encrypting the message also. Therefore
- * we need to save the ephemeral key in RahasData passed here.
- * @param serviceCert Public key used to encrypt the assertion is extracted from this certificate.
- * @param keySize Size of the key to be used
- * @param crypto The relevant private key
- * @param keyComputation Key computation mechanism.
- * @return OpenSAML KeyInfo representation.
- * @throws WSSecurityException We use WSS4J to generate encrypted key. This exception will trigger if an
- * error occurs while generating the encrypted key.
- * @throws TrustException If an error occurred while creating KeyInfo object.
- */
- public static KeyInfo getSymmetricKeyBasedKeyInfo(Document doc,
- RahasData data,
- X509Certificate serviceCert,
- int keySize,
- Crypto crypto,
- int keyComputation) throws WSSecurityException, TrustException {
-
- byte[] ephemeralKey = TokenIssuerUtil.getSharedSecret(
- data, keyComputation, keySize);
-
- WSSecEncryptedKey encryptedKey = getSymmetricKeyBasedKeyInfoContent(doc, ephemeralKey, serviceCert,
- keySize, crypto);
-
- // Extract the base64 encoded secret value
- byte[] tempKey = new byte[keySize / 8];
- System.arraycopy(encryptedKey.getEphemeralKey(), 0, tempKey,
- 0, keySize / 8);
-
-
- data.setEphmeralKey(tempKey);
-
- EncryptedKey samlEncryptedKey = SAMLUtils.createEncryptedKey(serviceCert, encryptedKey);
- return SAMLUtils.createKeyInfo(samlEncryptedKey);
- }
-
-
-
- // TODO remove keySize parameter
- static WSSecEncryptedKey getSymmetricKeyBasedKeyInfoContent(Document doc,
- byte[] ephemeralKey,
- X509Certificate serviceCert,
- int keySize,
- Crypto crypto) throws WSSecurityException,
- TrustException {
- // Create the encrypted key
- WSSecEncryptedKey encryptedKeyBuilder = new WSSecEncryptedKey();
-
- // Use thumbprint id
- encryptedKeyBuilder
- .setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
-
- // SEt the encryption cert
- encryptedKeyBuilder.setUseThisCert(serviceCert);
-
- // TODO setting keysize is removed with wss4j 1.6 migration - do we actually need this ?
-
- encryptedKeyBuilder.setEphemeralKey(ephemeralKey);
-
- // Set key encryption algo
- encryptedKeyBuilder
- .setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
-
- // Build
- encryptedKeyBuilder.prepare(doc, crypto);
-
- return encryptedKeyBuilder;
- }
-
- /**
- * Creates the X509 data element in a SAML issuer token. Should create an element similar to following,
- * <X509Data xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
- * xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
- * <X509Certificate>
- * MIICNTCCAZ6gAwIB...
- * </X509Certificate>
- * </X509Data>
- * @param clientCert Client certificate to be used when generating X509 data
- * @return SAML X509Data representation.
- * @throws TrustException If an error occurred while creating X509Data and X509Certificate.
- */
- static X509Data createX509Data(X509Certificate clientCert) throws TrustException {
-
- byte[] clientCertBytes;
- try {
- clientCertBytes = clientCert.getEncoded();
- } catch (CertificateEncodingException e) {
- log.error("An error occurred while encoding certificate.", e);
- throw new TrustException("An error occurred while encoding certificate.", e);
- }
- String base64Cert = Base64.encode(clientCertBytes);
-
- org.opensaml.xml.signature.X509Certificate x509Certificate
- = (org.opensaml.xml.signature.X509Certificate)SAMLUtils.buildXMLObject
- (org.opensaml.xml.signature.X509Certificate.DEFAULT_ELEMENT_NAME);
-
- x509Certificate.setValue(base64Cert);
-
- X509Data x509Data = (X509Data)SAMLUtils.buildXMLObject(X509Data.DEFAULT_ELEMENT_NAME);
- x509Data.getX509Certificates().add(x509Certificate);
-
- return x509Data;
- }
-
- /**
* This method will created the "EncryptedKey" of a SAML assertion.
* An encrypted key would look like as follows,
* <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
@@ -699,9 +558,9 @@ public class SAMLUtils {
throws TrustException {
SecurityTokenReference securityTokenReference
- = (SecurityTokenReference)SAMLUtils.buildXMLObject(SecurityTokenReference.ELEMENT_NAME);
+ = (SecurityTokenReference)CommonUtil.buildXMLObject(SecurityTokenReference.ELEMENT_NAME);
- KeyIdentifier keyIdentifier = (KeyIdentifier)SAMLUtils.buildXMLObject(KeyIdentifier.ELEMENT_NAME);
+ KeyIdentifier keyIdentifier = (KeyIdentifier)CommonUtil.buildXMLObject(KeyIdentifier.ELEMENT_NAME);
// Encoding type set to http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0
// #Base64Binary
@@ -714,16 +573,16 @@ public class SAMLUtils {
KeyInfo keyInfo = SAMLUtils.createKeyInfo();
keyInfo.getXMLObjects().add(securityTokenReference);
- CipherValue cipherValue = (CipherValue)buildXMLObject(CipherValue.DEFAULT_ELEMENT_NAME);
+ CipherValue cipherValue = (CipherValue)CommonUtil.buildXMLObject(CipherValue.DEFAULT_ELEMENT_NAME);
cipherValue.setValue(Base64.encode(wsSecEncryptedKey.getEncryptedEphemeralKey()));
- CipherData cipherData = (CipherData)buildXMLObject(CipherData.DEFAULT_ELEMENT_NAME);
+ CipherData cipherData = (CipherData)CommonUtil.buildXMLObject(CipherData.DEFAULT_ELEMENT_NAME);
cipherData.setCipherValue(cipherValue);
- EncryptionMethod encryptionMethod = (EncryptionMethod)buildXMLObject(EncryptionMethod.DEFAULT_ELEMENT_NAME);
+ EncryptionMethod encryptionMethod = (EncryptionMethod)CommonUtil.buildXMLObject(EncryptionMethod.DEFAULT_ELEMENT_NAME);
encryptionMethod.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
- EncryptedKey encryptedKey = (EncryptedKey)SAMLUtils.buildXMLObject(EncryptedKey.DEFAULT_ELEMENT_NAME);
+ EncryptedKey encryptedKey = (EncryptedKey)CommonUtil.buildXMLObject(EncryptedKey.DEFAULT_ELEMENT_NAME);
encryptedKey.setID(wsSecEncryptedKey.getId());
encryptedKey.setEncryptionMethod(encryptionMethod);
@@ -753,14 +612,5 @@ public class SAMLUtils {
return Base64.encode(data);
}
- /**
- * Converts java.util.Date to opensaml DateTime object.
- * @param date Java util date
- * @return opensaml specific DateTime object.
- */
- public static DateTime convertToDateTime(Date date) {
- return new DateTime(date);
- }
-
}
Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java Thu Mar 8 08:11:32 2012
@@ -18,11 +18,20 @@ package org.apache.rahas.impl;
import junit.framework.Assert;
import junit.framework.TestCase;
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.context.MessageContext;
+import org.apache.rahas.RahasConstants;
import org.apache.rahas.RahasData;
+import org.apache.rahas.Token;
+import org.apache.rahas.client.STSClient;
+import org.apache.rahas.test.util.AbstractTestCase;
+import org.apache.rahas.test.util.TestSTSClient;
import org.apache.rahas.test.util.TestUtil;
import org.apache.ws.security.components.crypto.Crypto;
import org.joda.time.DateTime;
+import org.opensaml.common.xml.SAMLConstants;
import org.w3c.dom.Document;
import java.io.File;
@@ -30,44 +39,50 @@ import java.io.File;
/**
* Test class for SAML2 token issuer.
*/
-public class SAML2TokenIssuerTest extends TestCase {
+public class SAML2TokenIssuerTest extends AbstractTestCase {
- public void testIssueToken() {
- // TODO
- Assert.assertTrue(true);
- }
-
- public void testCreateSubjectWithHolderOfKeySC() throws Exception {
-
- // TODO Its hard to do unit testing on TokenIssuer
- // Cos we need to construct complete message contexts with all
- // relevant data. This is more like an integration test rather than a
- // unit test. Therefore we need to refactor code to smaller testable units (methods)
- // and then only write tests.
-
- /*SAML2TokenIssuer saml2TokenIssuer = new SAML2TokenIssuer();
-
- MessageContext messageContext = new MessageContext();
-
- File file = new File("./sts-aar-resources/saml-issuer-config.xml");
- Assert.assertTrue(file.exists());
+ private String configurationElement = "<configuration><saml-issuer-config>" +
+ "<issuerName>Test_STS</issuerName>" +
+ "<issuerKeyAlias>apache</issuerKeyAlias>" +
+ "<issuerKeyPassword>password</issuerKeyPassword>" +
+ "<cryptoProperties><crypto provider=\"org.apache.ws.security.components.crypto.Merlin\">" +
+ "<property name=\"org.apache.ws.security.crypto.merlin.keystore.type\">JKS</property>" +
+ "<property name=\"org.apache.ws.security.crypto.merlin.file\">src/test/resources/keystore.jks</property>" +
+ "<property name=\"org.apache.ws.security.crypto.merlin.keystore.password\">password</property></crypto>" +
+ "</cryptoProperties>" +
+ "<timeToLive>300000</timeToLive>" +
+ "<keySize>256</keySize>" +
+ "<addRequestedAttachedRef /><addRequestedUnattachedRef />" +
+ "<keyComputation>2</keyComputation>" +
+ "<proofKeyType>BinarySecret</proofKeyType>" +
+ "<trusted-services>" +
+ "<service alias=\"apache\">http://10.100.3.196:9768/services/echo/</service>" +
+ "</trusted-services></saml-issuer-config></configuration>";
+
+ public void testCreateSubjectWithHolderOfKeySubjectConfirmation() throws Exception {
+
+ RahasData rahasData = TestUtil.createTestRahasData("http://10.100.3.196:9768/services/echo/");
+
+ SAML2TokenIssuer tokenIssuer = new SAML2TokenIssuer();
+ tokenIssuer.setConfigurationElement(AXIOMUtil.stringToOM(this.configurationElement));
+ SOAPEnvelope envelope = tokenIssuer.issue(rahasData);
+ //System.out.println(envelope.toString());
- SAMLTokenIssuerConfig samlTokenIssuerConfig = new SAMLTokenIssuerConfig(file.getAbsolutePath());
- Crypto crypto = TestUtil.getCrypto();
- DateTime creationDate = new DateTime();
- DateTime expirationDate = new DateTime(2050, 1, 1, 0, 0, 0, 0);
- RahasData rahasData = new RahasData(messageContext);*/
+ TestSTSClient stsClient = TestUtil.createTestSTSClient(SAMLConstants.SAML20_NS);
- /*Document document;
- Crypto crypto;
- DateTime creationDate;
- DateTime expirationDate;
- RahasData rahasData;*/
+ Token token = stsClient.processResponse(RahasConstants.VERSION_05_02,
+ envelope.getBody().getFirstElement(), "http://10.100.3.196:9768/services/echo/");
+ Assert.assertNotNull(token.getToken());
+ }
+ public void testCreateSubjectWithBearerSubjectConfirmation() {
+ // TODO
+ }
+ public void testCreateSubjectWithHOKSubjectConfirmationPublicCert() {
+ // TODO
+ }
- //saml2TokenIssuer.createSubjectWithHolderOfKeySC()
- }
}
Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/CommonUtilTest.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/CommonUtilTest.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/CommonUtilTest.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/CommonUtilTest.java Thu Mar 8 08:11:32 2012
@@ -19,25 +19,38 @@
package org.apache.rahas.impl.util;
import junit.framework.Assert;
-import junit.framework.TestCase;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
+import org.apache.rahas.RahasData;
import org.apache.rahas.TrustException;
import org.apache.rahas.impl.SAMLTokenIssuerConfig;
+import org.apache.rahas.impl.TokenIssuerUtil;
+import org.apache.rahas.test.util.AbstractTestCase;
+import org.apache.rahas.test.util.TestCallbackHandler;
+import org.apache.rahas.test.util.TestSAMLCallbackHandler;
+import org.apache.rahas.test.util.TestUtil;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSEncryptionPart;
import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.message.WSSecEncrypt;
+import org.apache.ws.security.message.WSSecHeader;
+import org.opensaml.Configuration;
+import org.opensaml.xml.signature.KeyInfo;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
/**
* A test class for common util.
*/
-public class CommonUtilTest extends TestCase {
+public class CommonUtilTest extends AbstractTestCase {
private boolean isConfigFromFile = false;
@@ -149,4 +162,128 @@ public class CommonUtilTest extends Test
checkConfigurations(tokenIssuerConfig);
}
+ public void testGetDecryptedBytes() throws Exception {
+
+ RahasData rahasData = new RahasData();
+ byte[] ephemeralKey = TokenIssuerUtil.getSharedSecret(
+ rahasData, 1, 192);
+
+ Document doc = TestUtil.getTestDocument();
+
+ WSSecEncrypt builder = new WSSecEncrypt();
+ builder.setUserInfo("apache");
+ builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
+ builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
+ builder.setEphemeralKey(ephemeralKey);
+ WSSecHeader secHeader = new WSSecHeader();
+ secHeader.insertSecurityHeader(doc);
+
+ builder.prepare(doc, TestUtil.getCrypto());
+
+ List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
+ WSEncryptionPart encP =
+ new WSEncryptionPart(
+ "add", "http://ws.apache.org/counter/counter_port_type", "Element"
+ );
+ parts.add(encP);
+
+ Element refs = builder.encryptForRef(null, parts);
+ builder.addInternalRefElement(refs);
+
+ builder.prependToHeader(secHeader);
+
+ builder.prependBSTElementToHeader(secHeader);
+
+ Element element = builder.getEncryptedKeyElement();
+
+ byte[] decryptedKey = CommonUtil.getDecryptedBytes(new TestCallbackHandler(), TestUtil.getCrypto(), element);
+
+ Assert.assertTrue(Arrays.equals(ephemeralKey, decryptedKey));
+
+ }
+
+ public void testGetSymmetricKeyBasedKeyInfo() throws Exception {
+
+ RahasData rahasData = new RahasData();
+
+ Document doc = TestUtil.getTestDocument();
+
+ KeyInfo keyInfo = CommonUtil.getSymmetricKeyBasedKeyInfo(doc, rahasData,
+ TestUtil.getDefaultCertificate(), 256, TestUtil.getCrypto(), 2);
+
+ Assert.assertNotNull(keyInfo);
+
+ marshallerFactory.getMarshaller(keyInfo).marshall(keyInfo, doc.getDocumentElement());
+
+ printElement(keyInfo.getDOM());
+
+ OMElement element = (OMElement)keyInfo.getDOM();
+
+ printElement(element);
+
+ Assert.assertNotNull(rahasData.getEphmeralKey());
+
+ Assert.assertNotNull(element.getChildrenWithLocalName("EncryptedKey"));
+ Assert.assertNotNull(element.getChildrenWithLocalName("CipherData"));
+ Assert.assertNotNull(element.getChildrenWithLocalName("CipherValue"));
+ }
+
+ public void testGetCertificateBasedKeyInfo() throws Exception {
+
+ Document doc = TestUtil.getTestDocument();
+
+ KeyInfo keyInfo = CommonUtil.getCertificateBasedKeyInfo(TestUtil.getDefaultCertificate());
+
+ Assert.assertNotNull(keyInfo);
+
+ marshallerFactory.getMarshaller(keyInfo).marshall(keyInfo, doc.getDocumentElement());
+
+ printElement(keyInfo.getDOM());
+
+ OMElement element = (OMElement)keyInfo.getDOM();
+
+ printElement(element);
+
+ Assert.assertNotNull(element.getChildrenWithLocalName("X509Data"));
+ Assert.assertNotNull(element.getChildrenWithLocalName("X509Certificate"));
+
+ }
+
+ public void testGetSAMLCallbackHandlerWithObject() throws Exception {
+
+ RahasData rahasData = new RahasData();
+
+ this.isConfigFromFile = true;
+ SAMLTokenIssuerConfig tokenIssuerConfig = CommonUtil.createTokenIssuerConfiguration(configurationFileName);
+ Assert.assertNotNull(tokenIssuerConfig);
+ checkConfigurations(tokenIssuerConfig);
+
+ tokenIssuerConfig.setCallbackHandler(new TestSAMLCallbackHandler());
+
+ SAMLCallbackHandler cb = CommonUtil.getSAMLCallbackHandler(tokenIssuerConfig, rahasData);
+
+ Assert.assertTrue(cb instanceof TestSAMLCallbackHandler);
+ }
+
+ public void testGetSAMLCallbackHandlerWithCallbackName() throws Exception {
+
+ RahasData rahasData = new RahasData();
+
+ MessageContext messageContext = new MessageContext();
+ messageContext.setAxisService(new AxisService("My Service"));
+
+ rahasData.setInMessageContext(messageContext);
+
+ this.isConfigFromFile = true;
+ SAMLTokenIssuerConfig tokenIssuerConfig = CommonUtil.createTokenIssuerConfiguration(configurationFileName);
+ Assert.assertNotNull(tokenIssuerConfig);
+ checkConfigurations(tokenIssuerConfig);
+
+ tokenIssuerConfig.setCallbackHandlerName("org.apache.rahas.test.util.TestSAMLCallbackHandler");
+
+ SAMLCallbackHandler cb = CommonUtil.getSAMLCallbackHandler(tokenIssuerConfig, rahasData);
+
+ Assert.assertTrue(cb instanceof TestSAMLCallbackHandler);
+ }
+
}
Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/SAMLUtilsTest.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/SAMLUtilsTest.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/SAMLUtilsTest.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/impl/util/SAMLUtilsTest.java Thu Mar 8 08:11:32 2012
@@ -26,11 +26,10 @@ import org.apache.commons.logging.LogFac
import org.apache.rahas.Rahas;
import org.apache.rahas.TrustException;
import org.apache.rahas.TrustUtil;
-import org.apache.rahas.impl.AbstractIssuerConfig;
+import org.apache.rahas.test.util.AbstractTestCase;
import org.apache.rahas.test.util.TestUtil;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
-import org.apache.ws.security.components.crypto.CryptoFactory;
import org.apache.ws.security.message.WSSecEncryptedKey;
import org.apache.ws.security.util.Base64;
import org.joda.time.DateTime;
@@ -59,29 +58,17 @@ import java.security.cert.X509Certificat
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import java.util.Properties;
/**
* A test class for SAML 1 Token Issuer.
*/
-public class SAMLUtilsTest extends TestCase{
-
- protected static MarshallerFactory marshallerFactory;
-
- private static final boolean PRINT = false;
+public class SAMLUtilsTest extends AbstractTestCase {
private static final Log log = LogFactory.getLog(SAMLUtilsTest.class);
- public void setUp() throws AxisFault {
- Rahas rahas = new Rahas();
- rahas.init(null, null);
-
- marshallerFactory = Configuration.getMarshallerFactory();
- }
-
public void testBuildXMLObjectNegative() {
try {
- SAMLUtils.buildXMLObject(new QName("http://x.com", "y"));
+ CommonUtil.buildXMLObject(new QName("http://x.com", "y"));
Assert.fail("This should throw an exception");
} catch (TrustException e) {
}
@@ -172,7 +159,7 @@ public class SAMLUtilsTest extends TestC
public void testCreateKeyInfoWithX509Data() throws Exception {
- X509Data x509Data = SAMLUtils.createX509Data(getTestCertificate());
+ X509Data x509Data = CommonUtil.createX509Data(getTestCertificate());
org.opensaml.xml.signature.KeyInfo keyInfo = SAMLUtils.createKeyInfo(x509Data);
@@ -210,7 +197,7 @@ public class SAMLUtilsTest extends TestC
= SAMLUtils.createNamedIdentifier("joe,ou=people,ou=saml-demo,o=baltimore.com",
NameIdentifier.X509_SUBJECT);
- X509Data x509Data = SAMLUtils.createX509Data(getTestCertificate());
+ X509Data x509Data = CommonUtil.createX509Data(getTestCertificate());
org.opensaml.xml.signature.KeyInfo keyInfo = SAMLUtils.createKeyInfo(x509Data);
@@ -233,7 +220,7 @@ public class SAMLUtilsTest extends TestC
public void testCreateX509Data() throws Exception {
- X509Data x509Data = SAMLUtils.createX509Data(getTestCertificate());
+ X509Data x509Data = CommonUtil.createX509Data(getTestCertificate());
Assert.assertNotNull(x509Data);
marshallerFactory.getMarshaller(x509Data).marshall(x509Data);
@@ -273,16 +260,14 @@ public class SAMLUtilsTest extends TestC
SOAPEnvelope env = TrustUtil.createSOAPEnvelope("http://schemas.xmlsoap.org/soap/envelope/");
Document doc = ((Element) env).getOwnerDocument();
- int keySize = 256;
-
byte [] ephemeralKey = generateEphemeralKey(256);
WSSecEncryptedKey encryptedKey
- = SAMLUtils.getSymmetricKeyBasedKeyInfoContent(doc,
- ephemeralKey, getTestCertificate(), keySize, TestUtil.getCrypto());
+ = CommonUtil.getSymmetricKeyBasedKeyInfoContent(doc,
+ ephemeralKey, getTestCertificate(), TestUtil.getCrypto());
Assert.assertNotNull(encryptedKey.getEncryptedKeyElement());
- printElement(encryptedKey.getEncryptedKeyElement());
+ //printElement(encryptedKey.getEncryptedKeyElement());
return encryptedKey;
}
@@ -300,13 +285,6 @@ public class SAMLUtilsTest extends TestC
- private static void printElement(Element element) throws TransformerException {
-
- // print xml
- if (PRINT) {
- System.out.println(getXMLString(element));
- }
- }
private static X509Certificate getTestCertificate() throws IOException, WSSecurityException, TrustException {
@@ -315,21 +293,7 @@ public class SAMLUtilsTest extends TestC
return CommonUtil.getCertificateByAlias(crypto, "apache");
}
- private static String getXMLString(Element element) throws TransformerException {
- TransformerFactory transfac = TransformerFactory.newInstance();
- Transformer trans = transfac.newTransformer();
- trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
- trans.setOutputProperty(OutputKeys.INDENT, "yes");
-
- // create string from xml tree
- StringWriter sw = new StringWriter();
- StreamResult result = new StreamResult(sw);
- DOMSource source = new DOMSource(element);
- trans.transform(source, result);
- return sw.toString();
-
- }
private static boolean equals(String element1, String element2) throws ParserConfigurationException, IOException, SAXException {
Added: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/AbstractTestCase.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/AbstractTestCase.java?rev=1298292&view=auto
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/AbstractTestCase.java (added)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/AbstractTestCase.java Thu Mar 8 08:11:32 2012
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.rahas.test.util;
+
+import junit.framework.TestCase;
+import org.apache.axiom.om.OMElement;
+import org.apache.rahas.Rahas;
+import org.apache.ws.security.WSSConfig;
+import org.opensaml.Configuration;
+import org.opensaml.xml.io.MarshallerFactory;
+import org.w3c.dom.Element;
+
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.StringWriter;
+
+/**
+ * An abstract class for tests
+ */
+public class AbstractTestCase extends TestCase {
+
+ protected static MarshallerFactory marshallerFactory;
+
+ private static final boolean PRINT = false;
+
+ public void setUp() throws Exception {
+
+ Rahas rahas = new Rahas();
+ //noinspection NullableProblems
+ rahas.init(null, null);
+
+ WSSConfig.init();
+
+ org.apache.xml.security.Init.init();
+
+ marshallerFactory = Configuration.getMarshallerFactory();
+
+ }
+
+ public String getXMLString(Element element) throws TransformerException {
+
+ TransformerFactory transfac = TransformerFactory.newInstance();
+ Transformer trans = transfac.newTransformer();
+ trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ trans.setOutputProperty(OutputKeys.INDENT, "yes");
+
+ // create string from xml tree
+ StringWriter sw = new StringWriter();
+ StreamResult result = new StreamResult(sw);
+ DOMSource source = new DOMSource(element);
+ trans.transform(source, result);
+ return sw.toString();
+
+ }
+
+ public void printElement(Element element) throws TransformerException {
+ // print xml
+ if (PRINT) {
+ System.out.println(getXMLString(element));
+ }
+ }
+
+ public void printElement(OMElement element) throws TransformerException {
+ // print xml
+ if (PRINT) {
+ element.build();
+ System.out.println(element.toString());
+ }
+ }
+
+ public void testDummy() {
+
+ }
+
+}
Added: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestCallbackHandler.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestCallbackHandler.java?rev=1298292&view=auto
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestCallbackHandler.java (added)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestCallbackHandler.java Thu Mar 8 08:11:32 2012
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.rahas.test.util;
+
+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;
+
+/**
+ * Password callback for tests.
+ */
+public class TestCallbackHandler implements CallbackHandler {
+ public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+
+ for(Callback callback : callbacks) {
+ if (callback instanceof WSPasswordCallback) {
+ WSPasswordCallback wsPasswordCallback = (WSPasswordCallback)callback;
+
+ if (wsPasswordCallback.getIdentifier().equals("apache")) {
+ wsPasswordCallback.setPassword("password");
+ }
+ }
+ }
+
+ }
+}
Added: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSAMLCallbackHandler.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSAMLCallbackHandler.java?rev=1298292&view=auto
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSAMLCallbackHandler.java (added)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSAMLCallbackHandler.java Thu Mar 8 08:11:32 2012
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.rahas.test.util;
+
+import org.apache.rahas.impl.util.SAMLCallback;
+import org.apache.rahas.impl.util.SAMLCallbackHandler;
+import org.opensaml.common.SAMLException;
+
+/**
+ * A callback handler for testing purpose.
+ */
+public class TestSAMLCallbackHandler implements SAMLCallbackHandler {
+ public void handle(SAMLCallback callback) throws SAMLException {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
+}
Added: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSTSClient.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSTSClient.java?rev=1298292&view=auto
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSTSClient.java (added)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestSTSClient.java Thu Mar 8 08:11:32 2012
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.apache.rahas.test.util;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.rahas.Token;
+import org.apache.rahas.TrustException;
+import org.apache.rahas.client.STSClient;
+
+/**
+ * STS client for tests.
+ */
+public class TestSTSClient extends STSClient {
+
+ public TestSTSClient(ConfigurationContext configCtx) throws TrustException {
+ super(configCtx);
+ }
+
+ public Token processResponse(int version, OMElement result,
+ String issuerAddress) throws TrustException {
+ return super.processIssueResponse(version, result, issuerAddress);
+ }
+
+ public OMElement createRST(String appliesTo) throws TrustException {
+
+ return super.createIssueRequest(appliesTo);
+ }
+}
Modified: axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestUtil.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestUtil.java?rev=1298292&r1=1298291&r2=1298292&view=diff
==============================================================================
--- axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestUtil.java (original)
+++ axis/axis2/java/rampart/trunk/modules/rampart-trust/src/test/java/org/apache/rahas/test/util/TestUtil.java Thu Mar 8 08:11:32 2012
@@ -16,18 +16,53 @@
package org.apache.rahas.test.util;
import junit.framework.Assert;
+import org.apache.axiom.om.*;
+import org.apache.axiom.om.impl.builder.StAXBuilder;
+import org.apache.axiom.om.impl.dom.DOOMAbstractFactory;
+import org.apache.axiom.om.util.StAXUtils;
+import org.apache.axiom.soap.*;
+import org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder;
+import org.apache.axiom.soap.impl.dom.soap11.SOAP11Factory;
+import org.apache.axis2.addressing.AddressingConstants;
+import org.apache.axis2.context.ConfigurationContext;
+import org.apache.axis2.context.ConfigurationContextFactory;
+import org.apache.axis2.context.MessageContext;
+import org.apache.axis2.description.AxisService;
+import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.apache.rahas.RahasConstants;
+import org.apache.rahas.RahasData;
import org.apache.rahas.TrustException;
+import org.apache.rahas.TrustUtil;
import org.apache.rahas.impl.util.CommonUtil;
+import org.apache.ws.secpolicy.Constants;
+import org.apache.ws.security.WSConstants;
+import org.apache.ws.security.WSSecurityEngineResult;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoFactory;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
+import org.apache.ws.security.components.crypto.CryptoType;
+import org.apache.ws.security.handler.WSHandlerConstants;
+import org.apache.ws.security.handler.WSHandlerResult;
+import org.apache.ws.security.saml.ext.builder.SAML1Constants;
+import org.apache.xml.security.utils.XMLUtils;
+import org.opensaml.common.xml.SAMLConstants;
+import org.w3c.dom.DOMConfiguration;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.stream.FactoryConfigurationError;
+import javax.xml.stream.XMLStreamReader;
+import java.io.*;
+import java.security.Principal;
import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
import java.util.Properties;
/**
@@ -37,6 +72,36 @@ public class TestUtil {
private static final Log log = LogFactory.getLog(TestUtil.class);
+ // Directly copied from WSS4J
+ public static final String SAMPLE_SOAP_MSG =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ + "<SOAP-ENV:Envelope "
+ + "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
+ + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
+ + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
+ + "<SOAP-ENV:Header"
+ + " xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/07/secext\""
+ + " xmlns:wsu=\"http://schemas.xmlsoap.org/ws/2002/07/utility\"/>"
+ + "<SOAP-ENV:Body>"
+ + "<add xmlns=\"http://ws.apache.org/counter/counter_port_type\">"
+ + "<value xmlns=\"\">15</value>"
+ + "</add>"
+ + "</SOAP-ENV:Body>"
+ + "</SOAP-ENV:Envelope>";
+
+ /**
+ * Convert an SOAP Envelope as a String to a org.w3c.dom.Document.
+ * Directly copied from WSS4J
+ */
+ public static org.w3c.dom.Document toSOAPPart(String xml) throws Exception {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+
+ InputStream in = new ByteArrayInputStream(xml.getBytes());
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ return builder.parse(in);
+ }
+
public static Crypto getCrypto() throws IOException, WSSecurityException, TrustException {
File file = new File("src/test/resources/crypto.config");
@@ -58,4 +123,340 @@ public class TestUtil {
return crypto;
}
+
+ public static X509Certificate getDefaultCertificate() throws WSSecurityException, TrustException, IOException {
+ Crypto crypto = getCrypto();
+
+ CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
+ cryptoType.setAlias("apache");
+
+ return crypto.getX509Certificates(cryptoType)[0];
+ }
+
+ public static Document getTestDocument() throws Exception {
+
+ InputStream is = new ByteArrayInputStream(SAMPLE_SOAP_MSG.getBytes());
+ SOAPEnvelope envelope = createSOAPEnvelope(is);
+
+ return TestUtil.getDocumentFromSOAPEnvelope(envelope, true);
+ }
+
+ public static SOAPEnvelope createSOAPEnvelope(InputStream in) throws Exception {
+ XMLStreamReader xmlreader =
+ StAXUtils.createXMLStreamReader(in);
+ StAXBuilder builder = new StAXSOAPModelBuilder(xmlreader, null);
+ return (SOAPEnvelope) builder.getDocumentElement();
+ }
+
+ public static OMElement getRSTTemplate(String samlNamespace) throws Exception {
+ OMFactory fac = OMAbstractFactory.getOMFactory();
+ OMElement element = null;
+ OMElement elem = fac.createOMElement(Constants.RST_TEMPLATE);
+ TrustUtil.createTokenTypeElement(RahasConstants.VERSION_05_02, elem).setText(samlNamespace);
+ TrustUtil.createKeyTypeElement(RahasConstants.VERSION_05_02, elem,
+ RahasConstants.KEY_TYPE_SYMM_KEY);
+ TrustUtil.createKeySizeElement(RahasConstants.VERSION_05_02, elem, 256);
+ element = TrustUtil.createClaims(RahasConstants.VERSION_05_02, elem, "http://wso2.org");
+ addClaimType(element, "http://wso2.org/claims/givenname");
+ return elem;
+ }
+
+ private static void addClaimType(OMElement parent, String uri) {
+ OMElement element = null;
+ element = parent.getOMFactory().createOMElement(new QName("http://schemas.xmlsoap.org/ws/2005/05/identity", "ClaimType", "wsid"),
+ parent);
+ element.addAttribute(parent.getOMFactory().createOMAttribute("Uri", null, uri));
+ }
+
+ public static TestSTSClient createTestSTSClient(String samlVersion) throws Exception {
+
+ ConfigurationContext configurationContext
+ = ConfigurationContextFactory.createConfigurationContextFromFileSystem("src/test/resources/repo",
+ "src/test/resources/repo/conf/client.axis2.xml");
+
+ TestSTSClient stsClient = new TestSTSClient(configurationContext);
+
+ stsClient.setRstTemplate(getRSTTemplate(samlVersion));
+ stsClient.setAction(RahasConstants.WST_NS_05_02 + RahasConstants.RST_ACTION_SCT);
+
+ return stsClient;
+
+ }
+
+ public static MessageContext createDummyMessageContext(String appliesTo) throws Exception {
+ TestSTSClient stsClient = TestUtil.createTestSTSClient(SAMLConstants.SAML20_NS);
+ OMElement requestSecurityToken = stsClient.createRST(appliesTo);
+
+ MessageContext dummyMessageContext = new MessageContext();
+
+ populateReceivedResults(dummyMessageContext);
+
+ dummyMessageContext.setProperty(AddressingConstants.WS_ADDRESSING_VERSION,
+ AddressingConstants.Submission.WSA_NAMESPACE);
+
+ SOAP11Factory factory = new SOAP11Factory();
+ SOAPEnvelope envelope = factory.createSOAPEnvelope();
+
+ SOAPBody soapBody = factory.createSOAPBody(envelope);
+ soapBody.addChild(requestSecurityToken);
+
+ dummyMessageContext.setEnvelope(envelope);
+
+ dummyMessageContext.setAxisService(new AxisService("TestService"));
+
+
+ AxisConfiguration axisConfiguration = new AxisConfiguration();
+ dummyMessageContext.setConfigurationContext(new ConfigurationContext(axisConfiguration));
+
+ return dummyMessageContext;
+ }
+
+ public static RahasData createTestRahasData(String appliesTo) throws Exception {
+ return new RahasData(createDummyMessageContext(appliesTo));
+ }
+
+ private static void populateReceivedResults(MessageContext messageContext) throws Exception {
+ List<WSSecurityEngineResult> wsSecEngineResults = new ArrayList<WSSecurityEngineResult>();
+ WSSecurityEngineResult result = new WSSecurityEngineResult(WSConstants.SIGN);
+
+ Principal principal = new Principal() {
+ public String getName() {
+ return "apache";
+ }
+ };
+
+ result.put(WSSecurityEngineResult.TAG_PRINCIPAL, principal);
+ result.put(WSSecurityEngineResult.TAG_X509_CERTIFICATE, getDefaultCertificate());
+
+ wsSecEngineResults.add(result);
+
+ WSHandlerResult handlerResult = new WSHandlerResult(null, wsSecEngineResults);
+
+ List<WSHandlerResult> handlerResultList = new ArrayList<WSHandlerResult>();
+ handlerResultList.add(handlerResult);
+
+ messageContext.setProperty(WSHandlerConstants.RECV_RESULTS, handlerResultList);
+
+ }
+
+ /**
+ * This is directly taken from rampart-core.
+ * TODO we need to move these common code to a new module. Otherwise code will be duplicated.
+ * We cannot following method from rampart-core as it creates a cyclic dependency. Therefore we have
+ * to live will following.
+ * @param doc The document to convert.
+ * @param useDoom Whether to use doom or not.
+ * @return A SOAPEnvelope.
+ * @throws WSSecurityException If an error occurred during conversion.
+ */
+ public static SOAPEnvelope getSOAPEnvelopeFromDOMDocument(Document doc, boolean useDoom)
+ throws WSSecurityException {
+
+ if(useDoom) {
+ try {
+ //Get processed headers
+ SOAPEnvelope env = (SOAPEnvelope)doc.getDocumentElement();
+ ArrayList processedHeaderQNames = new ArrayList();
+ SOAPHeader soapHeader = env.getHeader();
+
+ if(soapHeader != null) {
+ Iterator headerBlocs = soapHeader.getChildElements();
+ while (headerBlocs.hasNext()) {
+
+ OMElement element = (OMElement)headerBlocs.next();
+ SOAPHeaderBlock header = null;
+
+ if (element instanceof SOAPHeaderBlock) {
+ header = (SOAPHeaderBlock) element;
+
+ // If a header block is not an instance of SOAPHeaderBlock, it means that
+ // it is a header we have added in rampart eg. EncryptedHeader and should
+ // be converted to SOAPHeaderBlock for processing
+ } else {
+ header = soapHeader.addHeaderBlock(element.getLocalName(), element.getNamespace());
+ Iterator attrIter = element.getAllAttributes();
+ while (attrIter.hasNext()) {
+ OMAttribute attr = (OMAttribute)attrIter.next();
+ header.addAttribute(attr.getLocalName(), attr.getAttributeValue(), attr.getNamespace());
+ }
+ Iterator nsIter = element.getAllDeclaredNamespaces();
+ while (nsIter.hasNext()) {
+ OMNamespace ns = (OMNamespace) nsIter.next();
+ header.declareNamespace(ns);
+ }
+ // retrieve all child nodes (including any text nodes)
+ // and re-attach to header block
+ Iterator children = element.getChildren();
+ while (children.hasNext()) {
+ OMNode child = (OMNode)children.next();
+ children.remove();
+ header.addChild(child);
+ }
+
+ element.detach();
+
+ soapHeader.build();
+
+ header.setProcessed();
+
+ }
+
+ if(header.isProcessed()) {
+ processedHeaderQNames.add(element.getQName());
+ }
+ }
+
+ }
+ XMLStreamReader reader = ((OMElement) doc.getDocumentElement())
+ .getXMLStreamReader();
+ SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createStAXSOAPModelBuilder(
+ reader);
+ SOAPEnvelope envelope = stAXSOAPModelBuilder.getSOAPEnvelope();
+
+ //Set the processed flag of the processed headers
+ SOAPHeader header = envelope.getHeader();
+ for (Iterator iter = processedHeaderQNames.iterator(); iter
+ .hasNext();) {
+ QName name = (QName) iter.next();
+ Iterator omKids = header.getChildrenWithName(name);
+ if(omKids.hasNext()) {
+ ((SOAPHeaderBlock)omKids.next()).setProcessed();
+ }
+ }
+
+ envelope.build();
+
+ return envelope;
+
+ } catch (FactoryConfigurationError e) {
+ throw new WSSecurityException(e.getMessage());
+ }
+ } else {
+ try {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ XMLUtils.outputDOM(doc.getDocumentElement(), os, true);
+ ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());
+
+ SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createSOAPModelBuilder(bais, null);
+ return stAXSOAPModelBuilder.getSOAPEnvelope();
+ } catch (Exception e) {
+ throw new WSSecurityException(e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * TODO we need to move these common code to a new module. Otherwise code will be duplicated.
+ * We cannot following method from rampart-core as it creates a cyclic dependency. Therefore we have
+ * to live will following.
+ * Creates a DOM Document using the SOAP Envelope.
+ * @param env An org.apache.axiom.soap.SOAPEnvelope instance
+ * @return Returns the DOM Document of the given SOAP Envelope.
+ * @throws Exception If an error occurred during conversion.
+ */
+ public static Document getDocumentFromSOAPEnvelope(SOAPEnvelope env, boolean useDoom)
+ throws WSSecurityException {
+ try {
+ if(env instanceof Element) {
+ Element element = (Element)env;
+ Document document = element.getOwnerDocument();
+ // For outgoing messages, Axis2 only creates the SOAPEnvelope, but no document. If
+ // the Axiom implementation also supports DOM, then the envelope (seen as a DOM
+ // element) will have an owner document, but the document and the envelope have no
+ // parent-child relationship. On the other hand, the input expected by WSS4J is
+ // a document with the envelope as document element. Therefore we need to set the
+ // envelope as document element on the owner document.
+ if (element.getParentNode() != document) {
+ document.appendChild(element);
+ }
+ // If the Axiom implementation supports DOM, then it is possible/likely that the
+ // DOM API was used to create the object model (or parts of it). In this case, the
+ // object model is not necessarily well formed with respect to namespaces because
+ // DOM doesn't generate namespace declarations automatically. This is an issue
+ // because WSS4J/Santuario expects that all namespace declarations are present.
+ // If this is not the case, then signature values or encryptions will be incorrect.
+ // To avoid this, we normalize the document. Note that if we disable the other
+ // normalizations supported by DOM, this is generally not a heavy operation.
+ // In particular, the Axiom implementation is not required to expand the object
+ // model (including OMSourcedElements) because the Axiom builder is required to
+ // perform namespace repairing, so that no modifications to unexpanded parts of
+ // the message are required.
+ DOMConfiguration domConfig = document.getDomConfig();
+ domConfig.setParameter("split-cdata-sections", Boolean.FALSE);
+ domConfig.setParameter("well-formed", Boolean.FALSE);
+ domConfig.setParameter("namespaces", Boolean.TRUE);
+ document.normalizeDocument();
+ return document;
+ }
+
+ if (useDoom) {
+ env.build();
+
+ // Workaround to prevent a bug in AXIOM where
+ // there can be an incomplete OMElement as the first child body
+ OMElement firstElement = env.getBody().getFirstElement();
+ if (firstElement != null) {
+ firstElement.build();
+ }
+
+ //Get processed headers
+ SOAPHeader soapHeader = env.getHeader();
+ ArrayList processedHeaderQNames = new ArrayList();
+ if(soapHeader != null) {
+ Iterator headerBlocs = soapHeader.getChildElements();
+ while (headerBlocs.hasNext()) {
+ SOAPHeaderBlock element = (SOAPHeaderBlock) headerBlocs.next();
+ if(element.isProcessed()) {
+ processedHeaderQNames.add(element.getQName());
+ }
+ }
+ }
+
+ // Check the namespace and find SOAP version and factory
+ String nsURI = null;
+ SOAPFactory factory;
+ if (env.getNamespace().getNamespaceURI().equals(
+ SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI)) {
+ nsURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
+ factory = DOOMAbstractFactory.getSOAP11Factory();
+ } else {
+ nsURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
+ factory = DOOMAbstractFactory.getSOAP12Factory();
+ }
+
+ StAXSOAPModelBuilder stAXSOAPModelBuilder = new StAXSOAPModelBuilder(
+ env.getXMLStreamReader(), factory, nsURI);
+ SOAPEnvelope envelope = (stAXSOAPModelBuilder)
+ .getSOAPEnvelope();
+ envelope.getParent().build();
+
+ //Set the processed flag of the processed headers
+ SOAPHeader header = envelope.getHeader();
+ for (Iterator iter = processedHeaderQNames.iterator(); iter
+ .hasNext();) {
+ QName name = (QName) iter.next();
+ Iterator omKids = header.getChildrenWithName(name);
+ if(omKids.hasNext()) {
+ ((SOAPHeaderBlock)omKids.next()).setProcessed();
+ }
+ }
+
+ Element envElem = (Element) envelope;
+ return envElem.getOwnerDocument();
+ } else {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ env.build();
+ env.serialize(baos);
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos
+ .toByteArray());
+ DocumentBuilderFactory factory = DocumentBuilderFactory
+ .newInstance();
+ factory.setNamespaceAware(true);
+ return factory.newDocumentBuilder().parse(bais);
+ }
+ } catch (Exception e) {
+ throw new WSSecurityException(
+ "Error in converting SOAP Envelope to Document", e);
+ }
+ }
}