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/02/29 11:45:39 UTC
svn commit: r1295060 [2/3] - in /axis/axis2/java/rampart/branches/1_6: ./
modules/rampart-core/src/main/java/org/apache/rampart/
modules/rampart-core/src/main/java/org/apache/rampart/saml/
modules/rampart-integration/src/test/java/org/apache/rahas/ mod...
Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java?rev=1295060&r1=1295059&r2=1295060&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenIssuer.java Wed Feb 29 10:45:37 2012
@@ -18,10 +18,11 @@ package org.apache.rahas.impl;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
-import org.apache.axiom.om.impl.dom.jaxp.DocumentBuilderFactoryImpl;
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;
import org.apache.rahas.RahasData;
import org.apache.rahas.Token;
@@ -31,37 +32,38 @@ import org.apache.rahas.TrustUtil;
import org.apache.rahas.impl.util.SAMLAttributeCallback;
import org.apache.rahas.impl.util.SAMLCallbackHandler;
import org.apache.rahas.impl.util.SAMLNameIdentifierCallback;
-import org.apache.ws.security.WSConstants;
+import org.apache.rahas.impl.util.SAMLUtils;
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.message.WSSecEncryptedKey;
import org.apache.ws.security.util.Base64;
import org.apache.ws.security.util.Loader;
import org.apache.ws.security.util.XmlSchemaDateFormat;
import org.apache.xml.security.signature.XMLSignature;
-import org.apache.xml.security.utils.EncryptionConstants;
-import org.opensaml.SAMLAssertion;
-import org.opensaml.SAMLAttribute;
-import org.opensaml.SAMLAttributeStatement;
-import org.opensaml.SAMLAuthenticationStatement;
-import org.opensaml.SAMLException;
-import org.opensaml.SAMLNameIdentifier;
-import org.opensaml.SAMLStatement;
-import org.opensaml.SAMLSubject;
+
+import org.joda.time.DateTime;
+import org.opensaml.common.SAMLException;
+import org.opensaml.saml1.core.*;
+import org.opensaml.xml.security.*;
+import org.opensaml.xml.security.SecurityException;
+import org.opensaml.xml.security.credential.Credential;
+import org.opensaml.xml.signature.KeyInfo;
+import org.opensaml.xml.signature.Signature;
+import org.opensaml.xml.signature.SignatureException;
+import org.opensaml.xml.signature.Signer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
-import org.w3c.dom.Text;
import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Date;
import java.util.List;
/**
@@ -75,273 +77,285 @@ public class SAMLTokenIssuer implements
private String configFile;
- public SOAPEnvelope issue(RahasData data) throws TrustException {
- try {
- MessageContext inMsgCtx = data.getInMessageContext();
+ //TODO move this to TrustUtil
+ private static final String AUTHENTICATION_METHOD_PASSWORD = "urn:oasis:names:tc:SAML:1.0:am:password";
- 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 });
- }
- }
+ private static final Log log = LogFactory.getLog(SAMLTokenIssuer.class);
- if (config == null) {
- throw new TrustException("configurationIsNull");
- }
+ public SOAPEnvelope issue(RahasData data) throws TrustException {
+ MessageContext inMsgCtx = data.getInMessageContext();
- // Set the DOM impl to DOOM
- DocumentBuilderFactoryImpl.setDOOMRequired(true);
+ SAMLTokenIssuerConfig config = null;
+ if (this.configElement != null) {
+ config = new SAMLTokenIssuerConfig(configElement
+ .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
+ }
- SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx
- .getEnvelope().getNamespace().getNamespaceURI());
-
- Crypto crypto;
- if (config.cryptoElement != null) { // crypto props
- // defined as
- // elements
- crypto = CryptoFactory.getInstance(TrustUtil
- .toProperties(config.cryptoElement), inMsgCtx
- .getAxisService().getClassLoader());
- } else { // crypto props defined in a properties file
- crypto = CryptoFactory.getInstance(config.cryptoPropertiesFile,
- inMsgCtx.getAxisService().getClassLoader());
- }
-
- // Creation and expiration times
- Date creationTime = new Date();
- Date expirationTime = new Date();
- expirationTime.setTime(creationTime.getTime() + config.ttl);
-
- // Get the document
- Document doc = ((Element) env).getOwnerDocument();
-
- // Get the key size and create a new byte array of that size
- int keySize = data.getKeysize();
-
- keySize = (keySize == -1) ? config.keySize : keySize;
-
- /*
- * Find the KeyType If the KeyType is SymmetricKey or PublicKey,
- * issue a SAML HoK assertion. - In the case of the PublicKey, in
- * coming security header MUST contain a certificate (maybe via
- * signature)
- *
- * If the KeyType is Bearer then issue a Bearer assertion
- *
- * If the key type is missing we will issue a HoK assertion
- */
-
- String keyType = data.getKeyType();
- SAMLAssertion assertion;
- if (keyType == null) {
- throw new TrustException(TrustException.INVALID_REQUEST,
- new String[] { "Requested KeyType is missing" });
- }
-
- if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
- || keyType.endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) {
- assertion = createHoKAssertion(config, doc, crypto,
- creationTime, expirationTime, data);
- } else if (keyType.endsWith(RahasConstants.KEY_TYPE_BEARER)) {
- assertion = createBearerAssertion(config, doc, crypto,
- creationTime, expirationTime, data);
- } else {
- throw new TrustException("unsupportedKeyType");
- }
+ // Look for the file
+ if (config == null && this.configFile != null) {
+ config = new SAMLTokenIssuerConfig(this.configFile);
+ }
- OMElement rstrElem;
- int wstVersion = data.getVersion();
- if (RahasConstants.VERSION_05_02 == wstVersion) {
- rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
- wstVersion, env.getBody());
+ // 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 {
- OMElement rstrcElem = TrustUtil
- .createRequestSecurityTokenResponseCollectionElement(
- wstVersion, env.getBody());
- rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
- wstVersion, rstrcElem);
+ throw new TrustException("expectedParameterMissing",
+ new String[] { this.configParamName });
}
+ }
- TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(
- RahasConstants.TOK_TYPE_SAML_10);
+ if (config == null) {
+ throw new TrustException("configurationIsNull");
+ }
- if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
- TrustUtil.createKeySizeElement(wstVersion, rstrElem, keySize);
- }
+ SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx
+ .getEnvelope().getNamespace().getNamespaceURI());
- if (config.addRequestedAttachedRef) {
- TrustUtil.createRequestedAttachedRef(rstrElem, assertion.getId(),wstVersion);
- }
+ Crypto crypto;
+ if (config.cryptoElement != null) { // crypto props
+ // defined as
+ // elements
+ crypto = CryptoFactory.getInstance(TrustUtil
+ .toProperties(config.cryptoElement), inMsgCtx
+ .getAxisService().getClassLoader());
+ } else { // crypto props defined in a properties file
+ crypto = CryptoFactory.getInstance(config.cryptoPropertiesFile,
+ inMsgCtx.getAxisService().getClassLoader());
+ }
- if (config.addRequestedUnattachedRef) {
- TrustUtil.createRequestedUnattachedRef(rstrElem, assertion.getId(),wstVersion);
- }
+ // Creation and expiration times
+ DateTime creationTime = new DateTime();
+ DateTime expirationTime = new DateTime(creationTime.getMillis() + config.ttl);
+
+ // Get the document
+ Document doc = ((Element) env).getOwnerDocument();
+
+ // Get the key size and create a new byte array of that size
+ int keySize = data.getKeysize();
+
+ keySize = (keySize == -1) ? config.keySize : keySize;
+
+ /*
+ * Find the KeyType If the KeyType is SymmetricKey or PublicKey,
+ * issue a SAML HoK assertion. - In the case of the PublicKey, in
+ * coming security header MUST contain a certificate (maybe via
+ * signature)
+ *
+ * If the KeyType is Bearer then issue a Bearer assertion
+ *
+ * If the key type is missing we will issue a HoK assertion
+ */
+
+ String keyType = data.getKeyType();
+ Assertion assertion;
+ if (keyType == null) {
+ throw new TrustException(TrustException.INVALID_REQUEST,
+ new String[] { "Requested KeyType is missing" });
+ }
- if (data.getAppliesToAddress() != null) {
- TrustUtil.createAppliesToElement(rstrElem, data
- .getAppliesToAddress(), data.getAddressingNs());
- }
+ if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
+ || keyType.endsWith(RahasConstants.KEY_TYPE_PUBLIC_KEY)) {
+ assertion = createHoKAssertion(config, doc, crypto,
+ creationTime, expirationTime, data);
+ } else if (keyType.endsWith(RahasConstants.KEY_TYPE_BEARER)) {
+ assertion = createBearerAssertion(config, doc, crypto,
+ creationTime, expirationTime, data);
+ } else {
+ throw new TrustException("unsupportedKeyType");
+ }
- // Use GMT time in milliseconds
- DateFormat zulu = new XmlSchemaDateFormat();
+ OMElement rstrElem;
+ int wstVersion = data.getVersion();
+ if (RahasConstants.VERSION_05_02 == wstVersion) {
+ rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
+ wstVersion, env.getBody());
+ } else {
+ OMElement rstrcElem = TrustUtil
+ .createRequestSecurityTokenResponseCollectionElement(
+ wstVersion, env.getBody());
+ rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
+ wstVersion, rstrcElem);
+ }
- // Add the Lifetime element
- TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu
- .format(creationTime), zulu.format(expirationTime));
+ TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(
+ RahasConstants.TOK_TYPE_SAML_10);
- // Create the RequestedSecurityToken element and add the SAML token
- // to it
- OMElement reqSecTokenElem = TrustUtil
- .createRequestedSecurityTokenElement(wstVersion, rstrElem);
- Token assertionToken;
- try {
- Node tempNode = assertion.toDOM();
- reqSecTokenElem.addChild((OMNode) ((Element) rstrElem)
- .getOwnerDocument().importNode(tempNode, true));
-
- // Store the token
- assertionToken = new Token(assertion.getId(),
- (OMElement) assertion.toDOM(), creationTime,
- expirationTime);
-
- // At this point we definitely have the secret
- // Otherwise it should fail with an exception earlier
- assertionToken.setSecret(data.getEphmeralKey());
- TrustUtil.getTokenStore(inMsgCtx).add(assertionToken);
+ if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
+ TrustUtil.createKeySizeElement(wstVersion, rstrElem, keySize);
+ }
- } catch (SAMLException e) {
- throw new TrustException("samlConverstionError", e);
- }
+ if (config.addRequestedAttachedRef) {
+ TrustUtil.createRequestedAttachedRef(rstrElem, assertion.getID(),wstVersion);
+ }
- if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
- && config.keyComputation != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {
+ if (config.addRequestedUnattachedRef) {
+ TrustUtil.createRequestedUnattachedRef(rstrElem, assertion.getID(),wstVersion);
+ }
- // Add the RequestedProofToken
- TokenIssuerUtil.handleRequestedProofToken(data, wstVersion,
- config, rstrElem, assertionToken, doc);
- }
+ if (data.getAppliesToAddress() != null) {
+ TrustUtil.createAppliesToElement(rstrElem, data
+ .getAppliesToAddress(), data.getAddressingNs());
+ }
+
+ // Use GMT time in milliseconds
+ DateFormat zulu = new XmlSchemaDateFormat();
- return env;
- } finally {
- // Unset the DOM impl to default
- DocumentBuilderFactoryImpl.setDOOMRequired(false);
+ // Add the Lifetime element
+ TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu
+ .format(creationTime.toDate()), zulu.format(expirationTime.toDate()));
+
+ // Create the RequestedSecurityToken element and add the SAML token
+ // to it
+ OMElement reqSecTokenElem = TrustUtil
+ .createRequestedSecurityTokenElement(wstVersion, rstrElem);
+ Token assertionToken;
+ //try {
+ Node tempNode = assertion.getDOM();
+ reqSecTokenElem.addChild((OMNode) ((Element) rstrElem)
+ .getOwnerDocument().importNode(tempNode, true));
+
+ // Store the token
+ assertionToken = new Token(assertion.getID(),
+ (OMElement) assertion.getDOM(), creationTime.toDate(),
+ expirationTime.toDate());
+
+ // At this point we definitely have the secret
+ // Otherwise it should fail with an exception earlier
+ assertionToken.setSecret(data.getEphmeralKey());
+ TrustUtil.getTokenStore(inMsgCtx).add(assertionToken);
+
+ /* } catch (SAMLException e) {
+ throw new TrustException("samlConverstionError", e);
+ }*/
+
+ if (keyType.endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)
+ && config.keyComputation != SAMLTokenIssuerConfig.KeyComputation.KEY_COMP_USE_REQ_ENT) {
+
+ // Add the RequestedProofToken
+ TokenIssuerUtil.handleRequestedProofToken(data, wstVersion,
+ config, rstrElem, assertionToken, doc);
}
+ return env;
}
- private SAMLAssertion createBearerAssertion(SAMLTokenIssuerConfig config,
- Document doc, Crypto crypto, Date creationTime,
- Date expirationTime, RahasData data) throws TrustException {
- try {
- Principal principal = data.getPrincipal();
- SAMLAssertion assertion;
- // In the case where the principal is a UT
- if (principal instanceof WSUsernameTokenPrincipal) {
- SAMLNameIdentifier nameId = null;
- if(config.getCallbackHandler() != null){
- SAMLNameIdentifierCallback cb = new SAMLNameIdentifierCallback(data);
- cb.setUserId(principal.getName());
- SAMLCallbackHandler callbackHandler = config.getCallbackHandler();
- callbackHandler.handle(cb);
- nameId = cb.getNameId();
- }else{
- nameId = new SAMLNameIdentifier(
- principal.getName(), null, SAMLNameIdentifier.FORMAT_EMAIL);
- }
- assertion = createAuthAssertion(doc, SAMLSubject.CONF_BEARER,
- nameId, null, config, crypto, creationTime,
- expirationTime, data);
- return assertion;
+
+
+ private Assertion createBearerAssertion(SAMLTokenIssuerConfig config,
+ Document doc, Crypto crypto, DateTime creationTime,
+ DateTime expirationTime, RahasData data) throws TrustException {
+
+ Principal principal = data.getPrincipal();
+ Assertion assertion;
+ // In the case where the principal is a UT
+ if (principal instanceof WSUsernameTokenPrincipal) {
+ NameIdentifier nameId = null;
+ if (config.getCallbackHandler() != null) {
+ SAMLNameIdentifierCallback cb = new SAMLNameIdentifierCallback(data);
+ cb.setUserId(principal.getName());
+ SAMLCallbackHandler callbackHandler = config.getCallbackHandler();
+ try {
+ callbackHandler.handle(cb);
+ } catch (SAMLException e) {
+ throw new TrustException("unableToRetrieveCallbackHandler", e);
+ }
+ nameId = cb.getNameId();
} else {
- throw new TrustException("samlUnsupportedPrincipal",
- new String[] { principal.getClass().getName() });
+
+ nameId = SAMLUtils.createNamedIdentifier(principal.getName(), NameIdentifier.EMAIL);
}
- } catch (SAMLException e) {
- throw new TrustException("samlAssertionCreationError", e);
+
+ assertion = createAuthAssertion(RahasConstants.SAML11_SUBJECT_CONFIRMATION_BEARER,
+ nameId, null, config, crypto, creationTime,
+ expirationTime, data);
+ return assertion;
+ } else {
+ throw new TrustException("samlUnsupportedPrincipal",
+ new String[]{principal.getClass().getName()});
}
}
- private SAMLAssertion createHoKAssertion(SAMLTokenIssuerConfig config,
- Document doc, Crypto crypto, Date creationTime,
- Date expirationTime, RahasData data) throws TrustException {
+ private Assertion createHoKAssertion(SAMLTokenIssuerConfig config,
+ Document doc, Crypto crypto, DateTime creationTime,
+ DateTime expirationTime, RahasData data) throws TrustException {
if (data.getKeyType().endsWith(RahasConstants.KEY_TYPE_SYMM_KEY)) {
- Element encryptedKeyElem;
X509Certificate serviceCert = null;
try {
+ // TODO what if principal is null ?
+ NameIdentifier nameIdentifier = null;
+ if (data.getPrincipal() != null) {
+ String subjectNameId = data.getPrincipal().getName();
+ nameIdentifier =SAMLUtils.createNamedIdentifier(subjectNameId, NameIdentifier.EMAIL);
+ }
+
+ /**
+ * In this case we need to create a KeyInfo similar to following,
+ * * <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
+ * <xenc:EncryptedKey xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
+ * ....
+ * </xenc:EncryptedKey>
+ * </ds:KeyInfo>
+ */
+
// Get ApliesTo to figure out which service to issue the token
// for
serviceCert = getServiceCert(config, crypto, data
.getAppliesToAddress());
- // Create the encrypted key
- WSSecEncryptedKey encrKeyBuilder = new WSSecEncryptedKey();
-
- // Use thumbprint id
- encrKeyBuilder
- .setKeyIdentifierType(WSConstants.THUMBPRINT_IDENTIFIER);
+ // set keySize
+ int keySize = data.getKeysize();
+ keySize = (keySize != -1) ? keySize : config.keySize;
- // SEt the encryption cert
- encrKeyBuilder.setUseThisCert(serviceCert);
-
- // set keysize
- int keysize = data.getKeysize();
- keysize = (keysize != -1) ? keysize : config.keySize;
- encrKeyBuilder.setKeySize(keysize);
-
- encrKeyBuilder.setEphemeralKey(TokenIssuerUtil.getSharedSecret(
- data, config.keyComputation, keysize));
+ // Create the encrypted key
+ KeyInfo encryptedKeyInfoElement
+ = SAMLUtils.getSymmetricKeyBasedKeyInfo(doc, data, serviceCert, keySize,
+ crypto, config.keyComputation);
- // Set key encryption algo
- encrKeyBuilder
- .setKeyEncAlgo(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSA15);
+ return this.createAttributeAssertion(data, encryptedKeyInfoElement, nameIdentifier, config,
+ crypto, creationTime, expirationTime);
- // Build
- encrKeyBuilder.prepare(doc, crypto);
- // Extract the base64 encoded secret value
- byte[] tempKey = new byte[keysize / 8];
- System.arraycopy(encrKeyBuilder.getEphemeralKey(), 0, tempKey,
- 0, keysize / 8);
+ } catch (WSSecurityException e) {
- data.setEphmeralKey(tempKey);
+ if (serviceCert != null) {
+ throw new TrustException(
+ "errorInBuildingTheEncryptedKeyForPrincipal",
+ new String[]{serviceCert.getSubjectDN().getName()},
+ e);
+ } else {
+ throw new TrustException(
+ "trustedCertNotFoundForEPR",
+ new String[]{data.getAppliesToAddress()},
+ e);
+ }
- // Extract the Encryptedkey DOM element
- encryptedKeyElem = encrKeyBuilder.getEncryptedKeyElement();
- } catch (WSSecurityException e) {
- throw new TrustException(
- "errorInBuildingTheEncryptedKeyForPrincipal",
- new String[] { serviceCert.getSubjectDN().getName() },
- e);
}
- return this.createAttributeAssertion(doc, data ,encryptedKeyElem, config,
- crypto, creationTime, expirationTime);
} else {
try {
+
+ /**
+ * In this case we need to create KeyInfo as follows,
+ * <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
+ * <X509Data xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
+ * xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
+ * <X509Certificate>
+ * MIICNTCCAZ6gAwIBAgIES343....
+ * </X509Certificate>
+ * </X509Data>
+ * </KeyInfo>
+ */
+
String subjectNameId = data.getPrincipal().getName();
- SAMLNameIdentifier nameId = new SAMLNameIdentifier(
- subjectNameId, null, SAMLNameIdentifier.FORMAT_EMAIL);
+ NameIdentifier nameId = SAMLUtils.createNamedIdentifier(subjectNameId, NameIdentifier.EMAIL);
// Create the ds:KeyValue element with the ds:X509Data
X509Certificate clientCert = data.getClientCert();
@@ -352,20 +366,9 @@ public class SAMLTokenIssuer implements
clientCert = certs[0];
}
- byte[] clientCertBytes = clientCert.getEncoded();
-
- String base64Cert = Base64.encode(clientCertBytes);
+ KeyInfo keyInfo = SAMLUtils.getCertificateBasedKeyInfo(clientCert);
- Text base64CertText = doc.createTextNode(base64Cert);
- Element x509CertElem = doc.createElementNS(WSConstants.SIG_NS,
- "X509Certificate");
- x509CertElem.appendChild(base64CertText);
- Element x509DataElem = doc.createElementNS(WSConstants.SIG_NS,
- "X509Data");
- x509DataElem.appendChild(x509CertElem);
-
- return this.createAuthAssertion(doc,
- SAMLSubject.CONF_HOLDER_KEY, nameId, x509DataElem,
+ return this.createAuthAssertion(RahasConstants.SAML11_SUBJECT_CONFIRMATION_HOK, nameId, keyInfo,
config, crypto, creationTime, expirationTime, data);
} catch (Exception e) {
throw new TrustException("samlAssertionCreationError", e);
@@ -405,90 +408,69 @@ public class SAMLTokenIssuer implements
/**
* Create the SAML assertion with the secret held in an
* <code>xenc:EncryptedKey</code>
- *
- * @param doc
- * @param keyInfoContent
- * @param config
- * @param crypto
- * @param notBefore
- * @param notAfter
- * @return
- * @throws TrustException
+ * @param data The Rahas configurations, this is needed to get the callbacks.
+ * @param keyInfo OpenSAML KeyInfo representation.
+ * @param subjectNameId Principal as an OpenSAML Subject
+ * @param config SAML Token issuer configurations.
+ * @param crypto To get certificate information.
+ * @param notBefore Validity period start.
+ * @param notAfter Validity period end
+ * @return OpenSAML Assertion object.
+ * @throws TrustException If an error occurred while creating the Assertion.
*/
- private SAMLAssertion createAttributeAssertion(Document doc, RahasData data,
- Element keyInfoContent, SAMLTokenIssuerConfig config,
- Crypto crypto, Date notBefore, Date notAfter) throws TrustException {
+ private Assertion createAttributeAssertion(RahasData data,
+ KeyInfo keyInfo, NameIdentifier subjectNameId,
+ SAMLTokenIssuerConfig config,
+ Crypto crypto, DateTime notBefore, DateTime notAfter) throws TrustException {
try {
- String[] confirmationMethods = new String[] { SAMLSubject.CONF_HOLDER_KEY };
- Element keyInfoElem = doc.createElementNS(WSConstants.SIG_NS,
- "KeyInfo");
- ((OMElement) keyInfoContent).declareNamespace(WSConstants.SIG_NS,
- WSConstants.SIG_PREFIX);
- ((OMElement) keyInfoContent).declareNamespace(WSConstants.ENC_NS,
- WSConstants.ENC_PREFIX);
-
- keyInfoElem.appendChild(keyInfoContent);
-
- SAMLSubject subject = new SAMLSubject(null, Arrays
- .asList(confirmationMethods), null, keyInfoElem);
-
-
- SAMLAttribute[] attrs = null;
- if(config.getCallbackHandler() != null){
- SAMLAttributeCallback cb = new SAMLAttributeCallback(data);
- SAMLCallbackHandler handler = config.getCallbackHandler();
- handler.handle(cb);
- attrs = cb.getAttributes();
+ 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 = null;
- try {
- cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
- } catch (ClassNotFoundException e) {
- throw new TrustException("cannotLoadPWCBClass", new String[]{config
- .getCallbackHandlerName()}, e);
- }
- try {
- handler = (SAMLCallbackHandler) cbClass.newInstance();
- } catch (java.lang.Exception e) {
- throw new TrustException("cannotCreatePWCBInstance", new String[]{config
- .getCallbackHandlerName()}, e);
- }
- handler.handle(cb);
- attrs = cb.getAttributes();
- }else{
- //TODO Remove this after discussing
- SAMLAttribute attribute = new SAMLAttribute("Name",
- "https://rahas.apache.org/saml/attrns", null, -1, Arrays
- .asList(new String[] { "Colombo/Rahas" }));
- attrs = new SAMLAttribute[]{attribute};
- }
-
- SAMLAttributeStatement attrStmt = new SAMLAttributeStatement(
- subject, Arrays.asList(attrs ));
-
- SAMLStatement[] statements = { attrStmt };
-
- SAMLAssertion assertion = new SAMLAssertion(config.issuerName,
- notBefore, notAfter, null, null, Arrays.asList(statements));
-
- // sign the assertion
- X509Certificate[] issuerCerts = crypto
- .getCertificates(config.issuerKeyAlias);
-
- String sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA;
- String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
- if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
- sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
- }
- java.security.Key issuerPK = crypto.getPrivateKey(
- config.issuerKeyAlias, config.issuerKeyPassword);
- assertion.sign(sigAlgo, issuerPK, Arrays.asList(issuerCerts));
+ && 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);
+ }
+ handler.handle(cb);
+ attrs = 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};
+ }
+
+ AttributeStatement attributeStatement = SAMLUtils.createAttributeStatement(subject, Arrays.asList(attrs));
+
+
+ List<Statement> attributeStatements = new ArrayList<Statement>();
+ attributeStatements.add(attributeStatement);
+
+ Assertion assertion = SAMLUtils.createAssertion(config.issuerName, notBefore,
+ notAfter, attributeStatements);
+
+ SAMLUtils.signAssertion(assertion, crypto, config.getIssuerKeyAlias(), config.getIssuerKeyPassword());
return assertion;
} catch (Exception e) {
@@ -497,66 +479,47 @@ public class SAMLTokenIssuer implements
}
/**
- * @param doc
- * @param confMethod
- * @param subjectNameId
- * @param keyInfoContent
- * @param config
- * @param crypto
- * @param notBefore
- * @param notAfter
- * @return
- * @throws TrustException
+ * Creates an authentication assertion.
+ * @param confirmationMethod The confirmation method. (HOK, Bearer ...)
+ * @param subjectNameId The principal name.
+ * @param keyInfo OpenSAML representation of KeyInfo.
+ * @param config Rahas configurations.
+ * @param crypto Certificate information.
+ * @param notBefore Validity start.
+ * @param notAfter Validity end.
+ * @param data Other Rahas data.
+ * @return An openSAML Assertion.
+ * @throws TrustException If an exception occurred while creating the Assertion.
*/
- private SAMLAssertion createAuthAssertion(Document doc, String confMethod,
- SAMLNameIdentifier subjectNameId, Element keyInfoContent,
- SAMLTokenIssuerConfig config, Crypto crypto, Date notBefore,
- Date notAfter, RahasData data) throws TrustException {
+ private Assertion createAuthAssertion(String confirmationMethod,
+ NameIdentifier subjectNameId, KeyInfo keyInfo,
+ SAMLTokenIssuerConfig config, Crypto crypto, DateTime notBefore,
+ DateTime notAfter, RahasData data) throws TrustException {
try {
- String[] confirmationMethods = new String[] { confMethod };
-
- Element keyInfoElem = null;
- if (keyInfoContent != null) {
- keyInfoElem = doc
- .createElementNS(WSConstants.SIG_NS, "KeyInfo");
- ((OMElement) keyInfoContent).declareNamespace(
- WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
- ((OMElement) keyInfoContent).declareNamespace(
- WSConstants.ENC_NS, WSConstants.ENC_PREFIX);
-
- keyInfoElem.appendChild(keyInfoContent);
- }
- SAMLSubject subject = new SAMLSubject(subjectNameId, Arrays
- .asList(confirmationMethods), null, keyInfoElem);
+ Subject subject = SAMLUtils.createSubject(subjectNameId,confirmationMethod, keyInfo);
- SAMLAuthenticationStatement authStmt = new SAMLAuthenticationStatement(
- subject,
- SAMLAuthenticationStatement.AuthenticationMethod_Password,
- notBefore, null, null, null);
+ AuthenticationStatement authenticationStatement
+ = SAMLUtils.createAuthenticationStatement(subject, AUTHENTICATION_METHOD_PASSWORD,
+ notBefore);
- List<SAMLStatement> statements = new ArrayList<SAMLStatement>();
+ List<Statement> statements = new ArrayList<Statement>();
if (data.getClaimDialect() != null && data.getClaimElem() != null) {
- SAMLStatement attrStatement = createSAMLAttributeStatement((SAMLSubject)subject.clone(), data, config);
+ Statement attrStatement = createSAMLAttributeStatement(
+ SAMLUtils.createSubject(subject.getNameIdentifier(),
+ confirmationMethod, keyInfo), data, config);
statements.add(attrStatement);
}
- statements.add(authStmt);
- SAMLAssertion assertion = new SAMLAssertion(config.issuerName,
- notBefore, notAfter, null, null, statements);
+ statements.add(authenticationStatement);
- // sign the assertion
- X509Certificate[] issuerCerts = crypto
- .getCertificates(config.issuerKeyAlias);
-
- String sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA;
- String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
- if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
- sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
- }
- java.security.Key issuerPK = crypto.getPrivateKey(
- config.issuerKeyAlias, config.issuerKeyPassword);
- assertion.sign(sigAlgo, issuerPK, Arrays.asList(issuerCerts));
+ Assertion assertion = SAMLUtils.createAssertion(config.issuerName,
+ notBefore, notAfter, statements);
+
+ // Signing the assertion
+ // The <ds:Signature>...</ds:Signature> element appears only after
+ // signing.
+ SAMLUtils.signAssertion(assertion, crypto, config.getIssuerKeyAlias(), config.getIssuerKeyPassword());
return assertion;
} catch (Exception e) {
@@ -611,53 +574,58 @@ public class SAMLTokenIssuer implements
this.configParamName = configParamName;
}
- private SAMLAttributeStatement createSAMLAttributeStatement(SAMLSubject subject,
- RahasData rahasData,
- SAMLTokenIssuerConfig config)
+ private AttributeStatement createSAMLAttributeStatement(Subject subject,
+ RahasData rahasData,
+ SAMLTokenIssuerConfig config)
throws TrustException {
- try {
- SAMLAttribute[] attrs = null;
- if (config.getCallbackHandler() != null) {
- SAMLAttributeCallback cb = new SAMLAttributeCallback(rahasData);
- SAMLCallbackHandler handler = config.getCallbackHandler();
+ Attribute[] attrs = null;
+ if (config.getCallbackHandler() != null) {
+ SAMLAttributeCallback cb = new SAMLAttributeCallback(rahasData);
+ SAMLCallbackHandler handler = config.getCallbackHandler();
+ try {
handler.handle(cb);
attrs = cb.getAttributes();
- } else if (config.getCallbackHandlerName() != null
- && config.getCallbackHandlerName().trim().length() > 0) {
- SAMLAttributeCallback cb = new SAMLAttributeCallback(rahasData);
- SAMLCallbackHandler handler = null;
- MessageContext msgContext = rahasData.getInMessageContext();
- ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
- Class cbClass = null;
- try {
- cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
- } catch (ClassNotFoundException e) {
- throw new TrustException("cannotLoadPWCBClass",
- new String[]{config.getCallbackHandlerName()}, e);
- }
- try {
- handler = (SAMLCallbackHandler) cbClass.newInstance();
- } catch (Exception e) {
- throw new TrustException("cannotCreatePWCBInstance",
- new String[]{config.getCallbackHandlerName()}, e);
- }
+ } catch (SAMLException e) {
+ throw new TrustException("unableToRetrieveCallbackHandler", e);
+ }
+
+ } else if (config.getCallbackHandlerName() != null
+ && config.getCallbackHandlerName().trim().length() > 0) {
+ SAMLAttributeCallback cb = new SAMLAttributeCallback(rahasData);
+ SAMLCallbackHandler handler = null;
+ MessageContext msgContext = rahasData.getInMessageContext();
+ ClassLoader classLoader = msgContext.getAxisService().getClassLoader();
+ Class cbClass = null;
+ try {
+ cbClass = Loader.loadClass(classLoader, config.getCallbackHandlerName());
+ } catch (ClassNotFoundException e) {
+ throw new TrustException("cannotLoadPWCBClass",
+ new String[]{config.getCallbackHandlerName()}, e);
+ }
+ try {
+ handler = (SAMLCallbackHandler) cbClass.newInstance();
+ } catch (Exception e) {
+ throw new TrustException("cannotCreatePWCBInstance",
+ new String[]{config.getCallbackHandlerName()}, e);
+ }
+ try {
handler.handle(cb);
- attrs = cb.getAttributes();
- } else {
- //TODO Remove this after discussing
- SAMLAttribute attribute = new SAMLAttribute("Name",
- "https://rahas.apache.org/saml/attrns",
- null, -1,
- Arrays.asList(new String[]{"Colombo/Rahas"}));
- attrs = new SAMLAttribute[]{attribute};
+ } catch (SAMLException e) {
+ throw new TrustException("unableToRetrieveCallbackHandler", e);
}
+ attrs = cb.getAttributes();
+ } else {
+ //TODO Remove this after discussing
+ Attribute attribute =
+ SAMLUtils.createAttribute("Name", "https://rahas.apache.org/saml/attrns", "Colombo/Rahas");
- SAMLAttributeStatement attrStmt = new SAMLAttributeStatement(
- subject, Arrays.asList(attrs));
- return attrStmt;
- } catch (SAMLException e) {
- throw new TrustException(e.getMessage(), e);
+ attrs = new Attribute[]{attribute};
}
+
+ AttributeStatement attributeStatement = SAMLUtils.createAttributeStatement(subject, Arrays.asList(attrs));
+
+ return attributeStatement;
+
}
}
Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java?rev=1295060&r1=1295059&r2=1295060&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenRenewer.java Wed Feb 29 10:45:37 2012
@@ -1,14 +1,10 @@
package org.apache.rahas.impl;
-import java.security.PublicKey;
-import java.security.cert.X509Certificate;
import java.text.DateFormat;
-import java.util.Arrays;
import java.util.Date;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
-import org.apache.axiom.om.impl.dom.jaxp.DocumentBuilderFactoryImpl;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.Parameter;
@@ -19,16 +15,17 @@ import org.apache.rahas.TokenRenewer;
import org.apache.rahas.TokenStorage;
import org.apache.rahas.TrustException;
import org.apache.rahas.TrustUtil;
-import org.apache.ws.security.WSSecurityException;
+import org.apache.rahas.impl.util.SAMLUtils;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoFactory;
import org.apache.ws.security.util.XmlSchemaDateFormat;
-import org.apache.xml.security.signature.XMLSignature;
-import org.opensaml.SAMLAssertion;
-import org.opensaml.SAMLException;
+import org.joda.time.DateTime;
+import org.opensaml.saml1.core.Assertion;
+import org.opensaml.saml1.core.Conditions;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
+@SuppressWarnings({"UnusedDeclaration"})
public class SAMLTokenRenewer implements TokenRenewer {
private String configParamName;
@@ -38,14 +35,14 @@ public class SAMLTokenRenewer implements
private String configFile;
public SOAPEnvelope renew(RahasData data) throws TrustException {
-
+
// retrieve the message context
MessageContext inMsgCtx = data.getInMessageContext();
-
+
SAMLTokenIssuerConfig config = null;
if (this.configElement != null) {
config = new SAMLTokenIssuerConfig(configElement
- .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
+ .getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
}
// Look for the file
@@ -62,115 +59,92 @@ public class SAMLTokenRenewer implements
SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG));
} else {
throw new TrustException("expectedParameterMissing",
- new String[] { this.configParamName });
+ new String[]{this.configParamName});
}
}
if (config == null) {
throw new TrustException("configurationIsNull");
}
-
+
// retrieve the list of tokens from the message context
TokenStorage tkStorage = TrustUtil.getTokenStore(inMsgCtx);
-
- try {
- // Set the DOM impl to DOOM
- DocumentBuilderFactoryImpl.setDOOMRequired(true);
-
- // Create envelope
- SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx
- .getEnvelope().getNamespace().getNamespaceURI());
-
- // Create RSTR element, with respective version
- OMElement rstrElem;
- int wstVersion = data.getVersion();
- if (RahasConstants.VERSION_05_02 == wstVersion) {
- rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
- wstVersion, env.getBody());
- } else {
- OMElement rstrcElem = TrustUtil
- .createRequestSecurityTokenResponseCollectionElement(
- wstVersion, env.getBody());
- rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
- wstVersion, rstrcElem);
- }
-
- Crypto crypto;
- if (config.cryptoElement != null) {
- // crypto props defined as elements
- crypto = CryptoFactory.getInstance(TrustUtil
- .toProperties(config.cryptoElement), inMsgCtx
- .getAxisService().getClassLoader());
- } else {
- // crypto props defined in a properties file
- crypto = CryptoFactory.getInstance(config.cryptoPropertiesFile,
- inMsgCtx.getAxisService().getClassLoader());
- }
- // Create TokenType element
- TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(
- RahasConstants.TOK_TYPE_SAML_10);
-
- // Creation and expiration times
- Date creationTime = new Date();
- Date expirationTime = new Date();
- expirationTime.setTime(creationTime.getTime() + config.ttl);
-
- // Use GMT time in milliseconds
- DateFormat zulu = new XmlSchemaDateFormat();
-
- // Add the Lifetime element
- TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu
- .format(creationTime), zulu.format(expirationTime));
-
- // Obtain the token
- Token tk = tkStorage.getToken(data.getTokenId());
-
- OMElement assertionOMElement = tk.getToken();
- SAMLAssertion samlAssertion = null;
-
- try {
- samlAssertion = new SAMLAssertion((Element) assertionOMElement);
- samlAssertion.unsign();
- samlAssertion.setNotBefore(creationTime);
- samlAssertion.setNotOnOrAfter(expirationTime);
-
- // sign the assertion
- X509Certificate[] issuerCerts = crypto
- .getCertificates(config.issuerKeyAlias);
-
- String sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA;
- String pubKeyAlgo = issuerCerts[0].getPublicKey().getAlgorithm();
- if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
- sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA;
- }
- java.security.Key issuerPK = crypto.getPrivateKey(
- config.issuerKeyAlias, config.issuerKeyPassword);
-
- samlAssertion.sign(sigAlgo, issuerPK, Arrays.asList(issuerCerts));
-
- // Create the RequestedSecurityToken element and add the SAML token
- // to it
- OMElement reqSecTokenElem = TrustUtil
- .createRequestedSecurityTokenElement(wstVersion, rstrElem);
-
- Node tempNode = samlAssertion.toDOM();
- reqSecTokenElem.addChild((OMNode) ((Element) rstrElem)
- .getOwnerDocument().importNode(tempNode, true));
-
-
- } catch (SAMLException e) {
- throw new TrustException("Cannot create SAML Assertion",e);
- } catch (WSSecurityException e) {
- throw new TrustException("Cannot create SAML Assertion",e);
- } catch (Exception e) {
- throw new TrustException("Cannot create SAML Assertion",e);
- }
- return env;
- } finally {
- DocumentBuilderFactoryImpl.setDOOMRequired(false);
+ // Create envelope
+ SOAPEnvelope env = TrustUtil.createSOAPEnvelope(inMsgCtx
+ .getEnvelope().getNamespace().getNamespaceURI());
+
+ // Create RSTR element, with respective version
+ OMElement rstrElem;
+ int wstVersion = data.getVersion();
+ if (RahasConstants.VERSION_05_02 == wstVersion) {
+ rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
+ wstVersion, env.getBody());
+ } else {
+ OMElement rstrcElem = TrustUtil
+ .createRequestSecurityTokenResponseCollectionElement(
+ wstVersion, env.getBody());
+ rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(
+ wstVersion, rstrcElem);
+ }
+
+ Crypto crypto;
+ if (config.cryptoElement != null) {
+ // crypto props defined as elements
+ crypto = CryptoFactory.getInstance(TrustUtil
+ .toProperties(config.cryptoElement), inMsgCtx
+ .getAxisService().getClassLoader());
+ } else {
+ // crypto props defined in a properties file
+ crypto = CryptoFactory.getInstance(config.cryptoPropertiesFile,
+ inMsgCtx.getAxisService().getClassLoader());
+ }
+
+ // Create TokenType element
+ TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(
+ RahasConstants.TOK_TYPE_SAML_10);
+
+ // Creation and expiration times
+ Date creationTime = new Date();
+ Date expirationTime = new Date();
+ expirationTime.setTime(creationTime.getTime() + config.ttl);
+
+ // Use GMT time in milliseconds
+ DateFormat zulu = new XmlSchemaDateFormat();
+
+ // Add the Lifetime element
+ TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu
+ .format(creationTime), zulu.format(expirationTime));
+
+ // Obtain the token
+ Token tk = tkStorage.getToken(data.getTokenId());
+
+ OMElement assertionOMElement = tk.getToken();
+ Assertion samlAssertion;
+
+
+ samlAssertion = SAMLUtils.buildAssertion((Element) assertionOMElement);
+ if (samlAssertion.getConditions() == null) {
+ samlAssertion.setConditions((Conditions) SAMLUtils.buildXMLObject(Conditions.DEFAULT_ELEMENT_NAME));
}
+ samlAssertion.getConditions().setNotBefore(new DateTime(creationTime));
+ samlAssertion.getConditions().setNotOnOrAfter(new DateTime(expirationTime));
+
+ // sign the assertion
+ SAMLUtils.signAssertion(samlAssertion, crypto, config.getIssuerKeyAlias(), config.getIssuerKeyPassword());
+
+ // Create the RequestedSecurityToken element and add the SAML token
+ // to it
+ OMElement reqSecTokenElem = TrustUtil
+ .createRequestedSecurityTokenElement(wstVersion, rstrElem);
+
+ Node tempNode = samlAssertion.getDOM();
+ reqSecTokenElem.addChild((OMNode) ((Element) rstrElem)
+ .getOwnerDocument().importNode(tempNode, true));
+
+ return env;
+
}
/**
Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenValidator.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenValidator.java?rev=1295060&r1=1295059&r2=1295060&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenValidator.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/SAMLTokenValidator.java Wed Feb 29 10:45:37 2012
@@ -19,15 +19,18 @@ import org.apache.rahas.TokenStorage;
import org.apache.rahas.TokenValidator;
import org.apache.rahas.TrustException;
import org.apache.rahas.TrustUtil;
+import org.apache.rahas.impl.util.SAMLUtils;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.components.crypto.CryptoFactory;
-import org.opensaml.SAMLAssertion;
-import org.opensaml.SAMLException;
+import org.opensaml.saml1.core.Assertion;
+import org.opensaml.xml.signature.SignatureValidator;
+import org.opensaml.xml.validation.ValidationException;
import org.w3c.dom.Element;
/**
* Implementation of a SAML Token Validator for the Security Token Service.
*/
+@SuppressWarnings({"UnusedDeclaration"})
public class SAMLTokenValidator implements TokenValidator {
Log log = LogFactory.getLog(SAMLTokenValidator.class);
@@ -112,31 +115,31 @@ public class SAMLTokenValidator implemen
* Checks whether the token is valid or not, by verifying the issuer's own
* signature. If it has been signed by the token issuer, then it is a valid
* token.
- *
- * @param token
- * the token to validate.
+ *
+ * @param token the token to validate.
+ * @param issuerPBKey Public key which should be used during validation.
* @return true if the token has been signed by the issuer.
*/
private boolean isValid(Token token, PublicKey issuerPBKey) {
- // extract SAMLAssertion object from token
- OMElement assertionOMElement = token.getToken();
- SAMLAssertion samlAssertion = null;
-
- try {
- samlAssertion = new SAMLAssertion((Element) assertionOMElement);
+ // extract SAMLAssertion object from token
+ OMElement assertionOMElement = token.getToken();
+ Assertion samlAssertion = null;
+
+ try {
+ samlAssertion = SAMLUtils.buildAssertion((Element) assertionOMElement);
+
+ log.info("Verifying token validity...");
+
+ // check if the token has been signed by the issuer.
+ SignatureValidator validator = new SignatureValidator(samlAssertion.getSignature().getSigningCredential());
+ validator.validate(samlAssertion.getSignature());
+ } catch (ValidationException e) {
+ log.error("Signature verification failed on SAML token.", e);
+ return false;
+ }
- log.info("Verifying token validity...");
-
- // check if the token has been signed by the issuer.
- samlAssertion.verify(issuerPBKey);
-
- } catch (SAMLException e) {
- log.error("Could not verify signature", e);
- return false;
- }
-
- // if there was no exception, then the token is valid
- return true;
+ // if there was no exception, then the token is valid
+ return true;
}
//here we basically reuse the SAMLTokenIssuer config
@@ -197,14 +200,7 @@ public class SAMLTokenValidator implemen
return issuerPBKey;
}
- /**
- * Returns the <wst:Status> element.
- *
- * @param version
- * WS-Trust version.
- * @param parent
- * the parent OMElement.
- */
+
private static OMElement createMessageElement(int version,
OMElement parent, String elementName) throws TrustException {
return createOMElement(parent, TrustUtil.getWSTNamespace(version),
@@ -224,7 +220,7 @@ public class SAMLTokenValidator implemen
* value of the <configuration-file> element of the
* token-dispatcher-configuration
*
- * @param configFile
+ * @param configFile configuration file to be used.
*/
public void setConfigurationFile(String configFile) {
this.configFile = configFile;
@@ -236,7 +232,7 @@ public class SAMLTokenValidator implemen
* object available in the via the messageContext when the
* <code>TokenValidator</code> is called.
*
- * @param configParamName
+ * @param configParamName Parameter name.
* @see org.apache.axis2.description.Parameter
*/
public void setConfigurationParamName(String configParamName) {
Added: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/AxiomParserPool.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/AxiomParserPool.java?rev=1295060&view=auto
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/AxiomParserPool.java (added)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/AxiomParserPool.java Wed Feb 29 10:45:37 2012
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF 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.impl.util;
+
+import static org.apache.axiom.om.OMAbstractFactory.FEATURE_DOM;
+
+import java.lang.reflect.Field;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.dom.DOMMetaFactory;
+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
+ * instead of requesting a {@link DocumentBuilderFactory} using JAXP.
+ */
+public class AxiomParserPool extends StaticBasicParserPool {
+ public AxiomParserPool() {
+ DOMMetaFactory metaFactory = (DOMMetaFactory)OMAbstractFactory.getMetaFactory(FEATURE_DOM);
+ DocumentBuilderFactory dbf = metaFactory.newDocumentBuilderFactory();
+ // Unfortunately, ParserPool doesn't allow to set the DocumentBuilderFactory, so that we
+ // have to use reflection here.
+ try {
+ Field dbfField = StaticBasicParserPool.class.getDeclaredField("builderFactory");
+ dbfField.setAccessible(true);
+ dbfField.set(this, dbf);
+ } catch (IllegalAccessException ex) {
+ throw new IllegalAccessError(ex.getMessage());
+ } catch (NoSuchFieldException ex) {
+ throw new NoSuchFieldError(ex.getMessage());
+ }
+ }
+}
Added: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java?rev=1295060&view=auto
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java (added)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/CommonUtil.java Wed Feb 29 10:45:37 2012
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2004,2005 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.
+ * 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.impl.util;
+
+import org.apache.axiom.om.OMAbstractFactory;
+import org.apache.axiom.om.dom.DOMMetaFactory;
+import org.apache.rahas.TrustException;
+import org.w3c.dom.Document;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import static org.apache.axiom.om.OMAbstractFactory.FEATURE_DOM;
+
+/**
+ * This class implements some utility methods common to SAML1 and SAML2.
+ */
+public class CommonUtil {
+
+ /**
+ * This method creates a DOM compatible Axiom document.
+ * @return DOM compatible Axiom document
+ * @throws TrustException If an error occurred while creating the Document.
+ */
+ public static Document getOMDOMDocument() throws TrustException {
+ DOMMetaFactory metaFactory = (DOMMetaFactory) OMAbstractFactory.getMetaFactory(FEATURE_DOM);
+ DocumentBuilderFactory dbf = metaFactory.newDocumentBuilderFactory();
+ try {
+ return dbf.newDocumentBuilder().newDocument();
+ } catch (ParserConfigurationException e) {
+ throw new TrustException("Error creating Axiom compatible DOM Document", e);
+ }
+ }
+}
Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java?rev=1295060&r1=1295059&r2=1295060&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAML2Utils.java Wed Feb 29 10:45:37 2012
@@ -20,6 +20,7 @@ package org.apache.rahas.impl.util;
import org.apache.axiom.om.impl.dom.jaxp.DocumentBuilderFactoryImpl;
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.WSConstants;
import org.apache.ws.security.WSPasswordCallback;
@@ -66,7 +67,7 @@ public class SAML2Utils {
try {
String jaxpProperty = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
- System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
+ //System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(xmlObj);
@@ -221,7 +222,7 @@ public class SAML2Utils {
// 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");
+ //System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
MarshallerFactory marshallerFactory = org.opensaml.xml.Configuration.getMarshallerFactory();
Marshaller marshaller = marshallerFactory.getMarshaller(KIElem);
@@ -310,6 +311,21 @@ public class SAML2Utils {
}
}
+ /**
+ * Get the subject confirmation method of a SAML 2.0 assertion
+ *
+ * @param assertion SAML 2.0 assertion
+ * @return Subject Confirmation method
+ */
+ public static String getSAML2SubjectConfirmationMethod(Assertion assertion) {
+ String subjectConfirmationMethod = RahasConstants.SAML20_SUBJECT_CONFIRMATION_HOK;
+ List<SubjectConfirmation> subjectConfirmations = assertion.getSubject().getSubjectConfirmations();
+ if (subjectConfirmations.size() > 0) {
+ subjectConfirmationMethod = subjectConfirmations.get(0).getMethod();
+ }
+ return subjectConfirmationMethod;
+ }
+
}
Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLAttributeCallback.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLAttributeCallback.java?rev=1295060&r1=1295059&r2=1295060&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLAttributeCallback.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLAttributeCallback.java Wed Feb 29 10:45:37 2012
@@ -4,50 +4,61 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.rahas.RahasData;
-import org.opensaml.SAMLAttribute;
-import org.opensaml.saml2.core.Attribute;
+import org.opensaml.common.SAMLObject;
+
+@SuppressWarnings({"UnusedDeclaration"})
public class SAMLAttributeCallback implements SAMLCallback{
-
- private List attributes = null;
- private RahasData data = null;
-
- public SAMLAttributeCallback(RahasData data){
- attributes = new ArrayList();
- this.data = data;
- }
-
- public int getCallbackType(){
- return SAMLCallback.ATTR_CALLBACK;
- }
-
- public void addAttributes(SAMLAttribute attribute){
- attributes.add(attribute);
- }
+
+ private List<SAMLObject> attributes = null;
+ private RahasData data = null;
+
+ public SAMLAttributeCallback(RahasData data){
+ attributes = new ArrayList<SAMLObject>();
+ this.data = data;
+ }
+
+ public int getCallbackType(){
+ return SAMLCallback.ATTR_CALLBACK;
+ }
+
+ /**
+ * Add SAML1 attribute.
+ * @param attribute SAML1 attribute
+ */
+ public void addAttributes(org.opensaml.saml1.core.Attribute attribute){
+ attributes.add(attribute);
+ }
/**
* Overloaded method to support SAML2
- * @param attr
+ * @param attribute SAML2 attribute.
*/
- public void addAttributes(Attribute attr){
- attributes.add(attr);
+ public void addAttributes(org.opensaml.saml2.core.Attribute attribute){
+ attributes.add(attribute);
}
/**
* Get the array of SAML2 attributes.
- * @return
+ * @return SAML2 attribute list.
*/
- public Attribute[] getSAML2Attributes(){
- return (Attribute[])attributes.toArray(new Attribute[attributes.size()]);
+ public org.opensaml.saml2.core.Attribute[] getSAML2Attributes(){
+ return (org.opensaml.saml2.core.Attribute[])attributes.toArray
+ (new org.opensaml.saml2.core.Attribute[attributes.size()]);
+ }
+
+ /**
+ * Get SAML2 attribute
+ * @return SAML2 attributes.
+ */
+ public org.opensaml.saml1.core.Attribute[] getAttributes(){
+ return (org.opensaml.saml1.core.Attribute[])attributes.toArray
+ (new org.opensaml.saml1.core.Attribute[attributes.size()]);
+
+ }
+
+ public RahasData getData() {
+ return data;
}
-
- public SAMLAttribute[] getAttributes(){
- return (SAMLAttribute[])attributes.toArray(new SAMLAttribute[attributes.size()]);
-
- }
-
- public RahasData getData() {
- return data;
- }
}
Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLCallbackHandler.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLCallbackHandler.java?rev=1295060&r1=1295059&r2=1295060&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLCallbackHandler.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLCallbackHandler.java Wed Feb 29 10:45:37 2012
@@ -1,6 +1,6 @@
package org.apache.rahas.impl.util;
-import org.opensaml.SAMLException;
+import org.opensaml.common.SAMLException;
/**
* SAMLCallback Handler enables you to add data to the
Modified: axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLNameIdentifierCallback.java
URL: http://svn.apache.org/viewvc/axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLNameIdentifierCallback.java?rev=1295060&r1=1295059&r2=1295060&view=diff
==============================================================================
--- axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLNameIdentifierCallback.java (original)
+++ axis/axis2/java/rampart/branches/1_6/modules/rampart-trust/src/main/java/org/apache/rahas/impl/util/SAMLNameIdentifierCallback.java Wed Feb 29 10:45:37 2012
@@ -1,7 +1,7 @@
package org.apache.rahas.impl.util;
import org.apache.rahas.RahasData;
-import org.opensaml.SAMLNameIdentifier;
+import org.opensaml.saml1.core.NameIdentifier;
/**
* This is used retrieve data for the SAMLNameIdentifier.
@@ -11,37 +11,37 @@ import org.opensaml.SAMLNameIdentifier;
*
*/
public class SAMLNameIdentifierCallback implements SAMLCallback{
-
- private SAMLNameIdentifier nameId = null;
- private String userId = null;
- private RahasData data = null;
-
- public SAMLNameIdentifierCallback(RahasData data){
- this.data = data;
- }
-
- public int getCallbackType(){
- return SAMLCallback.NAME_IDENTIFIER_CALLBACK;
- }
-
- public SAMLNameIdentifier getNameId() {
- return nameId;
- }
-
- public void setNameId(SAMLNameIdentifier nameId) {
- this.nameId = nameId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public String getUserId() {
- return userId;
- }
-
- public RahasData getData() {
- return data;
- }
-
+
+ private NameIdentifier nameId = null;
+ private String userId = null;
+ private RahasData data = null;
+
+ public SAMLNameIdentifierCallback(RahasData data){
+ this.data = data;
+ }
+
+ public int getCallbackType(){
+ return SAMLCallback.NAME_IDENTIFIER_CALLBACK;
+ }
+
+ public NameIdentifier getNameId() {
+ return nameId;
+ }
+
+ public void setNameId(NameIdentifier nameId) {
+ this.nameId = nameId;
+ }
+
+ public void setUserId(String userId) {
+ this.userId = userId;
+ }
+
+ public String getUserId() {
+ return userId;
+ }
+
+ public RahasData getData() {
+ return data;
+ }
+
}