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 ve...@apache.org on 2017/01/30 17:50:59 UTC
svn commit: r1780953 [8/9] - in
/axis/axis2/java/rampart/branches/RAMPART-289: ./ apidocs/ code-coverage/
etc/ legal/ modules/distribution/ modules/distribution/src/
modules/documentation/ modules/rampart-core/
modules/rampart-core/src/main/java/META-I...
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java Mon Jan 30 17:50:58 2017
@@ -20,7 +20,6 @@ import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.context.MessageContext;
-import org.apache.axis2.description.Parameter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.RahasConstants;
@@ -33,7 +32,6 @@ import org.apache.rahas.impl.util.*;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.WSUsernameTokenPrincipal;
import org.apache.ws.security.components.crypto.Crypto;
-import org.apache.ws.security.components.crypto.CryptoFactory;
import org.apache.ws.security.util.Loader;
import org.apache.ws.security.util.XmlSchemaDateFormat;
@@ -64,60 +62,43 @@ public class SAMLTokenIssuer implements
private String configFile;
-
- //TODO move this to TrustUtil
- private static final String AUTHENTICATION_METHOD_PASSWORD = "urn:oasis:names:tc:SAML:1.0:am:password";
-
private static final Log log = LogFactory.getLog(SAMLTokenIssuer.class);
public SOAPEnvelope issue(RahasData data) throws TrustException {
MessageContext inMsgCtx = data.getInMessageContext();
- SAMLTokenIssuerConfig config = null;
- if (this.configElement != null) {
- config = new SAMLTokenIssuerConfig(configElement
- .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
- }
-
- // Look for the file
- if (config == null && this.configFile != null) {
- config = new SAMLTokenIssuerConfig(this.configFile);
- }
-
- // Look for the param
- if (config == null && this.configParamName != null) {
- Parameter param = inMsgCtx.getParameter(this.configParamName);
- if (param != null && param.getParameterElement() != null) {
- config = new SAMLTokenIssuerConfig(param
- .getParameterElement().getFirstChildWithName(
- SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
- } else {
- throw new TrustException("expectedParameterMissing",
- new String[] { this.configParamName });
+ SAMLTokenIssuerConfig tokenIssuerConfiguration = CommonUtil.getTokenIssuerConfiguration(this.configElement,
+ this.configFile, inMsgCtx.getParameter(this.configParamName));
+
+ if (tokenIssuerConfiguration == null) {
+
+ 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";
+ }
+
+ log.debug("Unable to build token configurations, " + parameterName);
}
- }
- if (config == null) {
throw new TrustException("configurationIsNull");
}
SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx
.getEnvelope().getNamespace().getNamespaceURI());
- Crypto crypto;
- if (config.cryptoElement != null) { // crypto props defined as elements
- crypto = CommonUtil.getCrypto(TrustUtil
- .toProperties(config.cryptoElement), inMsgCtx
- .getAxisService().getClassLoader());
-
- } else { // crypto props defined in a properties file
- crypto = CommonUtil.getCrypto(config.cryptoPropertiesFile, inMsgCtx
+ Crypto crypto = tokenIssuerConfiguration.getIssuerCrypto(inMsgCtx
.getAxisService().getClassLoader());
- }
// Creation and expiration times
DateTime creationTime = new DateTime();
- DateTime expirationTime = new DateTime(creationTime.getMillis() + config.ttl);
+ DateTime expirationTime = new DateTime(creationTime.getMillis() + tokenIssuerConfiguration.getTtl());
// Get the document
Document doc = ((Element) env).getOwnerDocument();
@@ -125,7 +106,7 @@ public class SAMLTokenIssuer implements
// Get the key size and create a new byte array of that size
int keySize = data.getKeysize();
- keySize = (keySize == -1) ? config.keySize : keySize;
+ keySize = (keySize == -1) ? tokenIssuerConfiguration.getKeySize() : keySize;
/*
* Find the KeyType If the KeyType is SymmetricKey or PublicKey,
@@ -147,10 +128,10 @@ public class SAMLTokenIssuer implements
if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
|| keyType.endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) {
- assertion = createHoKAssertion(config, doc, crypto,
+ assertion = createHoKAssertion(tokenIssuerConfiguration, doc, crypto,
creationTime, expirationTime, data);
} else if (keyType.endsWith(RahasConstants.KEY_TYPE_BEARER)) {
- assertion = createBearerAssertion(config, doc, crypto,
+ assertion = createBearerAssertion(tokenIssuerConfiguration, doc, crypto,
creationTime, expirationTime, data);
} else {
throw new TrustException("unsupportedKeyType");
@@ -176,11 +157,11 @@ public class SAMLTokenIssuer implements
TrustUtil.createKeySizeElement(wstVersion, rstrElem, keySize);
}
- if (config.addRequestedAttachedRef) {
+ if (tokenIssuerConfiguration.isAddRequestedAttachedRef()) {
TrustUtil.createRequestedAttachedRef(rstrElem, assertion.getID(),wstVersion);
}
- if (config.addRequestedUnattachedRef) {
+ if (tokenIssuerConfiguration.isAddRequestedUnattachedRef()) {
TrustUtil.createRequestedUnattachedRef(rstrElem, assertion.getID(),wstVersion);
}
@@ -221,11 +202,11 @@ public class SAMLTokenIssuer implements
}*/
if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
- && config.keyComputation != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {
+ && tokenIssuerConfiguration.getKeyComputation() != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {
// Add the RequestedProofToken
TokenIssuerUtil.handleRequestedProofToken(data, wstVersion,
- config, rstrElem, assertionToken, doc);
+ tokenIssuerConfiguration, rstrElem, assertionToken, doc);
}
return env;
@@ -298,12 +279,12 @@ public class SAMLTokenIssuer implements
// set keySize
int keySize = data.getKeysize();
- keySize = (keySize != -1) ? keySize : config.keySize;
+ keySize = (keySize != -1) ? keySize : config.getKeySize();
// Create the encrypted key
KeyInfo encryptedKeyInfoElement
- = SAMLUtils.getSymmetricKeyBasedKeyInfo(doc, data, serviceCert, keySize,
- crypto, config.keyComputation);
+ = CommonUtil.getSymmetricKeyBasedKeyInfo(doc, data, serviceCert, keySize,
+ crypto, config.getKeyComputation());
return this.createAttributeAssertion(data, encryptedKeyInfoElement, nameIdentifier, config,
crypto, creationTime, expirationTime);
@@ -350,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);
@@ -376,15 +357,15 @@ public class SAMLTokenIssuer implements
// TODO a duplicate method !!
if (serviceAddress != null && !"".equals(serviceAddress)) {
- String alias = (String) config.trustedServices.get(serviceAddress);
+ String alias = (String) config.getTrustedServices().get(serviceAddress);
if (alias != null) {
return CommonUtil.getCertificateByAlias(crypto,alias);
} else {
- alias = (String) config.trustedServices.get("*");
+ alias = (String) config.getTrustedServices().get("*");
return CommonUtil.getCertificateByAlias(crypto,alias);
}
} else {
- String alias = (String) config.trustedServices.get("*");
+ String alias = (String) config.getTrustedServices().get("*");
return CommonUtil.getCertificateByAlias(crypto,alias);
}
@@ -412,47 +393,28 @@ 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>();
attributeStatements.add(attributeStatement);
- Assertion assertion = SAMLUtils.createAssertion(config.issuerName, notBefore,
+ Assertion assertion = SAMLUtils.createAssertion(config.getIssuerName(), notBefore,
notAfter, attributeStatements);
SAMLUtils.signAssertion(assertion, crypto, config.getIssuerKeyAlias(), config.getIssuerKeyPassword());
@@ -485,7 +447,7 @@ public class SAMLTokenIssuer implements
Subject subject = SAMLUtils.createSubject(subjectNameId,confirmationMethod, keyInfo);
AuthenticationStatement authenticationStatement
- = SAMLUtils.createAuthenticationStatement(subject, AUTHENTICATION_METHOD_PASSWORD,
+ = SAMLUtils.createAuthenticationStatement(subject, RahasConstants.AUTHENTICATION_METHOD_PASSWORD,
notBefore);
List<Statement> statements = new ArrayList<Statement>();
@@ -498,7 +460,7 @@ public class SAMLTokenIssuer implements
statements.add(authenticationStatement);
- Assertion assertion = SAMLUtils.createAssertion(config.issuerName,
+ Assertion assertion = SAMLUtils.createAssertion(config.getIssuerName(),
notBefore, notAfter, statements);
// Signing the assertion
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuerConfig.java Mon Jan 30 17:50:58 2017
@@ -20,15 +20,18 @@ import org.apache.axiom.om.OMAbstractFac
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.OMXMLBuilderFactory;
+import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axis2.description.Parameter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.TrustException;
+import org.apache.rahas.TrustUtil;
import org.apache.rahas.impl.util.CommonUtil;
import org.apache.rahas.impl.util.SAMLCallbackHandler;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
+import org.apache.ws.security.components.crypto.CryptoFactory;
import javax.xml.namespace.QName;
import java.io.FileInputStream;
@@ -92,10 +95,12 @@ public class SAMLTokenIssuerConfig exten
public final static QName ISSUER_NAME = new QName("issuerName");
public final static QName SAML_CALLBACK_CLASS = new QName("dataCallbackHandlerClass");
-
+
protected String issuerKeyAlias;
protected String issuerKeyPassword;
protected String issuerName;
+
+ // TODO in next major release convert this to a typed map
protected Map trustedServices = new HashMap();
protected String trustStorePropFile;
protected SAMLCallbackHandler callbackHandler;
@@ -120,13 +125,13 @@ public class SAMLTokenIssuerConfig exten
*/
public SAMLTokenIssuerConfig(String configFilePath) throws TrustException {
FileInputStream fis;
- StAXOMBuilder builder;
+ OMXMLParserWrapper builder;
try {
fis = new FileInputStream(configFilePath);
- builder = new StAXOMBuilder(fis);
+ builder = OMXMLBuilderFactory.createOMBuilder(fis);
} catch (Exception e) {
throw new TrustException("errorLoadingConfigFile",
- new String[] { configFilePath });
+ new String[] { configFilePath }, e);
}
this.load(builder.getDocumentElement());
}
@@ -422,6 +427,14 @@ public class SAMLTokenIssuerConfig exten
return callbackHandler;
}
+ public String getIssuerName() {
+ return issuerName;
+ }
+
+ public String getTrustStorePropFile() {
+ return trustStorePropFile;
+ }
+
public void setCallbackHandler(SAMLCallbackHandler callbackHandler) {
this.callbackHandler = callbackHandler;
}
@@ -449,14 +462,50 @@ 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);
+ }
+
+ }
+
+ /**
+ * This method will create a Crypto object based on property values defined in cryptoElement or
+ * cryptoPropertiesFile.
+ * @param classLoader A class loader to pass into CryptoFactory.
+ * @return A Crypto object
+ * @throws TrustException If an error occurred while creating the Crypto object.
+ */
+ public Crypto getIssuerCrypto(ClassLoader classLoader) throws TrustException {
+
+ try {
+ if (this.cryptoElement != null) {
+ // crypto props defined as elements
+ return CryptoFactory.getInstance(TrustUtil
+ .toProperties(this.cryptoElement), classLoader);
+ } else {
+ // crypto props defined in a properties file
+ return CryptoFactory.getInstance(this.cryptoPropertiesFile,
+ classLoader);
+ }
+
+ } catch (WSSecurityException e) {
+ throw new TrustException("errorLoadingCryptoProperties", e);
}
}
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java Mon Jan 30 17:50:58 2017
@@ -88,16 +88,8 @@ public class SAMLTokenRenewer implements
wstVersion, rstrcElem);
}
- Crypto crypto;
ClassLoader classLoader = inMsgCtx.getAxisService().getClassLoader();
- if (config.cryptoElement != null) {
- // crypto props defined as elements
- crypto = CommonUtil.getCrypto(TrustUtil
- .toProperties(config.cryptoElement), classLoader);
- } else {
- // crypto props defined in a properties file
- crypto = CommonUtil.getCrypto(config.cryptoPropertiesFile, classLoader);
- }
+ Crypto crypto = config.getIssuerCrypto(classLoader);
// Create TokenType element
TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(
@@ -106,7 +98,7 @@ public class SAMLTokenRenewer implements
// Creation and expiration times
Date creationTime = new Date();
Date expirationTime = new Date();
- expirationTime.setTime(creationTime.getTime() + config.ttl);
+ expirationTime.setTime(creationTime.getTime() + config.getTtl());
// Use GMT time in milliseconds
DateFormat zulu = new XmlSchemaDateFormat();
@@ -124,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));
}
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenValidator.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenValidator.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenValidator.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenValidator.java Mon Jan 30 17:50:58 2017
@@ -184,7 +184,7 @@ public class SAMLTokenValidator implemen
inMsgCtx.getAxisService().getClassLoader());
}
- X509Certificate issuerCert = CommonUtil.getCertificateByAlias(crypto,config.issuerKeyAlias);
+ X509Certificate issuerCert = CommonUtil.getCertificateByAlias(crypto,config.getIssuerKeyAlias());
issuerPBKey = issuerCert.getPublicKey();
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SCTIssuer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SCTIssuer.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SCTIssuer.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SCTIssuer.java Mon Jan 30 17:50:58 2017
@@ -136,14 +136,14 @@ public class SCTIssuer implements TokenI
OMElement reqAttachedRef = null;
OMElement reqUnattachedRef = null;
- if (config.addRequestedAttachedRef) {
+ if (config.isAddRequestedAttachedRef()) {
reqAttachedRef = TrustUtil.createRequestedAttachedRef(wstVersion,
rstrElem,
"#" + sct.getID(),
tokenType);
}
- if (config.addRequestedUnattachedRef) {
+ if (config.isAddRequestedUnattachedRef()) {
reqUnattachedRef = TrustUtil.createRequestedUnattachedRef(wstVersion,
rstrElem,
sct.getIdentifier(),
@@ -154,7 +154,7 @@ public class SCTIssuer implements TokenI
Date creationTime = new Date();
Date expirationTime = new Date();
- expirationTime.setTime(creationTime.getTime() + config.ttl);
+ expirationTime.setTime(creationTime.getTime() + config.getTtl());
// Use GMT time in milliseconds
DateFormat zulu = new XmlSchemaDateFormat();
@@ -171,15 +171,15 @@ public class SCTIssuer implements TokenI
creationTime,
expirationTime);
- if(config.addRequestedAttachedRef) {
+ if(config.isAddRequestedAttachedRef()) {
sctToken.setAttachedReference(reqAttachedRef.getFirstElement());
}
- if(config.addRequestedUnattachedRef) {
+ if(config.isAddRequestedUnattachedRef()) {
sctToken.setUnattachedReference(reqUnattachedRef.getFirstElement());
}
- byte[] secret = TokenIssuerUtil.getSharedSecret(data, config.keyComputation, config.keySize);
+ byte[] secret = TokenIssuerUtil.getSharedSecret(data, config.getKeyComputation(), config.getKeySize());
sctToken.setSecret(secret);
//Add the RequestedProofToken
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SCTIssuerConfig.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SCTIssuerConfig.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SCTIssuerConfig.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SCTIssuerConfig.java Mon Jan 30 17:50:58 2017
@@ -17,7 +17,8 @@
package org.apache.rahas.impl;
import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.OMXMLBuilderFactory;
+import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.rahas.TrustException;
import javax.xml.namespace.QName;
@@ -68,10 +69,10 @@ public class SCTIssuerConfig extends Abs
public static SCTIssuerConfig load(String configFilePath)
throws TrustException {
FileInputStream fis;
- StAXOMBuilder builder;
+ OMXMLParserWrapper builder;
try {
fis = new FileInputStream(configFilePath);
- builder = new StAXOMBuilder(fis);
+ builder = OMXMLBuilderFactory.createOMBuilder(fis);
} catch (Exception e) {
throw new TrustException("errorLoadingConfigFile",
new String[] { configFilePath });
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/TokenCancelerConfig.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/TokenCancelerConfig.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/TokenCancelerConfig.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/TokenCancelerConfig.java Mon Jan 30 17:50:58 2017
@@ -16,7 +16,8 @@
package org.apache.rahas.impl;
import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axiom.om.OMXMLBuilderFactory;
+import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.rahas.TrustException;
import javax.xml.namespace.QName;
@@ -68,10 +69,10 @@ public class TokenCancelerConfig {
public static TokenCancelerConfig load(String configFilePath)
throws TrustException {
FileInputStream fis;
- StAXOMBuilder builder;
+ OMXMLParserWrapper builder;
try {
fis = new FileInputStream(configFilePath);
- builder = new StAXOMBuilder(fis);
+ builder = OMXMLBuilderFactory.createOMBuilder(fis);
} catch (Exception e) {
throw new TrustException("errorLoadingConfigFile", new String[] { configFilePath });
}
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/TokenIssuerUtil.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/TokenIssuerUtil.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/TokenIssuerUtil.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/TokenIssuerUtil.java Mon Jan 30 17:50:58 2017
@@ -18,7 +18,7 @@ package org.apache.rahas.impl;
import java.security.SecureRandom;
import org.apache.axiom.om.OMElement;
-import org.apache.axiom.om.util.Base64;
+import org.apache.axiom.util.base64.Base64Utils;
import org.apache.rahas.RahasConstants;
import org.apache.rahas.RahasData;
import org.apache.rahas.Token;
@@ -94,7 +94,7 @@ public class TokenIssuerUtil {
//set the RPT to include a ComputedKey element
OMElement respEntrElem = TrustUtil.createEntropyElement(wstVersion, rstrElem);
- String entr = Base64.encode(data.getResponseEntropy());
+ String entr = Base64Utils.encode(data.getResponseEntropy());
OMElement binSecElem = TrustUtil.createBinarySecretElement(wstVersion,
respEntrElem,
RahasConstants.BIN_SEC_TYPE_NONCE);
@@ -141,7 +141,7 @@ public class TokenIssuerUtil {
OMElement binSecElem = TrustUtil.createBinarySecretElement(wstVersion,
reqProofTokElem,
null);
- binSecElem.setText(Base64.encode(secret));
+ binSecElem.setText(Base64Utils.encode(secret));
token.setSecret(secret);
} else {
throw new IllegalArgumentException(config.proofKeyType);
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/AxiomParserPool.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/AxiomParserPool.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/AxiomParserPool.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/AxiomParserPool.java Mon Jan 30 17:50:58 2017
@@ -30,7 +30,7 @@ import org.opensaml.xml.parse.ParserPool
import org.opensaml.xml.parse.StaticBasicParserPool;
/**
- * Custom OpenSAML 1.x {@link ParserPool} implementation that uses a DOM aware Axiom implementation
+ * Custom OpenSAML {@link ParserPool} implementation that uses a DOM aware Axiom implementation
* instead of requesting a {@link DocumentBuilderFactory} using JAXP.
*/
public class AxiomParserPool extends StaticBasicParserPool {
Modified: axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java Mon Jan 30 17:50:58 2017
@@ -17,28 +17,42 @@
package org.apache.rahas.impl.util;
import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.dom.DOMMetaFactory;
+import org.apache.axis2.context.MessageContext;
+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.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.SAMLTokenIssuerConfig;
+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;
@@ -126,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();
@@ -139,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);
@@ -185,4 +196,282 @@ public class CommonUtil {
}
}
+
+ /**
+ * Creates the token issuer configuration. The configuration is created in following order,
+ * 1. Try create token configuration using configuration OMElement
+ * 2. Try create token configuration using a configuration file name
+ * 3. Try create token configuration using a parameter name in message context.
+ * The issuer configuration would look like as follows,
+ *
+ * <saml-issuer-config>
+ * <issuerName>Test_STS</issuerName>
+ * <issuerKeyAlias>ip</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">META-INF/rahas-sts.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="bob">http://localhost:8080/axis2/services/STS</service>
+ * </trusted-services>
+ * </saml-issuer-config>
+ *
+ * @param configElement Configuration as an OMElement.
+ * @param configFile Configuration as a file.
+ * @param messageContextParameter Configuration as a message context parameter.
+ * @return Token issuer configuration as a SAMLTokenIssuerConfig object.
+ * @throws TrustException If an error occurred while creating SAMLTokenIssuerConfig object.
+ */
+ public static SAMLTokenIssuerConfig getTokenIssuerConfiguration(OMElement configElement, String configFile,
+ Parameter messageContextParameter) throws TrustException {
+
+ // First try using configuration element
+ SAMLTokenIssuerConfig tokenIssuerConfiguration = createTokenIssuerConfiguration(configElement);
+
+ if (tokenIssuerConfiguration == null) {
+
+ // Now try file
+ tokenIssuerConfiguration = createTokenIssuerConfiguration(configFile);
+
+ if (tokenIssuerConfiguration == null) {
+
+ // Finally try using the parameter
+ if (messageContextParameter != null) {
+ tokenIssuerConfiguration = createTokenIssuerConfiguration(messageContextParameter);
+ }
+
+ return tokenIssuerConfiguration;
+ } else {
+ return tokenIssuerConfiguration;
+ }
+
+ } else {
+ return tokenIssuerConfiguration;
+ }
+ }
+
+ protected static SAMLTokenIssuerConfig createTokenIssuerConfiguration(OMElement configElement)
+ throws TrustException {
+
+ if (configElement != null) {
+
+ log.debug("Creating token issuer configuration using OMElement");
+
+ return new SAMLTokenIssuerConfig(configElement
+ .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
+ }
+
+ return null;
+ }
+
+ protected static SAMLTokenIssuerConfig createTokenIssuerConfiguration(String configFile) throws TrustException {
+
+ if (configFile != null) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Creating token issuer configuration using file " + configFile);
+ }
+
+ return new SAMLTokenIssuerConfig(configFile);
+ }
+
+ return null;
+ }
+
+ protected static SAMLTokenIssuerConfig createTokenIssuerConfiguration(Parameter messageContextParameter)
+ throws TrustException {
+
+ if (messageContextParameter != null && messageContextParameter.getParameterElement() != null) {
+
+ log.debug("Creating token issuer configuration using the config parameter");
+
+ return new SAMLTokenIssuerConfig(messageContextParameter
+ .getParameterElement().getFirstChildWithName(
+ SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
+ }
+
+ 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/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java Mon Jan 30 17:50:58 2017
@@ -1,5 +1,5 @@
/*
- * Copyright 2004,2005 The Apache Software Foundation.
+ * Copyright The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,31 +17,34 @@
package org.apache.rahas.impl.util;
-import org.apache.axiom.om.impl.dom.jaxp.DocumentBuilderFactoryImpl;
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.dom.DOMMetaFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.RahasConstants;
import org.apache.rahas.TrustException;
import org.apache.ws.security.*;
import org.apache.ws.security.components.crypto.Crypto;
-import org.apache.ws.security.handler.RequestData;
-import org.apache.ws.security.processor.EncryptedKeyProcessor;
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;
import org.opensaml.xml.io.*;
-import org.w3c.dom.*;
-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 org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import javax.security.auth.callback.Callback;
@@ -51,10 +54,8 @@ import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.cert.X509Certificate;
-import java.util.Iterator;
import java.util.List;
public class SAML2Utils {
@@ -64,41 +65,10 @@ public class SAML2Utils {
public static Element getElementFromAssertion(XMLObject xmlObj) throws TrustException {
try {
- String jaxpProperty = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
- //System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
-
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObj);
- Element element = marshaller.marshall(xmlObj);
-
- // Reset the sys. property to its previous value.
- if (jaxpProperty == null) {
- System.getProperties().remove("javax.xml.parsers.DocumentBuilderFactory");
- } else {
- System.setProperty("javax.xml.parsers.DocumentBuilderFactory", jaxpProperty);
- }
-
- ByteArrayOutputStream byteArrayOutputStrm = new ByteArrayOutputStream();
-
- DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
-
- DOMImplementationLS impl =
- (DOMImplementationLS) registry.getDOMImplementation("LS");
-
- LSSerializer writer = impl.createLSSerializer();
- LSOutput output = impl.createLSOutput();
- output.setByteStream(byteArrayOutputStrm);
- writer.write(element, output);
- String elementString = byteArrayOutputStrm.toString();
-
- DocumentBuilderFactoryImpl.setDOOMRequired(true);
-
- DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
- documentBuilderFactory.setNamespaceAware(true);
- DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();
- Document document = docBuilder.parse(new ByteArrayInputStream(elementString.trim().getBytes()));
- Element assertionElement = document.getDocumentElement();
- DocumentBuilderFactoryImpl.setDOOMRequired(false);
+ Element assertionElement = marshaller.marshall(xmlObj,
+ ((DOMMetaFactory)OMAbstractFactory.getMetaFactory(OMAbstractFactory.FEATURE_DOM)).newDocumentBuilderFactory().newDocumentBuilder().newDocument());
log.debug("DOM element is created successfully from the OpenSAML2 XMLObject");
return assertionElement;
@@ -108,16 +78,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.
@@ -186,7 +158,7 @@ public class SAML2Utils {
}
// extract the subject confirmation element from the subject
- SubjectConfirmation subjectConf = (SubjectConfirmation) samlSubject.getSubjectConfirmations().get(0);
+ SubjectConfirmation subjectConf = samlSubject.getSubjectConfirmations().get(0);
if (subjectConf == null) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"invalidSAML2Token", new Object[]{"for Signature (no Subject Confirmation)"});
@@ -203,9 +175,7 @@ public class SAML2Utils {
// Get the SAML specific XML representation of the keyInfo object
XMLObject KIElem = null;
List<XMLObject> scDataElements = scData.getOrderedChildren();
- Iterator<XMLObject> iterator = scDataElements.iterator();
- while (iterator.hasNext()) {
- XMLObject xmlObj = iterator.next();
+ for (XMLObject xmlObj : scDataElements) {
if (xmlObj instanceof org.opensaml.xml.signature.KeyInfo) {
KIElem = xmlObj;
break;
@@ -217,20 +187,14 @@ public class SAML2Utils {
// Generate a DOM element from the XMLObject.
if (KIElem != null) {
- // Set the "javax.xml.parsers.DocumentBuilderFactory" system property to make sure the endorsed JAXP
- // implementation is picked over the default jaxp impl shipped with the JDK.
- String jaxpProperty = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
- //System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
-
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(KIElem);
- keyInfoElement = marshaller.marshall(KIElem);
-
- // Reset the sys. property to its previous value.
- if (jaxpProperty == null) {
- System.getProperties().remove("javax.xml.parsers.DocumentBuilderFactory");
- } else {
- System.setProperty("javax.xml.parsers.DocumentBuilderFactory", jaxpProperty);
+ try {
+ keyInfoElement = marshaller.marshall(KIElem,
+ ((DOMMetaFactory)OMAbstractFactory.getMetaFactory(OMAbstractFactory.FEATURE_DOM)).newDocumentBuilderFactory().newDocumentBuilder().newDocument());
+ } catch (ParserConfigurationException ex) {
+ // We never get here
+ throw new Error(ex);
}
} else {
@@ -239,9 +203,9 @@ public class SAML2Utils {
}
AttributeStatement attrStmt = assertion.getAttributeStatements().size() != 0 ?
- (AttributeStatement) assertion.getAttributeStatements().get(0) : null;
+ assertion.getAttributeStatements().get(0) : null;
AuthnStatement authnStmt = assertion.getAuthnStatements().size() != 0 ?
- (AuthnStatement) assertion.getAuthnStatements().get(0) : null;
+ assertion.getAuthnStatements().get(0) : null;
// if an attr stmt is present, then it has a symmetric key.
if (attrStmt != null) {
@@ -270,7 +234,7 @@ public class SAML2Utils {
// If an authn stmt is present then it has a public key.
if (authnStmt != null) {
- X509Certificate[] certs = null;
+ X509Certificate[] certs;
try {
KeyInfo ki = new KeyInfo(keyInfoElement, null);
@@ -323,6 +287,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/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLUtils.java Mon Jan 30 17:50:58 2017
@@ -1,13 +1,10 @@
package org.apache.rahas.impl.util;
+import org.apache.axiom.util.UIDGenerator;
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 +16,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;
@@ -31,12 +26,9 @@ import org.opensaml.xml.schema.impl.XSSt
import org.opensaml.xml.security.SecurityHelper;
import org.opensaml.xml.security.credential.Credential;
import org.opensaml.xml.signature.*;
-import org.opensaml.xml.signature.KeyInfo;
-import org.opensaml.xml.signature.X509Data;
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 +45,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 +59,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 +113,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 +176,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 +185,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 +209,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 +231,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 +269,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 +306,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 +353,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 +373,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);
@@ -408,7 +385,7 @@ public class SAMLUtils {
* This method creates the final SAML assertion. The final SAML assertion would looks like as follows,
* <saml:Assertion AssertionID="_a75adf55-01d7-40cc-929f-dbd8372ebdfc"
* IssueInstant="2003-04-17T00:46:02Z"
- * Issuer=”www.opensaml.org”
+ * Issuer="www.opensaml.org"
* MajorVersion="1"
* MinorVersion="1"
* xmlns="urn:oasis:names:tc:SAML:1.0:assertion">
@@ -453,12 +430,13 @@ 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));
assertion.getStatements().addAll(statements);
-
+ assertion.setID(UIDGenerator.generateUID());
+ assertion.setIssueInstant(new DateTime());
return assertion;
}
@@ -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,127 +521,8 @@ 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,
@@ -699,14 +558,14 @@ 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
keyIdentifier.setEncodingType(KeyIdentifier.ENCODING_TYPE_BASE64_BINARY);
- keyIdentifier.setValueType(WSSecurityConstants.THUMB_PRINT_SHA1);
+ keyIdentifier.setValueType(WSSecurityConstants.WS_SECURITY11_NS+"#ThumbprintSHA1");
keyIdentifier.setValue(getThumbprintSha1(certificate));
securityTokenReference.getUnknownXMLObjects().add(keyIdentifier);
@@ -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/branches/RAMPART-289/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java?rev=1780953&r1=1780952&r2=1780953&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java (original)
+++ axis/axis2/java/rampart/branches/RAMPART-289/modules/rampart-trust/src/test/java/org/apache/rahas/impl/SAML2TokenIssuerTest.java Mon Jan 30 17:50:58 2017
@@ -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()
- }
}