JBoss Identity SVN: r812 - in identity-federation/trunk: jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust and 1 other directories.
by jboss-identity-commits@lists.jboss.org
Author: beve
Date: 2009-09-28 15:04:19 -0400 (Mon, 28 Sep 2009)
New Revision: 812
Modified:
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java
Log:
Work for re-opened https://jira.jboss.org/jira/browse/JBID-195 "Add 'AppliesTo' support for WSTrustClient and STSClient"
Re-opened to add an additional method: issueToken(String endpointURI, String tokenType)
Modified: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java 2009-09-28 08:38:47 UTC (rev 811)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java 2009-09-28 19:04:19 UTC (rev 812)
@@ -96,6 +96,23 @@
}
/**
+ * Issues a Security Token from the STS. This methods has the option of
+ * specifying both or one of endpointURI/tokenType but at least one must
+ * specified.
+ *
+ * @param endpointURI - The ultimate recipient of the token. This will be set at the AppliesTo for
+ * the RequestSecurityToken which is an optional element so it may be null.
+ * @param tokenType - The type of security token to be issued.
+ * @return Element - The Security Token Element issued.
+ * @throws IllegalArgumentException If neither endpointURI nor tokenType was specified.
+ * @throws WSTrustException
+ */
+ public Element issueToken(String endpointURI, String tokenType) throws WSTrustException
+ {
+ return stsClient.issueToken(endpointURI, tokenType);
+ }
+
+ /**
* This method will send a RequestSecurityToken with a RequestType of renew
* and the passed-in tokenType identifies the type of token to be renewed by
* the STS.
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java 2009-09-28 08:38:47 UTC (rev 811)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java 2009-09-28 19:04:19 UTC (rev 812)
@@ -92,13 +92,36 @@
* for the endpointURI passed in.
* @throws WSTrustException
*/
- public Element issueTokenForEndpoint(final String endpointURI) throws WSTrustException
+ public Element issueTokenForEndpoint(String endpointURI) throws WSTrustException
{
RequestSecurityToken request = new RequestSecurityToken();
setAppliesTo(endpointURI, request);
return issueToken(request);
}
+ /**
+ * Issues a Security Token from the STS. This methods has the option of
+ * specifying one or both of endpointURI/tokenType but at least one must
+ * specified.
+ *
+ * @param endpointURI - The ultimate recipient of the token. This will be set at the AppliesTo for
+ * the RequestSecurityToken which is an optional element so it may be null.
+ * @param tokenType - The type of security token to be issued.
+ * @return Element - The Security Token Element issued.
+ * @throws IllegalArgumentException If neither endpointURI nor tokenType was specified.
+ * @throws WSTrustException
+ */
+ public Element issueToken(String endpointURI, String tokenType) throws WSTrustException
+ {
+ if (endpointURI == null && tokenType == null)
+ throw new IllegalArgumentException("One of endpointURI or tokenType must be provided.");
+
+ RequestSecurityToken request = new RequestSecurityToken();
+ setAppliesTo(endpointURI, request);
+ setTokenType(tokenType, request);
+ return issueToken(request);
+ }
+
public Element issueToken(String tokenType) throws WSTrustException
{
// create a custom token request message.
Modified: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java 2009-09-28 08:38:47 UTC (rev 811)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java 2009-09-28 19:04:19 UTC (rev 812)
@@ -222,6 +222,29 @@
Element renewedToken = client.renewToken(SAMLUtil.SAML2_TOKEN_TYPE, token);
System.out.println("Renewed Token=" + DocumentUtil.getNodeAsString(renewedToken));
}
+
+ public void testIssue_Niehter_AppliesTo_Or_TokenType_Specified()
+ {
+ if(usetest == false)
+ return;
+
+ Builder stsConfigBuilder = new STSClientConfig.Builder();
+ stsConfigBuilder.serviceName("JBossSTS");
+ stsConfigBuilder.portName("JBossSTSPort");
+ stsConfigBuilder.endpointAddress("http://localhost:8080/jboss-sts/JBossSTS");
+ stsConfigBuilder.username("admin").password("admin");
+ STSClient client = new STSClient(stsConfigBuilder.build());
+
+ try
+ {
+ client.issueToken(null, null);
+ fail("issueTokenForEndpoint shoud throw an exception if endpointURI and tokenType are null");
+ }
+ catch(Exception e)
+ {
+ assertTrue("Excpetion was not of type IllegalException", e instanceof IllegalArgumentException);
+ }
+ }
private Dispatch<Source> createDispatch() throws MalformedURLException, JAXBException
14 years, 7 months
JBoss Identity SVN: r811 - in identity-federation/trunk: jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust and 1 other directories.
by jboss-identity-commits@lists.jboss.org
Author: beve
Date: 2009-09-28 04:38:47 -0400 (Mon, 28 Sep 2009)
New Revision: 811
Modified:
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java
Log:
Work for https://jira.jboss.org/jira/browse/JBID-195 "Add 'AppliesTo' support for WSTrustClient and STSClient"
Modified: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java 2009-09-25 17:41:16 UTC (rev 810)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java 2009-09-28 08:38:47 UTC (rev 811)
@@ -80,8 +80,22 @@
{
return stsClient.issueToken(tokenType);
}
-
+
/**
+ * This method will send a RequestSecurityToken with a RequestType of issue
+ * and the passed-in endpointURI identifies the ultimate recipient of the token.
+ *
+ * @param endpointURI - The ultimate recipient of the token. This will be set at the AppliesTo for
+ * the RequestSecurityToken which is an optional element so it may be null.
+ * @return Element - The Security Token element. Will be of the tokenType configured for the endpointURI.
+ * @throws WSTrustException
+ */
+ public Element issueTokenForEndpoint(String endpointURI) throws WSTrustException
+ {
+ return stsClient.issueTokenForEndpoint(endpointURI);
+ }
+
+ /**
* This method will send a RequestSecurityToken with a RequestType of renew
* and the passed-in tokenType identifies the type of token to be renewed by
* the STS.
@@ -93,7 +107,6 @@
public Element renewToken(String tokenType, Element token) throws WSTrustException
{
return stsClient.renewToken(tokenType, token);
-
}
/**
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java 2009-09-25 17:41:16 UTC (rev 810)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java 2009-09-28 08:38:47 UTC (rev 811)
@@ -82,16 +82,50 @@
}
dispatchLocal.set(dispatch);
}
-
+
+ /**
+ * Issues a Security Token for the ultimate recipient of the token.
+ *
+ * @param endpointURI - The ultimate recipient of the token. This will be set at the AppliesTo for
+ * the RequestSecurityToken which is an optional element so it may be null.
+ * @return Element - The Security Token Element which will be of the TokenType configured
+ * for the endpointURI passed in.
+ * @throws WSTrustException
+ */
+ public Element issueTokenForEndpoint(final String endpointURI) throws WSTrustException
+ {
+ RequestSecurityToken request = new RequestSecurityToken();
+ setAppliesTo(endpointURI, request);
+ return issueToken(request);
+ }
+
public Element issueToken(String tokenType) throws WSTrustException
{
// create a custom token request message.
RequestSecurityToken request = new RequestSecurityToken();
- request.setTokenType(URI.create(tokenType));
+ setTokenType(tokenType, request);
+ // send the token request to JBoss STS and get the response.
+ return issueToken(request);
+ }
+
+ private RequestSecurityToken setAppliesTo(String endpointURI, RequestSecurityToken rst)
+ {
+ if (endpointURI != null)
+ rst.setAppliesTo(WSTrustUtil.createAppliesTo(endpointURI));
+ return rst;
+ }
+
+ private RequestSecurityToken setTokenType(String tokenType, RequestSecurityToken rst)
+ {
+ if (tokenType != null)
+ rst.setTokenType(URI.create(tokenType));
+ return rst;
+ }
+
+ private Element issueToken(RequestSecurityToken request) throws WSTrustException
+ {
request.setRequestType(URI.create(WSTrustConstants.ISSUE_REQUEST));
request.setContext("context");
-
- // send the token request to JBoss STS and get the response.
WSTrustJAXBFactory jaxbFactory = WSTrustJAXBFactory.getInstance();
DOMSource requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
Source response = dispatchLocal.get().invoke(requestSource);
Modified: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java 2009-09-25 17:41:16 UTC (rev 810)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java 2009-09-28 08:38:47 UTC (rev 811)
@@ -200,6 +200,28 @@
Element renewedToken = client.renewToken(SAMLUtil.SAML2_TOKEN_TYPE, token);
System.out.println("Renewed Token=" + DocumentUtil.getNodeAsString(renewedToken));
}
+
+ public void testIssue_Validate_Renew_Using_AppliesTo() throws Exception
+ {
+ if(usetest == false)
+ return;
+
+ Builder stsConfigBuilder = new STSClientConfig.Builder();
+ stsConfigBuilder.serviceName("JBossSTS");
+ stsConfigBuilder.portName("JBossSTSPort");
+ stsConfigBuilder.endpointAddress("http://localhost:8080/jboss-sts/JBossSTS");
+ stsConfigBuilder.username("admin").password("admin");
+ STSClient client = new STSClient(stsConfigBuilder.build());
+
+ // This endpointURI is specified in src/test/resource/jboss-sts.xml
+ String endpointURI = "http://services.testcorp.org/provider2";
+
+ Element token = client.issueTokenForEndpoint(endpointURI);
+ assertTrue("Token is valid" , client.validateToken(token));
+
+ Element renewedToken = client.renewToken(SAMLUtil.SAML2_TOKEN_TYPE, token);
+ System.out.println("Renewed Token=" + DocumentUtil.getNodeAsString(renewedToken));
+ }
private Dispatch<Source> createDispatch() throws MalformedURLException, JAXBException
14 years, 7 months
JBoss Identity SVN: r810 - identity-federation/trunk/jboss-identity-fed-core.
by jboss-identity-commits@lists.jboss.org
Author: anil.saldhana(a)jboss.com
Date: 2009-09-25 13:41:16 -0400 (Fri, 25 Sep 2009)
New Revision: 810
Modified:
identity-federation/trunk/jboss-identity-fed-core/pom.xml
Log:
add the annotations api for JAXWS javax.annotation
Modified: identity-federation/trunk/jboss-identity-fed-core/pom.xml
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/pom.xml 2009-09-25 08:00:27 UTC (rev 809)
+++ identity-federation/trunk/jboss-identity-fed-core/pom.xml 2009-09-25 17:41:16 UTC (rev 810)
@@ -68,6 +68,12 @@
<version>1.0</version>
</dependency>
<dependency>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>annotations-api</artifactId>
+ <version>6.0.18</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
<groupId>sun-jaf</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
14 years, 7 months
JBoss Identity SVN: r809 - in identity-federation/trunk: jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust and 9 other directories.
by jboss-identity-commits@lists.jboss.org
Author: beve
Date: 2009-09-25 04:00:27 -0400 (Fri, 25 Sep 2009)
New Revision: 809
Added:
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClientConfig.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClientFactory.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/STSSaml20Handler.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/STSSecurityHandler.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientConfigUnitTestCase.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/handlers/
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/handlers/STSSaml20HandlerTestCase.java
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxrpc.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxws-ext.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxws.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-saaj.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/resolver.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xercesImpl.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xml-apis.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/wstrust/sts-client.properties
Removed:
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientConfig.java
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientFactory.java
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/
identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/handlers/
identity-federation/trunk/jboss-identity-fed-api/src/test/resources/wstrust/jboss-sts-client.properties
Modified:
identity-federation/trunk/jboss-identity-fed-api/pom.xml
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java
identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/WSTrustClientUnitTestCase.java
identity-federation/trunk/jboss-identity-fed-core/pom.xml
Log:
Work for re-opened https://jira.jboss.org/jira/browse/JBID-194 "Add a JAX-WS SOAP Protocol handler for JBossSTS"
This task was to move the code from jboss-identity-fed-api to jboss-identity-fed-core. Some minor refactoring was required also.
Modified: identity-federation/trunk/jboss-identity-fed-api/pom.xml
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/pom.xml 2009-09-24 01:24:30 UTC (rev 808)
+++ identity-federation/trunk/jboss-identity-fed-api/pom.xml 2009-09-25 08:00:27 UTC (rev 809)
@@ -127,12 +127,6 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <version>1.8.0</version>
- <scope>test</scope>
- </dependency>
</dependencies>
<reporting>
Modified: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java 2009-09-24 01:24:30 UTC (rev 808)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClient.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -21,223 +21,91 @@
*/
package org.jboss.identity.federation.api.wstrust;
-import java.net.URI;
-import java.util.Map;
-
-import javax.xml.namespace.QName;
-import javax.xml.soap.SOAPBody;
-import javax.xml.soap.SOAPEnvelope;
-import javax.xml.soap.SOAPPart;
-import javax.xml.transform.Source;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.ws.BindingProvider;
-import javax.xml.ws.Dispatch;
-import javax.xml.ws.Service;
-import javax.xml.ws.Service.Mode;
-import javax.xml.ws.soap.SOAPBinding;
-
import org.jboss.identity.federation.core.exceptions.ParsingException;
-import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
-import org.jboss.identity.federation.core.wstrust.WSTrustConstants;
+import org.jboss.identity.federation.core.wstrust.STSClient;
+import org.jboss.identity.federation.core.wstrust.STSClientConfig;
+import org.jboss.identity.federation.core.wstrust.STSClientFactory;
import org.jboss.identity.federation.core.wstrust.WSTrustException;
-import org.jboss.identity.federation.core.wstrust.WSTrustJAXBFactory;
-import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityToken;
-import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponse;
-import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponseCollection;
-import org.jboss.identity.federation.ws.trust.RenewTargetType;
-import org.jboss.identity.federation.ws.trust.StatusType;
-import org.jboss.identity.federation.ws.trust.ValidateTargetType;
-import org.w3c.dom.Document;
+import org.jboss.identity.federation.core.wstrust.STSClientConfig.Builder;
import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
/**
* WS-Trust Client
+ *
* @author Anil.Saldhana(a)redhat.com
* @since Aug 29, 2009
*/
public class WSTrustClient
{
- private ThreadLocal<Dispatch<Source>> dispatchLocal =
- new InheritableThreadLocal<Dispatch<Source>>();
-
- private String targetNS = "http://org.jboss.identity.trust/sts/";
-
- public static class SecurityInfo
- {
- private String username;
- private String passwd;
-
- public SecurityInfo(String name, char[] pass)
- {
- username = name;
- passwd = new String(pass);
- }
-
- public SecurityInfo(String name, String pass)
- {
- username = name;
- passwd = pass;
- }
- }
-
- public WSTrustClient(String serviceName, String port, String endpointURI,
- SecurityInfo secInfo) throws ParsingException
- {
- QName service = new QName(targetNS, serviceName);
- QName portName = new QName(targetNS, port);
-
- Service jaxwsService = Service.create(service);
- jaxwsService.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointURI);
- Dispatch<Source> dispatch = jaxwsService.createDispatch(portName,
- Source.class, Mode.PAYLOAD);
-
- // add the username and password to the request context.
- Map<String, Object> reqContext = dispatch.getRequestContext();
- if(secInfo != null)
- {
- reqContext.put(BindingProvider.USERNAME_PROPERTY, secInfo.username);
- reqContext.put(BindingProvider.PASSWORD_PROPERTY, secInfo.passwd);
- }
-
- dispatchLocal.set(dispatch);
- }
-
- public Element issueToken(String tokenType) throws WSTrustException
- {
- // create a custom token request message.
- RequestSecurityToken request = new RequestSecurityToken();
- request.setTokenType(URI.create(tokenType));
- request.setRequestType(URI.create(WSTrustConstants.ISSUE_REQUEST));
- request.setContext("context");
-
- // send the token request to JBoss STS and get the response.
- WSTrustJAXBFactory jaxbFactory = WSTrustJAXBFactory.getInstance();
- DOMSource requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
- Source response = dispatchLocal.get().invoke(requestSource);
-
- Node documentNode = ((DOMSource) response).getNode();
- Document responseDoc = documentNode instanceof Document ? (Document) documentNode : documentNode.getOwnerDocument();
-
-
- NodeList nodes;
- try
- {
- Document myDocument = DocumentUtil.createDocument();
- Node importedNode = myDocument.importNode(responseDoc.getDocumentElement(), true);
- myDocument.appendChild(importedNode);
-
- nodes = null;
- if(responseDoc instanceof SOAPPart)
- {
- SOAPPart soapPart = (SOAPPart) responseDoc;
- SOAPEnvelope env = soapPart.getEnvelope();
- SOAPBody body = env.getBody();
- Node data = body.getFirstChild();
- nodes = ((Element)data).getElementsByTagName("RequestedSecurityToken");
- }
- else
- nodes = responseDoc.getElementsByTagNameNS(WSTrustConstants.BASE_NAMESPACE, "RequestedSecurityToken");
- }
- catch (Exception e)
- {
- throw new WSTrustException("Exception in issuing token:", e);
- }
-
- if(nodes == null)
- throw new WSTrustException("NodeList is null");
-
- Node rstr = nodes.item(0);
-
- return (Element) rstr.getFirstChild();
- }
-
- public Element renewToken(String tokenType, Element token) throws WSTrustException
- {
- RequestSecurityToken request = new RequestSecurityToken();
- request.setContext("context");
-
- request.setTokenType(URI.create(WSTrustConstants.STATUS_TYPE));
- request.setRequestType(URI.create(WSTrustConstants.RENEW_REQUEST));
- RenewTargetType renewTarget = new RenewTargetType();
- renewTarget.setAny(token);
- request.setRenewTarget(renewTarget);
-
- // send the token request to JBoss STS and get the response.
- WSTrustJAXBFactory jaxbFactory = WSTrustJAXBFactory.getInstance();
- DOMSource requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
- Source response = dispatchLocal.get().invoke(requestSource);
-
- Node documentNode = ((DOMSource) response).getNode();
- Document responseDoc = documentNode instanceof Document ? (Document) documentNode : documentNode.getOwnerDocument();
-
-
- NodeList nodes;
- try
- {
- Document myDocument = DocumentUtil.createDocument();
- Node importedNode = myDocument.importNode(responseDoc.getDocumentElement(), true);
- myDocument.appendChild(importedNode);
-
- nodes = null;
- if(responseDoc instanceof SOAPPart)
- {
- SOAPPart soapPart = (SOAPPart) responseDoc;
- SOAPEnvelope env = soapPart.getEnvelope();
- SOAPBody body = env.getBody();
- Node data = body.getFirstChild();
- nodes = ((Element)data).getElementsByTagName("RequestedSecurityToken");
- }
- else
- nodes = responseDoc.getElementsByTagNameNS(WSTrustConstants.BASE_NAMESPACE, "RequestedSecurityToken");
- }
- catch (Exception e)
- {
- throw new WSTrustException("Exception in renewing token:", e);
- }
-
- if(nodes == null)
- throw new WSTrustException("NodeList is null");
-
- Node rstr = nodes.item(0);
-
- return (Element) rstr.getFirstChild();
-
- }
-
- public boolean validateToken(Element token) throws WSTrustException
- {
- RequestSecurityToken request = new RequestSecurityToken();
- request.setContext("context");
-
- request.setTokenType(URI.create(WSTrustConstants.STATUS_TYPE));
- request.setRequestType(URI.create(WSTrustConstants.VALIDATE_REQUEST));
- ValidateTargetType validateTarget = new ValidateTargetType();
- validateTarget.setAny(token);
- request.setValidateTarget(validateTarget);
+ /**
+ * The STSClient that this class delegates to.
+ */
+ private STSClient stsClient;
+
+ public static class SecurityInfo
+ {
+ private String username;
+ private String passwd;
- WSTrustJAXBFactory jaxbFactory = WSTrustJAXBFactory.getInstance();
-
- DOMSource requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
-
- Source response = dispatchLocal.get().invoke(requestSource);
- RequestSecurityTokenResponseCollection
- responseCollection = (RequestSecurityTokenResponseCollection) jaxbFactory
- .parseRequestSecurityTokenResponse(response);
- RequestSecurityTokenResponse tokenResponse = responseCollection.getRequestSecurityTokenResponses().get(0);
+ public SecurityInfo(String name, char[] pass)
+ {
+ username = name;
+ passwd = new String(pass);
+ }
- StatusType status = tokenResponse.getStatus();
- if (status != null)
- {
- String code = status.getCode();
- return WSTrustConstants.STATUS_CODE_VALID.equals(code);
- }
- return false;
- }
-
- public Dispatch<Source> getDispatch()
- {
- return dispatchLocal.get();
- }
+ public SecurityInfo(String name, String pass)
+ {
+ username = name;
+ passwd = pass;
+ }
+ }
+
+ public WSTrustClient(String serviceName, String port, String endpointURI, SecurityInfo secInfo) throws ParsingException
+ {
+ Builder builder = new STSClientConfig.Builder();
+ builder.serviceName(serviceName).portName(port).endpointAddress(endpointURI).username(secInfo.username).password(secInfo.passwd);
+ stsClient = STSClientFactory.getInstance().create(builder.build());
+ }
+
+ /**
+ * This method will send a RequestSecurityToken with a RequestType of issue
+ * and the passed-in tokenType identifies the type of token to be issued by
+ * the STS.
+ *
+ * @param tokenType - The type of token to be issued.
+ * @return Element - The Security Token element. Will be of the tokenType specified.
+ * @throws WSTrustException
+ */
+ public Element issueToken(String tokenType) throws WSTrustException
+ {
+ return stsClient.issueToken(tokenType);
+ }
+
+ /**
+ * This method will send a RequestSecurityToken with a RequestType of renew
+ * and the passed-in tokenType identifies the type of token to be renewed by
+ * the STS.
+ *
+ * @param tokenType - The type of token to be renewed.
+ * @param token - The security token to be renewed.
+ * @return Element - The Security Token element. Will be of the tokenType specified.
+ */
+ public Element renewToken(String tokenType, Element token) throws WSTrustException
+ {
+ return stsClient.renewToken(tokenType, token);
+
+ }
+
+ /**
+ * This method will send a RequestSecurityToken with a RequestType of validated by
+ * the STS.
+ *
+ * @param token - The security token to be validated.
+ * @return true - If the security token was sucessfully valiated.
+ */
+ public boolean validateToken(Element token) throws WSTrustException
+ {
+ return stsClient.validateToken(token);
+ }
+
}
\ No newline at end of file
Deleted: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientConfig.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientConfig.java 2009-09-24 01:24:30 UTC (rev 808)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientConfig.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -1,242 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
- * LLC, and individual contributors by the @authors tag. See the copyright.txt
- * in the distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it under the
- * terms of the GNU Lesser General Public License as published by the Free
- * Software Foundation; either version 2.1 of the License, or (at your option)
- * any later version.
- *
- * This software is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
- * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
- * details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this software; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
- * site: http://www.fsf.org.
- */
-package org.jboss.identity.federation.api.wstrust;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-/**
- * WSTrustClientConfig has the ability to either programatically construct
- * the configuration needed for {@link WSTrustClient} or parse a file
- * containing the configuration parameters.
- * <p/>
- *
- * <h3>Configure programatically</h3>
- * <pre>{@code
- *
- * Builder builder = new WSTrustClientConfig.Builder();
- * builder.serviceName("JBossSTS");
- * builder.portName("JBossSTSPort");
- * ...
- * WSTrustClientConfig config = builder.build();
- *
- * }</pre>
- *
- * <h3>Configure from file</h3>
- * <pre>{@code
- *
- * WSTrustClientConfig config = new WSTrustClientConfig.Builder().build(configFile);
- *
- * }</pre>
- *
- * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
- */
-public class WSTrustClientConfig
-{
- public static final String DEFAULT_CONFIG_FILE = "jboss-sts-client.properties";
-
- public static final String SERVICE_NAME = "serviceName";
- public static final String PORT_NAME = "portName";
- public static final String ENDPOINT_ADDRESS = "endpointAddress";
- public static final String USERNAME = "username";
- public static final String PASSWORD = "password";
- public static final String TOKEN_TYPE = "tokenType";
-
- private String serviceName;
- private String portName;
- private String endpointAddress;
- private String username;
- private String password;
-
- private WSTrustClientConfig(final Builder builder)
- {
- serviceName = builder.serviceName;
- portName = builder.portName;
- endpointAddress = builder.endpointAddress;
- username = builder.username;
- password = builder.password;
- }
-
- public String getServiceName()
- {
- return serviceName;
- }
-
- public String getPortName()
- {
- return portName;
- }
-
- public String getEndPointAddress()
- {
- return endpointAddress;
- }
-
- public String getUsername()
- {
- return username;
- }
-
- public String getPassword()
- {
- return password;
- }
-
- public String toString()
- {
- return getClass().getSimpleName() + "[serviceName=" + serviceName + ", portName=" + portName + ", endpointAddress=" + endpointAddress + "]";
- }
-
- public static class Builder
- {
- private String serviceName;
- private String portName;
- private String endpointAddress;
- private String username;
- private String password;
-
- public Builder serviceName(final String serviceName)
- {
- this.serviceName = serviceName;
- return this;
- }
-
- public Builder portName(final String portName)
- {
- this.portName = portName;
- return this;
- }
-
- public Builder endpointAddress(final String address)
- {
- this.endpointAddress = address;
- return this;
- }
-
- public Builder username(final String username)
- {
- this.username = username;
- return this;
- }
-
- public Builder password(final String password)
- {
- this.password = password;
- return this;
- }
-
- public WSTrustClientConfig build()
- {
- validate(this);
- return new WSTrustClientConfig(this);
- }
-
- private void validate(Builder builder)
- {
- checkPropertyShowValue(serviceName, SERVICE_NAME);
- checkPropertyShowValue(portName, PORT_NAME);
- checkPropertyShowValue(endpointAddress, endpointAddress);
- checkProperty(username, USERNAME);
- checkProperty(password, PASSWORD);
- }
-
- private void checkPropertyShowValue(final String propertyName, final String propertyValue)
- {
- if (propertyValue == null || propertyValue.equals(""))
- throw new IllegalArgumentException(propertyName + " property must not be null or empty was:" + propertyValue);
- }
-
- private void checkProperty(final String propertyName, final String propertyValue)
- {
- if (propertyValue == null || propertyValue.equals(""))
- throw new IllegalArgumentException(propertyName + " property must not be null");
- }
-
- public WSTrustClientConfig build(final String configFile)
- {
- InputStream in = null;
-
- try
- {
- in = getResource(configFile);
- if (in == null)
- {
- throw new IllegalStateException("Could not find properties file " + configFile);
-
- }
- final Properties properties = new Properties();
- properties.load(in);
- this.serviceName = properties.getProperty(SERVICE_NAME);
- this.portName = properties.getProperty(PORT_NAME);
- this.endpointAddress = properties.getProperty(ENDPOINT_ADDRESS);
- this.username = properties.getProperty(USERNAME);
- this.password = properties.getProperty(PASSWORD);
- }
- catch (IOException e)
- {
- throw new IllegalStateException("Could not load properties from " + configFile);
- }
- finally
- {
- try
- {
- if (in != null)
- in.close();
- }
- catch (final IOException ignored)
- {
- ignored.printStackTrace();
- }
- }
-
- validate(this);
- return new WSTrustClientConfig(this);
- }
- }
-
- private static InputStream getResource(String resource) throws IOException
- {
- // Try it as a File resource...
- final File file = new File(resource);
-
- if (file.exists() && !file.isDirectory())
- {
- return new FileInputStream(file);
- }
- // Try it as a classpath resource ...
- final ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader() ;
- if (threadClassLoader != null)
- {
- final InputStream is = threadClassLoader.getResourceAsStream(resource) ;
- if (is != null)
- {
- return is ;
- }
- }
-
- return null;
- }
-
-}
-
Deleted: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientFactory.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientFactory.java 2009-09-24 01:24:30 UTC (rev 808)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientFactory.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -1,50 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
- * LLC, and individual contributors by the @authors tag. See the copyright.txt
- * in the distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it under the
- * terms of the GNU Lesser General Public License as published by the Free
- * Software Foundation; either version 2.1 of the License, or (at your option)
- * any later version.
- *
- * This software is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
- * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
- * details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this software; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
- * site: http://www.fsf.org.
- */
-package org.jboss.identity.federation.api.wstrust;
-
-import org.jboss.identity.federation.api.wstrust.WSTrustClient;
-import org.jboss.identity.federation.api.wstrust.WSTrustClient.SecurityInfo;
-import org.jboss.identity.federation.core.exceptions.ParsingException;
-
-/**
- * Simple factory for creating {@link WSTrustClient}s.
- *
- * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
- */
-public final class WSTrustClientFactory
-{
- private static final WSTrustClientFactory INSTANCE = new WSTrustClientFactory();
-
- private WSTrustClientFactory()
- {
- }
-
- public static WSTrustClientFactory getInstance()
- {
- return INSTANCE;
- }
-
- public WSTrustClient create(final WSTrustClientConfig c) throws ParsingException
- {
- return new WSTrustClient(c.getServiceName(), c.getPortName(), c.getEndPointAddress(), new SecurityInfo(c.getUsername(), c.getPassword()));
- }
-}
-
Modified: identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/WSTrustClientUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/WSTrustClientUnitTestCase.java 2009-09-24 01:24:30 UTC (rev 808)
+++ identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/WSTrustClientUnitTestCase.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -48,12 +48,12 @@
import junit.framework.TestCase;
import org.jboss.identity.federation.api.wstrust.WSTrustClient;
-import org.jboss.identity.federation.api.wstrust.WSTrustClient.SecurityInfo;
import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
import org.jboss.identity.federation.core.util.KeyStoreUtil;
import org.jboss.identity.federation.core.util.XMLSignatureUtil;
import org.jboss.identity.federation.core.wstrust.WSTrustConstants;
import org.jboss.identity.federation.core.wstrust.WSTrustJAXBFactory;
+import org.jboss.identity.federation.api.wstrust.WSTrustClient.SecurityInfo;
import org.jboss.identity.federation.core.wstrust.plugins.saml.SAMLUtil;
import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityToken;
import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponse;
Deleted: identity-federation/trunk/jboss-identity-fed-api/src/test/resources/wstrust/jboss-sts-client.properties
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/test/resources/wstrust/jboss-sts-client.properties 2009-09-24 01:24:30 UTC (rev 808)
+++ identity-federation/trunk/jboss-identity-fed-api/src/test/resources/wstrust/jboss-sts-client.properties 2009-09-25 08:00:27 UTC (rev 809)
@@ -1,5 +0,0 @@
-serviceName=JBossSTS
-portName=JBossSTSPort
-endpointAddress=http://localhost:8080/jboss-sts/JBossSTS
-username=admin
-password=admin
Modified: identity-federation/trunk/jboss-identity-fed-core/pom.xml
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/pom.xml 2009-09-24 01:24:30 UTC (rev 808)
+++ identity-federation/trunk/jboss-identity-fed-core/pom.xml 2009-09-25 08:00:27 UTC (rev 809)
@@ -84,6 +84,30 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>1.8.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss.ws.native</groupId>
+ <artifactId>jbossws-native-client</artifactId>
+ <version>3.1.2.SP3</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>xml-apis</groupId>
+ <artifactId>xml-apis</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.jboss</groupId>
+ <artifactId>jboss-common-core</artifactId>
+ <version>2.2.14.GA</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<reporting>
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClient.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,218 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.wstrust;
+
+import java.net.URI;
+import java.util.Map;
+
+import javax.xml.namespace.QName;
+import javax.xml.soap.SOAPBody;
+import javax.xml.soap.SOAPEnvelope;
+import javax.xml.soap.SOAPPart;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.ws.BindingProvider;
+import javax.xml.ws.Dispatch;
+import javax.xml.ws.Service;
+import javax.xml.ws.Service.Mode;
+import javax.xml.ws.soap.SOAPBinding;
+
+import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
+import org.jboss.identity.federation.core.wstrust.WSTrustConstants;
+import org.jboss.identity.federation.core.wstrust.WSTrustException;
+import org.jboss.identity.federation.core.wstrust.WSTrustJAXBFactory;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityToken;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponse;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponseCollection;
+import org.jboss.identity.federation.ws.trust.RenewTargetType;
+import org.jboss.identity.federation.ws.trust.StatusType;
+import org.jboss.identity.federation.ws.trust.ValidateTargetType;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * WS-Trust Client
+ *
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Aug 29, 2009
+ */
+public class STSClient
+{
+ private ThreadLocal<Dispatch<Source>> dispatchLocal = new InheritableThreadLocal<Dispatch<Source>>();
+
+ private String targetNS = "http://org.jboss.identity.trust/sts/";
+
+ public STSClient(STSClientConfig config)
+ {
+ QName service = new QName(targetNS, config.getServiceName());
+ QName portName = new QName(targetNS, config.getPortName());
+
+ Service jaxwsService = Service.create(service);
+ jaxwsService.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, config.getEndPointAddress());
+ Dispatch<Source> dispatch = jaxwsService.createDispatch(portName, Source.class, Mode.PAYLOAD);
+
+ Map<String, Object> reqContext = dispatch.getRequestContext();
+ String username = config.getUsername();
+ if (username != null)
+ {
+ // add the username and password to the request context.
+ reqContext.put(BindingProvider.USERNAME_PROPERTY, config.getUsername());
+ reqContext.put(BindingProvider.PASSWORD_PROPERTY, config.getPassword());
+ }
+ dispatchLocal.set(dispatch);
+ }
+
+ public Element issueToken(String tokenType) throws WSTrustException
+ {
+ // create a custom token request message.
+ RequestSecurityToken request = new RequestSecurityToken();
+ request.setTokenType(URI.create(tokenType));
+ request.setRequestType(URI.create(WSTrustConstants.ISSUE_REQUEST));
+ request.setContext("context");
+
+ // send the token request to JBoss STS and get the response.
+ WSTrustJAXBFactory jaxbFactory = WSTrustJAXBFactory.getInstance();
+ DOMSource requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
+ Source response = dispatchLocal.get().invoke(requestSource);
+
+ Node documentNode = ((DOMSource) response).getNode();
+ Document responseDoc = documentNode instanceof Document ? (Document) documentNode : documentNode.getOwnerDocument();
+
+ NodeList nodes;
+ try
+ {
+ Document myDocument = DocumentUtil.createDocument();
+ Node importedNode = myDocument.importNode(responseDoc.getDocumentElement(), true);
+ myDocument.appendChild(importedNode);
+
+ nodes = null;
+ if (responseDoc instanceof SOAPPart)
+ {
+ SOAPPart soapPart = (SOAPPart) responseDoc;
+ SOAPEnvelope env = soapPart.getEnvelope();
+ SOAPBody body = env.getBody();
+ Node data = body.getFirstChild();
+ nodes = ((Element) data).getElementsByTagName("RequestedSecurityToken");
+ }
+ else
+ nodes = responseDoc.getElementsByTagNameNS(WSTrustConstants.BASE_NAMESPACE, "RequestedSecurityToken");
+ }
+ catch (Exception e)
+ {
+ throw new WSTrustException("Exception in issuing token:", e);
+ }
+
+ if (nodes == null)
+ throw new WSTrustException("NodeList is null");
+
+ Node rstr = nodes.item(0);
+
+ return (Element) rstr.getFirstChild();
+ }
+
+ public Element renewToken(String tokenType, Element token) throws WSTrustException
+ {
+ RequestSecurityToken request = new RequestSecurityToken();
+ request.setContext("context");
+
+ request.setTokenType(URI.create(WSTrustConstants.STATUS_TYPE));
+ request.setRequestType(URI.create(WSTrustConstants.RENEW_REQUEST));
+ RenewTargetType renewTarget = new RenewTargetType();
+ renewTarget.setAny(token);
+ request.setRenewTarget(renewTarget);
+
+ // send the token request to JBoss STS and get the response.
+ WSTrustJAXBFactory jaxbFactory = WSTrustJAXBFactory.getInstance();
+ DOMSource requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
+ Source response = dispatchLocal.get().invoke(requestSource);
+
+ Node documentNode = ((DOMSource) response).getNode();
+ Document responseDoc = documentNode instanceof Document ? (Document) documentNode : documentNode.getOwnerDocument();
+
+ NodeList nodes;
+ try
+ {
+ Document myDocument = DocumentUtil.createDocument();
+ Node importedNode = myDocument.importNode(responseDoc.getDocumentElement(), true);
+ myDocument.appendChild(importedNode);
+
+ nodes = null;
+ if (responseDoc instanceof SOAPPart)
+ {
+ SOAPPart soapPart = (SOAPPart) responseDoc;
+ SOAPEnvelope env = soapPart.getEnvelope();
+ SOAPBody body = env.getBody();
+ Node data = body.getFirstChild();
+ nodes = ((Element) data).getElementsByTagName("RequestedSecurityToken");
+ }
+ else
+ nodes = responseDoc.getElementsByTagNameNS(WSTrustConstants.BASE_NAMESPACE, "RequestedSecurityToken");
+ }
+ catch (Exception e)
+ {
+ throw new WSTrustException("Exception in renewing token:", e);
+ }
+
+ if (nodes == null)
+ throw new WSTrustException("NodeList is null");
+
+ Node rstr = nodes.item(0);
+
+ return (Element) rstr.getFirstChild();
+
+ }
+
+ public boolean validateToken(Element token) throws WSTrustException
+ {
+ RequestSecurityToken request = new RequestSecurityToken();
+ request.setContext("context");
+
+ request.setTokenType(URI.create(WSTrustConstants.STATUS_TYPE));
+ request.setRequestType(URI.create(WSTrustConstants.VALIDATE_REQUEST));
+ ValidateTargetType validateTarget = new ValidateTargetType();
+ validateTarget.setAny(token);
+ request.setValidateTarget(validateTarget);
+
+ WSTrustJAXBFactory jaxbFactory = WSTrustJAXBFactory.getInstance();
+
+ DOMSource requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
+
+ Source response = dispatchLocal.get().invoke(requestSource);
+ RequestSecurityTokenResponseCollection responseCollection = (RequestSecurityTokenResponseCollection) jaxbFactory.parseRequestSecurityTokenResponse(response);
+ RequestSecurityTokenResponse tokenResponse = responseCollection.getRequestSecurityTokenResponses().get(0);
+
+ StatusType status = tokenResponse.getStatus();
+ if (status != null)
+ {
+ String code = status.getCode();
+ return WSTrustConstants.STATUS_CODE_VALID.equals(code);
+ }
+ return false;
+ }
+
+ public Dispatch<Source> getDispatch()
+ {
+ return dispatchLocal.get();
+ }
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClientConfig.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClientConfig.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClientConfig.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,239 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.wstrust;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * STSClientConfig has the ability to either programatically construct the configuration
+ * needed for {@link STSClient} or parse a file containing the configuration parameters.
+ * <p/>
+ *
+ * <h3>Configure programatically</h3>
+ * Example:
+ * <pre>{@code
+ * Builder builder = new STSClientConfig.Builder();
+ * builder.serviceName("JBossSTS");
+ * builder.portName("JBossSTSPort");
+ * ...
+ * STSClientConfig config = builder.build();
+ * }</pre>
+ *
+ * <h3>Configure from file</h3>
+ * Example:
+ * <pre>{@code
+ * STSClientConfig config = new STSClientConfig.Builder().build(configFile);
+ * }</pre>
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ */
+public class STSClientConfig
+{
+ public static final String DEFAULT_CONFIG_FILE = "sts-client.properties";
+
+ public static final String SERVICE_NAME = "serviceName";
+ public static final String PORT_NAME = "portName";
+ public static final String ENDPOINT_ADDRESS = "endpointAddress";
+ public static final String USERNAME = "username";
+ public static final String PASSWORD = "password";
+ public static final String TOKEN_TYPE = "tokenType";
+
+ private String serviceName;
+ private String portName;
+ private String endpointAddress;
+ private String username;
+ private String password;
+
+ private STSClientConfig(final Builder builder)
+ {
+ serviceName = builder.serviceName;
+ portName = builder.portName;
+ endpointAddress = builder.endpointAddress;
+ username = builder.username;
+ password = builder.password;
+ }
+
+ public String getServiceName()
+ {
+ return serviceName;
+ }
+
+ public String getPortName()
+ {
+ return portName;
+ }
+
+ public String getEndPointAddress()
+ {
+ return endpointAddress;
+ }
+
+ public String getUsername()
+ {
+ return username;
+ }
+
+ public String getPassword()
+ {
+ return password;
+ }
+
+ public String toString()
+ {
+ return getClass().getSimpleName() + "[serviceName=" + serviceName + ", portName=" + portName + ", endpointAddress=" + endpointAddress + "]";
+ }
+
+ public static class Builder
+ {
+ private String serviceName;
+ private String portName;
+ private String endpointAddress;
+ private String username;
+ private String password;
+
+ public Builder serviceName(final String serviceName)
+ {
+ this.serviceName = serviceName;
+ return this;
+ }
+
+ public Builder portName(final String portName)
+ {
+ this.portName = portName;
+ return this;
+ }
+
+ public Builder endpointAddress(final String address)
+ {
+ this.endpointAddress = address;
+ return this;
+ }
+
+ public Builder username(final String username)
+ {
+ this.username = username;
+ return this;
+ }
+
+ public Builder password(final String password)
+ {
+ this.password = password;
+ return this;
+ }
+
+ public STSClientConfig build()
+ {
+ validate(this);
+ return new STSClientConfig(this);
+ }
+
+ private void validate(Builder builder)
+ {
+ checkPropertyShowValue(serviceName, SERVICE_NAME);
+ checkPropertyShowValue(portName, PORT_NAME);
+ checkPropertyShowValue(endpointAddress, endpointAddress);
+ checkProperty(username, USERNAME);
+ checkProperty(password, PASSWORD);
+ }
+
+ private void checkPropertyShowValue(final String propertyName, final String propertyValue)
+ {
+ if (propertyValue == null || propertyValue.equals(""))
+ throw new IllegalArgumentException(propertyName + " property must not be null or empty was:" + propertyValue);
+ }
+
+ private void checkProperty(final String propertyName, final String propertyValue)
+ {
+ if (propertyValue == null || propertyValue.equals(""))
+ throw new IllegalArgumentException(propertyName + " property must not be null");
+ }
+
+ public STSClientConfig build(final String configFile)
+ {
+ InputStream in = null;
+
+ try
+ {
+ in = getResource(configFile);
+ if (in == null)
+ {
+ throw new IllegalStateException("Could not find properties file " + configFile);
+
+ }
+ final Properties properties = new Properties();
+ properties.load(in);
+ this.serviceName = properties.getProperty(SERVICE_NAME);
+ this.portName = properties.getProperty(PORT_NAME);
+ this.endpointAddress = properties.getProperty(ENDPOINT_ADDRESS);
+ this.username = properties.getProperty(USERNAME);
+ this.password = properties.getProperty(PASSWORD);
+ }
+ catch (IOException e)
+ {
+ throw new IllegalStateException("Could not load properties from " + configFile);
+ }
+ finally
+ {
+ try
+ {
+ if (in != null)
+ in.close();
+ }
+ catch (final IOException ignored)
+ {
+ ignored.printStackTrace();
+ }
+ }
+
+ validate(this);
+ return new STSClientConfig(this);
+ }
+ }
+
+ private static InputStream getResource(String resource) throws IOException
+ {
+ // Try it as a File resource...
+ final File file = new File(resource);
+
+ if (file.exists() && !file.isDirectory())
+ {
+ return new FileInputStream(file);
+ }
+ // Try it as a classpath resource ...
+ final ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader() ;
+ if (threadClassLoader != null)
+ {
+ final InputStream is = threadClassLoader.getResourceAsStream(resource) ;
+ if (is != null)
+ {
+ return is ;
+ }
+ }
+
+ return null;
+ }
+
+}
+
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClientFactory.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClientFactory.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/STSClientFactory.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,48 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.wstrust;
+
+import org.jboss.identity.federation.core.exceptions.ParsingException;
+
+/**
+ * Simple factory for creating {@link STSClient}s.
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ */
+public final class STSClientFactory
+{
+ private static final STSClientFactory INSTANCE = new STSClientFactory();
+
+ private STSClientFactory()
+ {
+ }
+
+ public static STSClientFactory getInstance()
+ {
+ return INSTANCE;
+ }
+
+ public STSClient create(final STSClientConfig config) throws ParsingException
+ {
+ return new STSClient(config);
+ }
+}
+
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/STSSaml20Handler.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/STSSaml20Handler.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/STSSaml20Handler.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,67 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.wstrust.handlers;
+
+import static org.jboss.identity.federation.core.wstrust.WSTrustConstants.WSSE_NS;
+import static org.jboss.identity.federation.core.wstrust.WSTrustConstants.SAML2_ASSERTION_NS;
+import javax.xml.namespace.QName;
+
+
+/**
+ * A concrete implementation of {@link STSSecurityHandler} that can handle SAML
+ * version 2.0 Assertion inside of {@link WSTrustConstants#WSSE_NS} elements.
+ * <p/>
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ */
+public class STSSaml20Handler extends STSSecurityHandler
+{
+ /**
+ * Qualified name for WSSE Security Header ({@link WSTrustConstants#WSSE_NS}:"Security")
+ */
+ public static final QName SECURITY_QNAME = new QName(WSSE_NS, "Security");
+
+ /**
+ * Qualified name for SAML Version 2.0 ({@link WSTrustConstants#SAML2_ASSERTION_NS}:"Assertion")
+ */
+ public static final QName SAML_TOKEN_QNAME = new QName(SAML2_ASSERTION_NS, "Assertion");
+
+ /*
+ * (non-Javadoc)
+ * @see org.jboss.identity.federation.api.wstrust.handlers.JBossSTSSecurityHandler#getSecurityElementQName()
+ */
+ @Override
+ public QName getSecurityElementQName()
+ {
+ return SECURITY_QNAME;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.jboss.identity.federation.api.wstrust.handlers.JBossSTSSecurityHandler#getTokenElementQName()
+ */
+ @Override
+ public QName getTokenElementQName()
+ {
+ return SAML_TOKEN_QNAME;
+ }
+
+}
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/STSSecurityHandler.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/STSSecurityHandler.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/handlers/STSSecurityHandler.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,259 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.wstrust.handlers;
+
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import javax.xml.namespace.QName;
+import javax.xml.soap.SOAPException;
+import javax.xml.soap.SOAPHeader;
+import javax.xml.soap.SOAPHeaderElement;
+import javax.xml.ws.WebServiceException;
+import javax.xml.ws.handler.MessageContext;
+import javax.xml.ws.handler.soap.SOAPHandler;
+import javax.xml.ws.handler.soap.SOAPMessageContext;
+
+import org.jboss.identity.federation.core.wstrust.STSClient;
+import org.jboss.identity.federation.core.wstrust.STSClientConfig;
+import org.jboss.identity.federation.core.wstrust.STSClientFactory;
+import org.jboss.identity.federation.core.exceptions.ParsingException;
+import org.jboss.identity.federation.core.wstrust.WSTrustException;
+import org.w3c.dom.Element;
+
+/**
+ * STSSecurityHandler is a server-side JAX-WS SOAP Protocol handler that will extract a
+ * Security Token from the SOAP Security Header and validate the token with the configured
+ * Security Token Service (STS).
+ * <p/>
+ *
+ * This class is abstract to simpify is usage as the intention is for a handler to be specified
+ * in a server side handler chain. Here different Security Header specifications and security token
+ * specifications can be specified using class names instead of using properties which would force
+ * users to finding and setting the correct namespaces. Hopefully this will be easier and less
+ * error prone.
+ *
+ * <h3>Concrete implementations</h3>
+ * Subclasses a required to implement two methods:
+ * <ul>
+ * <li> {@link #getSecurityElementQName()}
+ * This should return the qualified name of the security header. This lets us support
+ * different versions. </li>
+ *
+ * <li>{@link #getTokenElementQName()}
+ * This should return the qualified name of the security token element that should exist
+ * in the security header. This lets us support different tokens that can be validated
+ * with the configured STS.</li>
+ * </ul>
+ *
+ * <h3>Configuration</h3>
+ * handlerchain.xml example:
+ * <pre>{@code
+ * <?xml version="1.0" encoding="UTF-8"?>
+ * <jws:handler-config xmlns:jws="http://java.sun.com/xml/ns/javaee">
+ * <jws:handler-chains>
+ * <jws:handler-chain>
+ * <jws:handler>
+ * <jws:handler-class>org.jboss.identity.federation.core.wstrust.handlers.STSSaml20Handler</jws:handler-class>
+ * </jws:handler>
+ * </jws:handler-chain>
+ * </jws:handler-chains>
+ * </jws:handler-config>
+ * }</pre>
+ * <p/>
+ *
+ * This class uses {@link STSClient} to interact with an STS. By default the configuration
+ * properties are set in a file named {@link STSClientConfig#DEFAULT_CONFIG_FILE}.
+ * This can be overridden by specifying environment entries in a deployment descriptor.
+ *
+ * For example in web.xml:
+ * <pre>{@code
+ * <env-entry>
+ * <env-entry-name>STSClientConfig</env-entry-name>
+ * <env-entry-type>java.lang.String</env-entry-type>
+ * <env-entry-value>/sts-client.properties</env-entry-value>
+ * </env-entry>
+ * }</pre>
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ */
+public abstract class STSSecurityHandler implements SOAPHandler<SOAPMessageContext>
+{
+ /**
+ * The path to the jboss-sts-client.properties file.
+ */
+ private String configFile = STSClientConfig.DEFAULT_CONFIG_FILE;
+
+ /**
+ * The {@link STSClient client} that will call the STS.
+ */
+ private STSClient wsTrustClient;
+
+ /**
+ * Subclasses can return the QName of the Security header element in usage.
+ *
+ * @return QName
+ */
+ public abstract QName getSecurityElementQName();
+
+ /**
+ * Subclasses can return the QName of the Security Element that should be used
+ * as the token for validation.
+ *
+ * @return QName
+ */
+ public abstract QName getTokenElementQName();
+
+ /**
+ * Post constuct will be called when the handler is deployed.
+ *
+ * @throws WebServiceException
+ */
+ @PostConstruct
+ public void createWSTrustClient()
+ {
+ if (wsTrustClient == null)
+ {
+ try
+ {
+ final STSClientConfig config = new STSClientConfig.Builder().build(configFile);
+ wsTrustClient = STSClientFactory.getInstance().create(config);
+ }
+ catch (final ParsingException e)
+ {
+ throw new IllegalStateException(e.getMessage(), e);
+ }
+ }
+ }
+
+ /**
+ * Will process in-bound messages and extract a security token from the SOAP Header. This token
+ * will then be validated using by calling the STS..
+ *
+ * @param messageContext The {@link SOAPMessageContext messageContext}.
+ * @return true If the security token was correctly validated or if this call was an outbound message.
+ * @throws WebServiceException If the security token could not be validated.
+ */
+ public boolean handleMessage(final SOAPMessageContext messageContext)
+ {
+ if (isOutBound(messageContext))
+ {
+ return true;
+ }
+
+ try
+ {
+ final Element securityToken = extractSecurityToken(messageContext, getSecurityElementQName(), getTokenElementQName());
+
+ if (wsTrustClient.validateToken(securityToken))
+ {
+ return true;
+ }
+ else
+ {
+ throw new WebServiceException("Could not validate security token "+ securityToken);
+ }
+ }
+ catch (final SOAPException e)
+ {
+ throw new WebServiceException(e.getMessage(), e);
+ }
+ catch (final WSTrustException e)
+ {
+ throw new WebServiceException(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Allows the {@link STSClient} to be injected if required.
+ *
+ * @param client The WSTrustClient to be used by this handler.
+ */
+ public void setWSTrustClient(final STSClient client)
+ {
+ wsTrustClient = client;
+ }
+
+ public Set<QName> getHeaders()
+ {
+ return Collections.singleton(getSecurityElementQName());
+ }
+
+ public boolean handleFault(final SOAPMessageContext messageContext)
+ {
+ return true;
+ }
+
+ public void close(final MessageContext messageContext)
+ {
+ // NoOp.
+ }
+
+
+ /**
+ * This setter enables the injection of the jboss-sts-client.properties file
+ * path.
+ *
+ * @param configFile
+ */
+ @Resource (name = "STSClientConfig")
+ public void setConfigFile(final String configFile)
+ {
+ if (configFile != null)
+ {
+ this.configFile = configFile;
+ }
+ }
+
+ private boolean isOutBound(final SOAPMessageContext messageContext)
+ {
+ return ((Boolean) messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue();
+ }
+
+ @SuppressWarnings("unchecked")
+ private Element extractSecurityToken(final SOAPMessageContext messageContext, final QName securityQName, final QName tokenQName) throws SOAPException
+ {
+ if (securityQName == null)
+ throw new IllegalStateException("securityQName from subclass cannot be null!");
+ if (tokenQName == null)
+ throw new IllegalStateException("tokenQName from subclass cannot be null!");
+
+ final SOAPHeader soapHeader = messageContext.getMessage().getSOAPHeader();
+ final Iterator securityHeaders = soapHeader.getChildElements(securityQName);
+ while (securityHeaders.hasNext())
+ {
+ final SOAPHeaderElement elem = (SOAPHeaderElement) securityHeaders.next();
+ // Check if the header is equal to the one this Handler is configured for.
+ if (elem.getElementQName().equals(securityQName))
+ {
+ final Iterator childElements = elem.getChildElements(tokenQName);
+ while (childElements.hasNext())
+ {
+ return (Element) childElements.next();
+ }
+ }
+ }
+ return null;
+ }
+}
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientConfigUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientConfigUnitTestCase.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientConfigUnitTestCase.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,68 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.test.identity.federation.core.wstrust;
+
+import org.jboss.identity.federation.core.wstrust.STSClientConfig;
+import org.jboss.identity.federation.core.wstrust.STSClientConfig.Builder;
+import org.junit.Test;
+
+import junit.framework.TestCase;
+
+/**
+ * Unit test for {@link WSTrustClientConfig}.
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ *
+ */
+public class STSClientConfigUnitTestCase extends TestCase
+{
+ final String serviceName = "JBossSTS";
+ final String portName = "JBossSTSPort";
+ final String endpointAddress = "http://localhost:8080/jboss-sts/JBossSTS";
+ final String username = "admin";
+ final String password = "admin";
+
+ @Test
+ public void testBuild()
+ {
+ final Builder builder = new STSClientConfig.Builder();
+ final STSClientConfig config = builder.serviceName(serviceName).portName(portName).endpointAddress(endpointAddress).username(username).password(password).build();
+ assertAllProperties(config);
+ }
+
+ public void testBuildFromConfigPropertiesFile()
+ {
+ final Builder builder = new STSClientConfig.Builder();
+ STSClientConfig config = builder.build("wstrust/sts-client.properties");
+ assertAllProperties(config);
+ }
+
+ private void assertAllProperties(final STSClientConfig config)
+ {
+ assertEquals(serviceName, config.getServiceName());
+ assertEquals(portName, config.getPortName());
+ assertEquals(endpointAddress, config.getEndPointAddress());
+ assertEquals(username, config.getUsername());
+ assertEquals(password, config.getPassword());
+
+ }
+
+}
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/STSClientUnitTestCase.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,238 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.identity.federation.core.wstrust;
+
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.security.KeyStore;
+import java.security.PublicKey;
+import java.util.Map;
+
+import javax.xml.bind.JAXBException;
+import javax.xml.namespace.QName;
+import javax.xml.soap.SOAPBody;
+import javax.xml.soap.SOAPEnvelope;
+import javax.xml.soap.SOAPPart;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.ws.BindingProvider;
+import javax.xml.ws.Dispatch;
+import javax.xml.ws.Service;
+import javax.xml.ws.Service.Mode;
+import javax.xml.ws.soap.SOAPBinding;
+
+import junit.framework.TestCase;
+
+import org.jboss.identity.federation.core.wstrust.STSClient;
+import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
+import org.jboss.identity.federation.core.util.KeyStoreUtil;
+import org.jboss.identity.federation.core.util.XMLSignatureUtil;
+import org.jboss.identity.federation.core.wstrust.STSClientConfig;
+import org.jboss.identity.federation.core.wstrust.WSTrustConstants;
+import org.jboss.identity.federation.core.wstrust.WSTrustJAXBFactory;
+import org.jboss.identity.federation.core.wstrust.STSClientConfig.Builder;
+import org.jboss.identity.federation.core.wstrust.plugins.saml.SAMLUtil;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityToken;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponse;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponseCollection;
+import org.jboss.identity.federation.ws.trust.StatusType;
+import org.jboss.identity.federation.ws.trust.ValidateTargetType;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+/**
+ * Unit tests for WS-Trust STS Clients
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Aug 26, 2009
+ */
+public class STSClientUnitTestCase extends TestCase
+{
+ //Specify whether this test is run as part of build
+ private boolean usetest = false;
+
+
+ public void testSTS() throws Exception
+ {
+ if(usetest == false)
+ return;
+
+ // create a dispatch object to invoke JBoss STSs.
+ Dispatch<Source> dispatch = createDispatch();
+
+ // create a custom token request message.
+ RequestSecurityToken request = new RequestSecurityToken();
+ request.setTokenType(URI.create(SAMLUtil.SAML2_TOKEN_TYPE));
+ request.setRequestType(URI.create(WSTrustConstants.ISSUE_REQUEST));
+ request.setContext("context");
+
+ // send the token request to JBoss STS and get the response.
+ WSTrustJAXBFactory jaxbFactory = WSTrustJAXBFactory.getInstance();
+ DOMSource requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
+ Source response = dispatch.invoke(requestSource);
+
+ Node documentNode = ((DOMSource) response).getNode();
+ Document responseDoc = documentNode instanceof Document ? (Document) documentNode : documentNode.getOwnerDocument();
+
+
+ Document myDocument = DocumentUtil.createDocument();
+
+ Node importedNode = myDocument.importNode(responseDoc.getDocumentElement(), true);
+
+ myDocument.appendChild(importedNode);
+
+ NodeList nodes = null;
+ if(responseDoc instanceof SOAPPart)
+ {
+ SOAPPart soapPart = (SOAPPart) responseDoc;
+ SOAPEnvelope env = soapPart.getEnvelope();
+ SOAPBody body = env.getBody();
+ Node data = body.getFirstChild();
+ nodes = ((Element)data).getElementsByTagName("RequestedSecurityToken");
+ }
+ else
+ nodes = responseDoc.getElementsByTagNameNS(WSTrustConstants.BASE_NAMESPACE, "RequestedSecurityToken");
+
+ assertNotNull("Nodelist not null", nodes);
+ Node rstr = nodes.item(0);
+ /*RequestSecurityTokenResponseCollection responseCollection = (RequestSecurityTokenResponseCollection) jaxbFactory.parseRequestSecurityTokenResponse(response);
+ RequestSecurityTokenResponse tokenResponse = responseCollection.getRequestSecurityTokenResponses().get(0);
+
+ // the SAML assertion is returned as an Element.
+ Element assertion = (Element) tokenResponse.getRequestedSecurityToken().getAny();*/
+ Element assertion = (Element) rstr.getFirstChild();
+ System.out.println("NAMESPACE=" + assertion.getNamespaceURI());
+
+// PublicKey key = getValidatingKey();
+// Document validate = DocumentUtil.createDocument();
+// validate.appendChild(validate.importNode(assertion, true));
+// System.out.println("Is token valid? " + XMLSignatureUtil.validate(validate, key));
+
+ // print the assertion for demonstration purposes.
+ System.out.println("\nSuccessfully issued a standard SAMLV2.0 Assertion!");
+ printAssertion(assertion);
+
+ ClassLoader tcl = Thread.currentThread().getContextClassLoader();
+ KeyStore ks = KeyStoreUtil.getKeyStore(tcl.getResource("keystore/sts_keystore.jks")
+ , "testpass".toCharArray());
+
+ PublicKey pk = KeyStoreUtil.getPublicKey(ks, "sts", "keypass".toCharArray());
+
+ assertNotNull("Public key is not null", pk);
+ Document tokenDocument = DocumentUtil.createDocument();
+ importedNode = tokenDocument.importNode(assertion, true);
+ tokenDocument.appendChild(importedNode);
+
+ //System.out.println("Going to validate:" + DocumentUtil.getDocumentAsString(tokenDocument));
+ //assertTrue("SignedInfo valid", XMLSignatureUtil.preCheckSignedInfo(tokenDocument));
+ //Locally we will validate the assertion
+ assertTrue("Recieved assertion sig valid", XMLSignatureUtil.validate(tokenDocument, pk));
+
+ // let's validate the received SAML assertion.
+ request.getAny().clear();
+ request.setTokenType(URI.create(WSTrustConstants.STATUS_TYPE));
+ request.setRequestType(URI.create(WSTrustConstants.VALIDATE_REQUEST));
+ ValidateTargetType validateTarget = new ValidateTargetType();
+ validateTarget.setAny(assertion);
+ request.setValidateTarget(validateTarget);
+
+ requestSource = (DOMSource) jaxbFactory.marshallRequestSecurityToken(request);
+
+ response = dispatch.invoke(requestSource);
+ RequestSecurityTokenResponseCollection
+ responseCollection = (RequestSecurityTokenResponseCollection) jaxbFactory
+ .parseRequestSecurityTokenResponse(response);
+ RequestSecurityTokenResponse tokenResponse = responseCollection.getRequestSecurityTokenResponses().get(0);
+
+ StatusType status = tokenResponse.getStatus();
+ if (status != null)
+ {
+ String code = status.getCode();
+ assertFalse("Signature is valid", WSTrustConstants.STATUS_CODE_INVALID.equals(code));
+
+ System.out.println("\n\nSAMLV2.0 Assertion successfuly validated!");
+ System.out.println("Validation status code: " + tokenResponse.getStatus().getCode());
+ System.out.println("Validation status reason: " + tokenResponse.getStatus().getReason());
+ }
+ else
+ System.out.println("\n\nFailed to validate SAMLV2.0 Assertion");
+ }
+
+ public void testIssue_Validate_Renew() throws Exception
+ {
+ if(usetest == false)
+ return;
+
+ String serviceName = "JBossSTS";
+ String portName = "JBossSTSPort";
+ String endpointAddress = "http://localhost:8080/jboss-sts/JBossSTS";
+ Builder builder = new STSClientConfig.Builder();
+ STSClientConfig config = builder.serviceName(serviceName).portName(portName).endpointAddress(endpointAddress).username("admin").password("admin").build();
+ STSClient client = new STSClient(config);
+ Element token = client.issueToken(SAMLUtil.SAML2_TOKEN_TYPE);
+ assertTrue("Token is valid" , client.validateToken(token));
+
+ Element renewedToken = client.renewToken(SAMLUtil.SAML2_TOKEN_TYPE, token);
+ System.out.println("Renewed Token=" + DocumentUtil.getNodeAsString(renewedToken));
+ }
+
+
+ private Dispatch<Source> createDispatch() throws MalformedURLException, JAXBException
+ {
+ // JBoss STS target information.
+ String targetNS = "http://org.jboss.identity.trust/sts/";
+ QName serviceName = new QName(targetNS, "JBossSTS");
+ QName portName = new QName(targetNS, "JBossSTSPort");
+ URL endpointAddress = new URL("http://localhost:8080/jboss-sts/JBossSTS");
+// URL securityConfigURL = new File("jboss-wsse-client.xml").toURI().toURL();
+
+ Service service = Service.create(serviceName);
+ service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress.toExternalForm());
+
+ // create the dispatch, setting the client security configuration file.
+ Dispatch<Source> dispatch = service.createDispatch(portName, Source.class, Mode.PAYLOAD);
+// ((ConfigProvider) dispatch).setSecurityConfig(securityConfigURL.toExternalForm());
+// ((ConfigProvider) dispatch).setConfigName("Standard WSSecurity Client");
+
+ // add the username and password to the request context.
+ Map<String, Object> reqContext = dispatch.getRequestContext();
+ reqContext.put(BindingProvider.USERNAME_PROPERTY, "admin");
+ reqContext.put(BindingProvider.PASSWORD_PROPERTY, "admin");
+
+ return dispatch;
+ }
+
+ private void printAssertion(Element assertion) throws Exception
+ {
+ TransformerFactory tranFactory = TransformerFactory.newInstance();
+ Transformer aTransformer = tranFactory.newTransformer();
+ Source src = new DOMSource(assertion);
+ Result dest = new StreamResult(System.out);
+ aTransformer.transform(src, dest);
+ }
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/handlers/STSSaml20HandlerTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/handlers/STSSaml20HandlerTestCase.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/handlers/STSSaml20HandlerTestCase.java 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,154 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.test.identity.federation.core.wstrust.handlers;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import javax.xml.namespace.QName;
+import javax.xml.soap.MessageFactory;
+import javax.xml.soap.SOAPElement;
+import javax.xml.soap.SOAPException;
+import javax.xml.soap.SOAPHeader;
+import javax.xml.soap.SOAPHeaderElement;
+import javax.xml.soap.SOAPMessage;
+import javax.xml.ws.WebServiceException;
+import javax.xml.ws.handler.MessageContext;
+import javax.xml.ws.handler.soap.SOAPMessageContext;
+
+import junit.framework.TestCase;
+
+import org.jboss.identity.federation.core.wstrust.STSClient;
+import org.jboss.identity.federation.core.wstrust.handlers.STSSaml20Handler;
+import org.jboss.identity.federation.core.wstrust.handlers.STSSecurityHandler;
+import org.w3c.dom.Element;
+
+/**
+ * Unit test for {@link STSSaml20Handler}.
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ *
+ */
+public class STSSaml20HandlerTestCase extends TestCase
+{
+ private SOAPMessageContext soapMessageContext;
+ private SOAPMessage soapMessage;
+ private STSClient wsTrustClient;
+ private STSSaml20Handler samlHandler;
+
+ public void testHandleMessageOutbound() throws SOAPException
+ {
+ setOutbound(soapMessageContext, true);
+ assertTrue(new STSSaml20Handler().handleMessage(soapMessageContext));
+ }
+
+ public void testHandleMessageInboundValidToken() throws Exception
+ {
+ final SOAPHeader soapHeader = soapMessage.getSOAPHeader();
+
+ // Make the Mocked WSTrustClient validateToken method return true.
+ when(wsTrustClient.validateToken((any(Element.class)))).thenReturn(true);
+
+ final SOAPHeaderElement securityHeader = addSecurityHeader(samlHandler, soapHeader);
+ addAssertionElement(samlHandler, securityHeader);
+
+ setOutbound(soapMessageContext, false);
+ setMessageOnContext(soapMessageContext, soapMessage);
+
+ boolean result = samlHandler.handleMessage(soapMessageContext);
+ assertTrue(result);
+ }
+
+ public void testHandleMessageInValidToken() throws Exception
+ {
+ final SOAPHeader soapHeader = soapMessage.getSOAPHeader();
+
+ // Make the Mocked WSTrustClient validateToken method return false.
+ when(wsTrustClient.validateToken((any(Element.class)))).thenReturn(false);
+
+ final SOAPHeaderElement securityHeader = addSecurityHeader(samlHandler, soapHeader);
+ addAssertionElement(samlHandler, securityHeader);
+
+ setOutbound(soapMessageContext, false);
+ setMessageOnContext(soapMessageContext, soapMessage);
+ try
+ {
+ samlHandler.handleMessage(soapMessageContext);
+ fail("handleMessage should have thrown a exception!");
+ }
+ catch(final Exception e)
+ {
+ assertTrue (e instanceof WebServiceException);
+ }
+ }
+
+ public void setUp()
+ {
+ // Create a Mock for WSTrustClient.
+ wsTrustClient = mock(STSClient.class);
+
+ samlHandler = new STSSaml20Handler();
+ // Set the WSTrustClient to our mocked client.
+ samlHandler.setWSTrustClient(wsTrustClient);
+ // Simulate the WS Engine calling @PostConstruct.
+ samlHandler.createWSTrustClient();
+
+ soapMessageContext = mock(SOAPMessageContext.class);
+
+ try
+ {
+ soapMessage = MessageFactory.newInstance().createMessage();
+ }
+ catch (SOAPException e)
+ {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
+
+ private SOAPHeaderElement addSecurityHeader(final STSSecurityHandler handler, final SOAPHeader soapHeader) throws SOAPException
+ {
+ final QName securityQName = handler.getSecurityElementQName();
+ final SOAPHeaderElement securityHeader = soapHeader.addHeaderElement(new QName(securityQName.getNamespaceURI(), securityQName.getLocalPart(), "wsse"));
+ soapHeader.addChildElement(securityHeader);
+ return securityHeader;
+ }
+
+ private SOAPElement addAssertionElement(final STSSecurityHandler handler, final SOAPHeaderElement securityHeader) throws SOAPException
+ {
+ final QName tokenElementQName = handler.getTokenElementQName();
+ final SOAPElement tokenElement = securityHeader.addChildElement(new QName(tokenElementQName.getNamespaceURI(), tokenElementQName.getLocalPart(), "saml"));
+ return securityHeader.addChildElement(tokenElement);
+ }
+
+ private void setMessageOnContext(final SOAPMessageContext messageContext, final SOAPMessage soapMessage)
+ {
+ when(messageContext.getMessage()).thenReturn(soapMessage);
+ }
+
+ private void setOutbound(MessageContext messageContext, boolean outbound)
+ {
+ when(messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).thenReturn(outbound);
+ }
+
+}
+
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxrpc.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxrpc.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxws-ext.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxws-ext.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxws.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-jaxws.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-saaj.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/jbossws-native-saaj.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/resolver.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/resolver.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xercesImpl.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xercesImpl.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xml-apis.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xml-apis.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/wstrust/sts-client.properties
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/resources/wstrust/sts-client.properties (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/resources/wstrust/sts-client.properties 2009-09-25 08:00:27 UTC (rev 809)
@@ -0,0 +1,5 @@
+serviceName=JBossSTS
+portName=JBossSTSPort
+endpointAddress=http://localhost:8080/jboss-sts/JBossSTS
+username=admin
+password=admin
14 years, 7 months
JBoss Identity SVN: r808 - in identity-federation/trunk: jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/servlets and 25 other directories.
by jboss-identity-commits@lists.jboss.org
Author: sguilhen(a)redhat.com
Date: 2009-09-23 21:24:30 -0400 (Wed, 23 Sep 2009)
New Revision: 808
Added:
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/impl/KeyStoreKeyManager.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/impl/SecurityActions.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyConfigurationException.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyManager.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyProcessingException.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/util/EncryptionKeyUtil.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/util/KeyStoreUtil.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/JBossSTS.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/JBossSTSConfiguration.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/util/KeystoreUtilUnitTestCase.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/JBossSTSUnitTestCase.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/TestPrincipal.java
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/jboss-sts.xml
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/keystore/jbid_test_keystore.jks
Removed:
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/jboss/wstrust/
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/KeyStoreKeyManager.java
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/cert/
identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/KeystoreUtilUnitTestCase.java
identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/wstrust/
identity-federation/trunk/jboss-identity-bindings/src/test/resources/jboss-sts.xml
identity-federation/trunk/jboss-identity-bindings/src/test/resources/keystore/sts_keystore.jks
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/util/KeyStoreUtil.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/MockSTSConfiguration.java
identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyConfigurationException.java
identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyManager.java
identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyProcessingException.java
Modified:
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/servlets/MetadataServlet.java
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectWithSignatureValve.java
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPWebBrowserSSOValve.java
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPPostSignatureFormAuthenticator.java
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectSignatureFormAuthenticator.java
identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/ValveUtil.java
identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/RedirectBindingSignatureUtilTestCase.java
identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/WSTrustClientUnitTestCase.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/StandardRequestHandler.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAMLUtil.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SAML20TokenProviderUnitTestCase.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SpecialTokenProvider.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/WSTrustServiceFactoryUnitTestCase.java
identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/filters/SPFilter.java
identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/servlets/IDPServlet.java
identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/util/IDPWebRequestUtil.java
identity-federation/trunk/jboss-identity-webapps/jboss-sts/src/main/resources/jboss-sts.xml
identity-federation/trunk/jboss-identity-webapps/jboss-sts/src/main/webapp/WEB-INF/web.xml
Log:
JBID-193: moved JBossSTS, JBossSTSConfiguration and all relevant classes to the core module. Tests and referencing files have been updated accordingly.
Modified: identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/servlets/MetadataServlet.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/servlets/MetadataServlet.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/servlets/MetadataServlet.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -46,12 +46,12 @@
import org.jboss.identity.federation.core.config.KeyValueType;
import org.jboss.identity.federation.core.config.MetadataProviderType;
import org.jboss.identity.federation.core.config.ProviderType;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
import org.jboss.identity.federation.core.saml.v2.constants.JBossSAMLConstants;
import org.jboss.identity.federation.core.util.XMLEncryptionUtil;
import org.jboss.identity.federation.saml.v2.metadata.EntityDescriptorType;
import org.jboss.identity.federation.saml.v2.metadata.KeyDescriptorType;
import org.jboss.identity.federation.saml.v2.metadata.RoleDescriptorType;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
import org.jboss.identity.federation.web.util.ConfigurationUtil;
import org.jboss.identity.xmlsec.w3.xmldsig.KeyInfoType;
Deleted: identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/KeyStoreKeyManager.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/KeyStoreKeyManager.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/KeyStoreKeyManager.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,345 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.identity.federation.bindings.tomcat;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.GeneralSecurityException;
-import java.security.KeyPair;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.Certificate;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.crypto.SecretKey;
-
-import org.apache.log4j.Logger;
-import org.jboss.identity.federation.core.config.AuthPropertyType;
-import org.jboss.identity.federation.core.config.KeyValueType;
-import org.jboss.identity.federation.web.interfaces.TrustKeyConfigurationException;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
-import org.jboss.identity.federation.web.interfaces.TrustKeyProcessingException;
-import org.jboss.identity.federation.api.util.KeyStoreUtil;
-import org.jboss.identity.federation.bindings.util.ValveUtil;
-import org.jboss.identity.federation.bindings.util.cert.EncryptionKeyUtil;
-
-/**
- * KeyStore based Trust Key Manager
- * @author Anil.Saldhana(a)redhat.com
- * @since Jan 22, 2009
- */
-public class KeyStoreKeyManager implements TrustKeyManager
-{
- /**
- * An map of secret keys alive only for the duration of the program.
- * The keys are generated on the fly. If you need sophisticated key
- * storage, then a custom version of the {@code TrustKeyManager}
- * needs to be written that either uses a secure thumb drive or
- * a TPM module or a HSM module.
- * Also see JBoss XMLKey.
- */
- private final Map<String,SecretKey> keys = new HashMap<String,SecretKey>();
-
- private static Logger log = Logger.getLogger(KeyStoreKeyManager.class);
- private boolean trace = log.isTraceEnabled();
-
- private final HashMap<String,String> domainAliasMap = new HashMap<String,String>();
- private final HashMap<String,String> authPropsMap = new HashMap<String,String>();
-
- private KeyStore ks = null;
-
- private String keyStoreURL;
- private char[] signingKeyPass;
- private String signingAlias;
- private String keyStorePass;
-
- public static final String KEYSTORE_URL = "KeyStoreURL";
- public static final String KEYSTORE_PASS = "KeyStorePass";
- public static final String SIGNING_KEY_PASS = "SigningKeyPass";
- public static final String SIGNING_KEY_ALIAS = "SigningKeyAlias";
-
- /**
- * @see TrustKeyManager#getSigningKey()
- */
- public PrivateKey getSigningKey()
- throws TrustKeyConfigurationException, TrustKeyProcessingException
- {
- try
- {
- if(ks == null)
- this.setUpKeyStore();
-
- if(ks == null)
- throw new IllegalStateException("KeyStore is null");
- return (PrivateKey) ks.getKey(this.signingAlias, this.signingKeyPass);
- }
- catch (KeyStoreException e)
- {
- throw new TrustKeyConfigurationException(e);
- }
- catch (NoSuchAlgorithmException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- catch (UnrecoverableKeyException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- catch (GeneralSecurityException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- catch (IOException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- }
-
- /*
- * (non-Javadoc)
- * @see org.jboss.identity.federation.bindings.interfaces.TrustKeyManager#getSigningKeyPair()
- */
- public KeyPair getSigningKeyPair()
- throws TrustKeyConfigurationException, TrustKeyProcessingException
- {
- try
- {
- if(this.ks == null)
- this.setUpKeyStore();
-
- PrivateKey privateKey = this.getSigningKey();
- PublicKey publicKey = KeyStoreUtil.getPublicKey(this.ks, this.signingAlias, this.signingKeyPass);
- return new KeyPair(publicKey, privateKey);
- }
- catch (KeyStoreException e)
- {
- throw new TrustKeyConfigurationException(e);
- }
- catch (GeneralSecurityException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- catch (IOException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- }
-
- /**
- * @see TrustKeyManager#getCertificate(String)
- */
- public Certificate getCertificate(String alias)
- throws TrustKeyConfigurationException, TrustKeyProcessingException
- {
- try
- {
- if(ks == null)
- this.setUpKeyStore();
-
- if(ks == null)
- throw new IllegalStateException("KeyStore is null");
-
- if(alias == null || alias.length() == 0)
- throw new IllegalArgumentException("Alias is null");
-
- return ks.getCertificate(alias);
- }
- catch (KeyStoreException e)
- {
- throw new TrustKeyConfigurationException(e);
- }
- catch (GeneralSecurityException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- catch (IOException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- }
-
- /**
- * @see TrustKeyManager#getPublicKey(String)
- */
- public PublicKey getPublicKey(String alias)
- throws TrustKeyConfigurationException, TrustKeyProcessingException
- {
- PublicKey publicKey = null;
-
- try
- {
- if(ks == null)
- this.setUpKeyStore();
-
- if(ks == null)
- throw new IllegalStateException("KeyStore is null");
- Certificate cert = ks.getCertificate(alias);
- if(cert != null)
- publicKey = cert.getPublicKey();
- else
- if(trace)
- log.trace("No public key found for alias=" + alias);
-
- return publicKey;
- }
- catch (KeyStoreException e)
- {
- throw new TrustKeyConfigurationException(e);
- }
- catch (GeneralSecurityException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- catch (IOException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- }
-
- /**
- * @throws IOException
- * @see TrustKeyManager#getValidatingKey(String)
- */
- public PublicKey getValidatingKey(String domain)
- throws TrustKeyConfigurationException, TrustKeyProcessingException
- {
- PublicKey publicKey = null;
- try
- {
- if(ks == null)
- this.setUpKeyStore();
-
- if(ks == null)
- throw new IllegalStateException("KeyStore is null");
- String domainAlias = this.domainAliasMap.get(domain);
- if(domainAlias == null)
- throw new IllegalStateException("Domain Alias missing for "+ domain);
- publicKey = null;
- try
- {
- publicKey = KeyStoreUtil.getPublicKey(ks, domainAlias, this.keyStorePass.toCharArray());
- }
- catch(UnrecoverableKeyException urke)
- {
- //Try with the signing key pass
- publicKey = KeyStoreUtil.getPublicKey(ks, domainAlias, this.signingKeyPass);
- }
- }
- catch (KeyStoreException e)
- {
- throw new TrustKeyConfigurationException(e);
- }
- catch (NoSuchAlgorithmException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- catch (GeneralSecurityException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- catch (IOException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- return publicKey;
- }
-
- /**
- * @see TrustKeyManager#setAuthProperties(List)
- */
- public void setAuthProperties(List<AuthPropertyType> authList)
- throws TrustKeyConfigurationException, TrustKeyProcessingException
- {
- for(AuthPropertyType auth: authList)
- {
- this.authPropsMap.put(auth.getKey(), auth.getValue());
- }
-
- this.keyStoreURL = this.authPropsMap.get(KEYSTORE_URL);
- this.keyStorePass = this.authPropsMap.get(KEYSTORE_PASS);
-
-
- this.signingAlias = this.authPropsMap.get(SIGNING_KEY_ALIAS);
-
- String keypass = this.authPropsMap.get(SIGNING_KEY_PASS);
- if(keypass == null || keypass.length() == 0)
- throw new RuntimeException("Signing Key Pass is null");
- this.signingKeyPass = keypass.toCharArray();
- }
-
- /**
- * @see TrustKeyManager#setValidatingAlias(List)
- */
- public void setValidatingAlias(List<KeyValueType> aliases)
- throws TrustKeyConfigurationException, TrustKeyProcessingException
- {
- for(KeyValueType alias: aliases)
- {
- domainAliasMap.put(alias.getKey(), alias.getValue());
- }
- }
-
- /**
- * @throws GeneralSecurityException
- * @see TrustKeyManager#getEncryptionKey(String)
- */
- public SecretKey getEncryptionKey(String domain,String encryptionAlgorithm, int keyLength)
- throws TrustKeyConfigurationException, TrustKeyProcessingException
- {
- SecretKey key = keys.get(domain);
- if(key == null)
- {
- try
- {
- key = EncryptionKeyUtil.getSecretKey(encryptionAlgorithm, keyLength);
- }
- catch (GeneralSecurityException e)
- {
- throw new TrustKeyProcessingException(e);
- }
- keys.put(domain, key);
- }
- return key;
- }
-
- private void setUpKeyStore() throws GeneralSecurityException, IOException
- {
- //Keystore URL/Pass can be either by configuration or on the HTTPS connector
- if(this.keyStoreURL == null)
- {
- this.keyStoreURL = SecurityActions.getProperty("javax.net.ssl.keyStore", null);
- }
- if(this.keyStorePass == null)
- {
- this.keyStorePass = SecurityActions.getProperty("javax.net.ssl.keyStorePassword", null);
- }
-
- InputStream is = ValveUtil.getKeyStoreInputStream(this.keyStoreURL);
- ks = KeyStoreUtil.getKeyStore(is, keyStorePass.toCharArray());
- }
-}
\ No newline at end of file
Modified: identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectWithSignatureValve.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectWithSignatureValve.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPRedirectWithSignatureValve.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -44,18 +44,18 @@
import org.jboss.identity.federation.api.saml.v2.response.SAML2Response;
import org.jboss.identity.federation.core.config.EncryptionType;
import org.jboss.identity.federation.core.config.KeyProviderType;
-import org.jboss.identity.federation.web.interfaces.TrustKeyConfigurationException;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
-import org.jboss.identity.federation.web.interfaces.TrustKeyProcessingException;
-import org.jboss.identity.federation.web.util.RedirectBindingSignatureUtil;
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.exceptions.ParsingException;
import org.jboss.identity.federation.core.exceptions.ProcessingException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyConfigurationException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
import org.jboss.identity.federation.core.util.XMLEncryptionUtil;
import org.jboss.identity.federation.saml.v2.assertion.EncryptedElementType;
import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
+import org.jboss.identity.federation.web.util.RedirectBindingSignatureUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
Modified: identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPWebBrowserSSOValve.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPWebBrowserSSOValve.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/idp/IDPWebBrowserSSOValve.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -45,21 +45,21 @@
import org.apache.catalina.valves.ValveBase;
import org.apache.log4j.Logger;
import org.jboss.identity.federation.bindings.tomcat.TomcatRoleGenerator;
+import org.jboss.identity.federation.core.config.IDPType;
+import org.jboss.identity.federation.core.config.KeyProviderType;
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.exceptions.ParsingException;
import org.jboss.identity.federation.core.impl.DelegatedAttributeManager;
import org.jboss.identity.federation.core.interfaces.AttributeManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyConfigurationException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssueInstantMissingException;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
import org.jboss.identity.federation.saml.v2.protocol.RequestAbstractType;
-import org.jboss.identity.federation.core.config.IDPType;
-import org.jboss.identity.federation.core.config.KeyProviderType;
import org.jboss.identity.federation.web.interfaces.RoleGenerator;
-import org.jboss.identity.federation.web.interfaces.TrustKeyConfigurationException;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
-import org.jboss.identity.federation.web.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.web.util.ConfigurationUtil;
import org.jboss.identity.federation.web.util.IDPWebRequestUtil;
import org.jboss.identity.federation.web.util.RedirectBindingSignatureUtil;
Modified: identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPPostSignatureFormAuthenticator.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPPostSignatureFormAuthenticator.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPPostSignatureFormAuthenticator.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -37,15 +37,15 @@
import org.apache.log4j.Logger;
import org.jboss.identity.federation.api.saml.v2.request.SAML2Request;
import org.jboss.identity.federation.core.config.KeyProviderType;
+import org.jboss.identity.federation.core.interfaces.TrustKeyConfigurationException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.core.saml.v2.common.SAMLDocumentHolder;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
import org.jboss.identity.federation.core.saml.v2.holders.DestinationInfoHolder;
import org.jboss.identity.federation.core.util.XMLSignatureUtil;
import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
-import org.jboss.identity.federation.web.interfaces.TrustKeyConfigurationException;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
-import org.jboss.identity.federation.web.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.web.util.PostBindingUtil;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
Modified: identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectSignatureFormAuthenticator.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectSignatureFormAuthenticator.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/tomcat/sp/SPRedirectSignatureFormAuthenticator.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -36,17 +36,17 @@
import org.apache.log4j.Logger;
import org.jboss.identity.federation.api.saml.v2.response.SAML2Response;
import org.jboss.identity.federation.core.config.KeyProviderType;
-import org.jboss.identity.federation.web.interfaces.TrustKeyConfigurationException;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
-import org.jboss.identity.federation.web.interfaces.TrustKeyProcessingException;
-import org.jboss.identity.federation.web.util.RedirectBindingSignatureUtil;
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.exceptions.ParsingException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyConfigurationException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
import org.jboss.identity.federation.core.saml.v2.util.SignatureUtil;
import org.jboss.identity.federation.core.util.XMLEncryptionUtil;
import org.jboss.identity.federation.saml.v2.assertion.EncryptedElementType;
import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
+import org.jboss.identity.federation.web.util.RedirectBindingSignatureUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
Modified: identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/ValveUtil.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/ValveUtil.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/main/java/org/jboss/identity/federation/bindings/util/ValveUtil.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -21,11 +21,7 @@
*/
package org.jboss.identity.federation.bindings.util;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
import java.io.IOException;
-import java.io.InputStream;
import java.net.URL;
/**
@@ -35,58 +31,7 @@
*/
public class ValveUtil
{
- /**
- * Seek the input stream to the KeyStore
- * @param keyStore
- * @return
- */
- public static InputStream getKeyStoreInputStream(String keyStore)
- {
- InputStream is = null;
-
- try
- {
- //Try the file method
- File file = new File(keyStore);
- is = new FileInputStream(file);
- }
- catch(Exception e)
- {
- try
- {
- URL url = new URL(keyStore);
- is = url.openStream();
- }
- catch(Exception ex)
- {
- is = SecurityActions.getContextClassLoader().getResourceAsStream(keyStore);
- }
- }
-
- if(is == null)
- {
- //Try the user.home dir
- String userHome = SecurityActions.getSystemProperty("user.home", "") + "/jbid-keystore";
- File ksDir = new File(userHome);
- if(ksDir.exists())
- {
- try
- {
- is = new FileInputStream(new File(userHome + "/" + keyStore));
- }
- catch (FileNotFoundException e)
- {
- is = null;
- }
- }
- }
- if(is == null)
- throw new RuntimeException("Keystore not located:" + keyStore);
- return is;
- }
-
-
/**
* Given a SP or IDP issuer from the assertion, return the host
* @param domainURL
Deleted: identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/KeystoreUtilUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/KeystoreUtilUnitTestCase.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/KeystoreUtilUnitTestCase.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,93 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.test.identity.federation.bindings.util;
-
-import java.io.InputStream;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.util.Enumeration;
-
-import junit.framework.TestCase;
-
-import org.jboss.identity.federation.api.util.KeyStoreUtil;
-import org.jboss.identity.federation.core.saml.v2.util.SignatureUtil;
-
-/**
- * Test the KeyStore Util
- * @author Anil.Saldhana(a)redhat.com
- * @since Jan 15, 2009
- */
-public class KeystoreUtilUnitTestCase extends TestCase
-{
-
- /**
- * Keystore (created 15Jan2009 and valid for 200K days)
- * The Keystore has been created with the command (all in one line)
-keytool -genkey -alias servercert
- -keyalg RSA
- -keysize 1024
- -dname "CN=jbossidentity.jboss.org,OU=RD,O=JBOSS,L=Chicago,S=Illinois,C=US"
- -keypass test123
- -keystore jbid_test_keystore.jks
- -storepass store123
- -validity 200000
- */
- private String keystoreLocation = "keystore/jbid_test_keystore.jks";
- private String keystorePass = "store123";
- private String alias = "servercert";
- private String keyPass = "test123";
-
-
- /**
- Generated a selfsigned cert
- keytool -selfcert
- -alias servercert
- -keypass test123
- -keystore jbid_test_keystore.jks
- -dname "cn=jbid test, ou=JBoss, o=JBoss, c=US"
- -storepass store123
- */
- public void testSignatureValidationInvalidation() throws Exception
- {
- ClassLoader tcl = Thread.currentThread().getContextClassLoader();
- InputStream ksStream = tcl.getResourceAsStream(keystoreLocation);
- assertNotNull("Input keystore stream is not null", ksStream);
-
- KeyStore ks = KeyStoreUtil.getKeyStore(ksStream, keystorePass.toCharArray());
- assertNotNull("KeyStore is not null",ks);
-
- //Check that there are aliases in the keystore
- Enumeration<String> aliases = ks.aliases();
- assertTrue("Aliases are not empty", aliases.hasMoreElements());
-
- PublicKey publicKey = KeyStoreUtil.getPublicKey(ks, alias, keyPass.toCharArray());
- assertNotNull("Public Key is not null", publicKey);
-
- PrivateKey privateKey = (PrivateKey) ks.getKey(alias, keyPass.toCharArray());
-
- String content = "Hello";
- byte[] sigValue = SignatureUtil.sign(content, privateKey);
- boolean isValid = SignatureUtil.validate(content.getBytes("UTF-8"), sigValue, publicKey);
- assertTrue("Valid sig?", isValid);
- }
-}
\ No newline at end of file
Modified: identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/RedirectBindingSignatureUtilTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/RedirectBindingSignatureUtilTestCase.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/util/RedirectBindingSignatureUtilTestCase.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -27,10 +27,10 @@
import junit.framework.TestCase;
-import org.jboss.identity.federation.api.util.KeyStoreUtil;
import org.jboss.identity.federation.core.saml.v2.common.IDGenerator;
import org.jboss.identity.federation.core.saml.v2.factories.JBossSAMLAuthnRequestFactory;
import org.jboss.identity.federation.core.saml.v2.util.SignatureUtil;
+import org.jboss.identity.federation.core.util.KeyStoreUtil;
import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
import org.jboss.identity.federation.web.util.RedirectBindingSignatureUtil;
Deleted: identity-federation/trunk/jboss-identity-bindings/src/test/resources/jboss-sts.xml
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/test/resources/jboss-sts.xml 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-bindings/src/test/resources/jboss-sts.xml 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,31 +0,0 @@
-<JBossSTS xmlns="urn:jboss:identity-federation:config:1.0"
- STSName="Test STS" TokenTimeout="7200" EncryptToken="true">
- <KeyProvider ClassName="org.jboss.identity.federation.bindings.tomcat.KeyStoreKeyManager">
- <Auth Key="KeyStoreURL" Value="keystore/sts_keystore.jks"/>
- <Auth Key="KeyStorePass" Value="testpass"/>
- <Auth Key="SigningKeyAlias" Value="sts"/>
- <Auth Key="SigningKeyPass" Value="keypass"/>
- <ValidatingAlias Key="http://services.testcorp.org/provider1" Value="service1"/>
- <ValidatingAlias Key="http://services.testcorp.org/provider2" Value="service2"/>
- </KeyProvider>
- <RequestHandler>org.jboss.identity.federation.core.wstrust.StandardRequestHandler</RequestHandler>
- <TokenProviders>
- <TokenProvider ProviderClass="org.jboss.test.identity.federation.bindings.wstrust.SpecialTokenProvider"
- TokenType="http://www.tokens.org/SpecialToken"
- TokenElement="SpecialToken"
- TokenElementNS="http://www.tokens.org">
- <Property Name="Property1" Value="Value1"/>
- <Property Name="Property2" Value="Value2"/>
- </TokenProvider>
- <TokenProvider ProviderClass="org.jboss.identity.federation.core.wstrust.plugins.saml.SAML20TokenProvider"
- TokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
- TokenElement="Assertion"
- TokenElementNS="urn:oasis:names:tc:SAML:2.0:assertion"/>
- </TokenProviders>
- <ServiceProviders>
- <ServiceProvider Endpoint="http://services.testcorp.org/provider1" TokenType="http://www.tokens.org/SpecialToken"
- TruststoreAlias="service1"/>
- <ServiceProvider Endpoint="http://services.testcorp.org/provider2" TokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
- TruststoreAlias="service2"/>
- </ServiceProviders>
-</JBossSTS>
\ No newline at end of file
Deleted: identity-federation/trunk/jboss-identity-bindings/src/test/resources/keystore/sts_keystore.jks
===================================================================
(Binary files differ)
Deleted: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/util/KeyStoreUtil.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/util/KeyStoreUtil.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/util/KeyStoreUtil.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,181 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.identity.federation.api.util;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.security.GeneralSecurityException;
-import java.security.Key;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.cert.Certificate;
-
-/**
- * Utility to handle Java Keystore
- * @author Anil.Saldhana(a)redhat.com
- * @since Jan 12, 2009
- */
-public class KeyStoreUtil
-{
- /**
- * Get the KeyStore
- * @param keyStoreFile
- * @param storePass
- * @return
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public static KeyStore getKeyStore(File keyStoreFile, char[] storePass) throws GeneralSecurityException, IOException
- {
- FileInputStream fis = new FileInputStream(keyStoreFile);
- return getKeyStore(fis,storePass);
- }
-
- /**
- * Get the Keystore given the url to the keystore file as a string
- * @param fileURL
- * @param storePass
- * @return
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public static KeyStore getKeyStore(String fileURL, char[] storePass) throws GeneralSecurityException, IOException
- {
- if(fileURL == null)
- throw new IllegalArgumentException("fileURL is null");
-
- File file = new File(fileURL);
- FileInputStream fis = new FileInputStream(file);
- return getKeyStore(fis,storePass);
- }
-
- /**
- * Get the Keystore given the URL to the keystore
- * @param url
- * @param storePass
- * @return
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public static KeyStore getKeyStore(URL url, char[] storePass) throws GeneralSecurityException, IOException
- {
- if(url == null)
- throw new IllegalArgumentException("url is null");
-
- return getKeyStore(url.openStream(), storePass);
- }
-
- /**
- * Get the Key Store
- * <b>Note:</b> This method wants the InputStream to be not null.
- * @param ksStream
- * @param storePass
- * @return
- * @throws GeneralSecurityException
- * @throws IOException
- * @throws IllegalArgumentException if ksStream is null
- */
- public static KeyStore getKeyStore(InputStream ksStream, char[] storePass) throws GeneralSecurityException, IOException
- {
- if(ksStream == null)
- throw new IllegalArgumentException("InputStream for the KeyStore is null");
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- ks.load(ksStream, storePass);
- return ks;
- }
-
- /**
- * Generate a Key Pair
- * @param algo (RSA, DSA etc)
- * @return
- * @throws GeneralSecurityException
- */
- public static KeyPair generateKeyPair(String algo) throws GeneralSecurityException
- {
- KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
- return kpg.genKeyPair();
- }
-
- /**
- * Get the Public Key from the keystore
- * @param ks
- * @param alias
- * @param password
- * @return
- * @throws GeneralSecurityException
- */
- public static PublicKey getPublicKey(KeyStore ks, String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, GeneralSecurityException
- {
- PublicKey publicKey = null;
-
- // Get private key
- Key key = ks.getKey(alias, password);
- if (key instanceof PrivateKey)
- {
- // Get certificate of public key
- Certificate cert = ks.getCertificate(alias);
-
- // Get public key
- publicKey = cert.getPublicKey();
- }
- // if alias is a certificate alias, get the public key from the certificate.
- if(publicKey == null)
- {
- Certificate cert = ks.getCertificate(alias);
- if(cert != null)
- publicKey = cert.getPublicKey();
- }
- return publicKey;
- }
-
- /**
- * Add a certificate to the KeyStore
- * @param keystoreFile
- * @param storePass
- * @param alias
- * @param cert
- * @throws GeneralSecurityException
- * @throws IOException
- */
- public static void addCertificate(File keystoreFile, char[] storePass, String alias, Certificate cert)
- throws GeneralSecurityException, IOException
- {
- KeyStore keystore = getKeyStore(keystoreFile, storePass);
-
- // Add the certificate
- keystore.setCertificateEntry(alias, cert);
-
- // Save the new keystore contents
- FileOutputStream out = new FileOutputStream(keystoreFile);
- keystore.store(out, storePass);
- out.close();
- }
-}
\ No newline at end of file
Modified: identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/WSTrustClientUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/WSTrustClientUnitTestCase.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/WSTrustClientUnitTestCase.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -47,10 +47,10 @@
import junit.framework.TestCase;
-import org.jboss.identity.federation.api.util.KeyStoreUtil;
import org.jboss.identity.federation.api.wstrust.WSTrustClient;
import org.jboss.identity.federation.api.wstrust.WSTrustClient.SecurityInfo;
import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
+import org.jboss.identity.federation.core.util.KeyStoreUtil;
import org.jboss.identity.federation.core.util.XMLSignatureUtil;
import org.jboss.identity.federation.core.wstrust.WSTrustConstants;
import org.jboss.identity.federation.core.wstrust.WSTrustJAXBFactory;
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/impl/KeyStoreKeyManager.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/impl/KeyStoreKeyManager.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/impl/KeyStoreKeyManager.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,399 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.impl;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.security.KeyPair;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.Certificate;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.crypto.SecretKey;
+
+import org.apache.log4j.Logger;
+import org.jboss.identity.federation.core.config.AuthPropertyType;
+import org.jboss.identity.federation.core.config.KeyValueType;
+import org.jboss.identity.federation.core.interfaces.TrustKeyConfigurationException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyProcessingException;
+import org.jboss.identity.federation.core.util.EncryptionKeyUtil;
+import org.jboss.identity.federation.core.util.KeyStoreUtil;
+
+/**
+ * KeyStore based Trust Key Manager
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Jan 22, 2009
+ */
+public class KeyStoreKeyManager implements TrustKeyManager
+{
+ /**
+ * An map of secret keys alive only for the duration of the program.
+ * The keys are generated on the fly. If you need sophisticated key
+ * storage, then a custom version of the {@code TrustKeyManager}
+ * needs to be written that either uses a secure thumb drive or
+ * a TPM module or a HSM module.
+ * Also see JBoss XMLKey.
+ */
+ private final Map<String,SecretKey> keys = new HashMap<String,SecretKey>();
+
+ private static Logger log = Logger.getLogger(KeyStoreKeyManager.class);
+ private boolean trace = log.isTraceEnabled();
+
+ private final HashMap<String,String> domainAliasMap = new HashMap<String,String>();
+ private final HashMap<String,String> authPropsMap = new HashMap<String,String>();
+
+ private KeyStore ks = null;
+
+ private String keyStoreURL;
+ private char[] signingKeyPass;
+ private String signingAlias;
+ private String keyStorePass;
+
+ public static final String KEYSTORE_URL = "KeyStoreURL";
+ public static final String KEYSTORE_PASS = "KeyStorePass";
+ public static final String SIGNING_KEY_PASS = "SigningKeyPass";
+ public static final String SIGNING_KEY_ALIAS = "SigningKeyAlias";
+
+ /**
+ * @see TrustKeyManager#getSigningKey()
+ */
+ public PrivateKey getSigningKey()
+ throws TrustKeyConfigurationException, TrustKeyProcessingException
+ {
+ try
+ {
+ if(ks == null)
+ this.setUpKeyStore();
+
+ if(ks == null)
+ throw new IllegalStateException("KeyStore is null");
+ return (PrivateKey) ks.getKey(this.signingAlias, this.signingKeyPass);
+ }
+ catch (KeyStoreException e)
+ {
+ throw new TrustKeyConfigurationException(e);
+ }
+ catch (NoSuchAlgorithmException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ catch (UnrecoverableKeyException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ catch (IOException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.jboss.identity.federation.bindings.interfaces.TrustKeyManager#getSigningKeyPair()
+ */
+ public KeyPair getSigningKeyPair()
+ throws TrustKeyConfigurationException, TrustKeyProcessingException
+ {
+ try
+ {
+ if(this.ks == null)
+ this.setUpKeyStore();
+
+ PrivateKey privateKey = this.getSigningKey();
+ PublicKey publicKey = KeyStoreUtil.getPublicKey(this.ks, this.signingAlias, this.signingKeyPass);
+ return new KeyPair(publicKey, privateKey);
+ }
+ catch (KeyStoreException e)
+ {
+ throw new TrustKeyConfigurationException(e);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ catch (IOException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ }
+
+ /**
+ * @see TrustKeyManager#getCertificate(String)
+ */
+ public Certificate getCertificate(String alias)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException
+ {
+ try
+ {
+ if(ks == null)
+ this.setUpKeyStore();
+
+ if(ks == null)
+ throw new IllegalStateException("KeyStore is null");
+
+ if(alias == null || alias.length() == 0)
+ throw new IllegalArgumentException("Alias is null");
+
+ return ks.getCertificate(alias);
+ }
+ catch (KeyStoreException e)
+ {
+ throw new TrustKeyConfigurationException(e);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ catch (IOException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ }
+
+ /**
+ * @see TrustKeyManager#getPublicKey(String)
+ */
+ public PublicKey getPublicKey(String alias)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException
+ {
+ PublicKey publicKey = null;
+
+ try
+ {
+ if(ks == null)
+ this.setUpKeyStore();
+
+ if(ks == null)
+ throw new IllegalStateException("KeyStore is null");
+ Certificate cert = ks.getCertificate(alias);
+ if(cert != null)
+ publicKey = cert.getPublicKey();
+ else
+ if(trace)
+ log.trace("No public key found for alias=" + alias);
+
+ return publicKey;
+ }
+ catch (KeyStoreException e)
+ {
+ throw new TrustKeyConfigurationException(e);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ catch (IOException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ }
+
+ /**
+ * @throws IOException
+ * @see TrustKeyManager#getValidatingKey(String)
+ */
+ public PublicKey getValidatingKey(String domain)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException
+ {
+ PublicKey publicKey = null;
+ try
+ {
+ if(ks == null)
+ this.setUpKeyStore();
+
+ if(ks == null)
+ throw new IllegalStateException("KeyStore is null");
+ String domainAlias = this.domainAliasMap.get(domain);
+ if(domainAlias == null)
+ throw new IllegalStateException("Domain Alias missing for "+ domain);
+ publicKey = null;
+ try
+ {
+ publicKey = KeyStoreUtil.getPublicKey(ks, domainAlias, this.keyStorePass.toCharArray());
+ }
+ catch(UnrecoverableKeyException urke)
+ {
+ //Try with the signing key pass
+ publicKey = KeyStoreUtil.getPublicKey(ks, domainAlias, this.signingKeyPass);
+ }
+ }
+ catch (KeyStoreException e)
+ {
+ throw new TrustKeyConfigurationException(e);
+ }
+ catch (NoSuchAlgorithmException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ catch (IOException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ return publicKey;
+ }
+
+ /**
+ * @see TrustKeyManager#setAuthProperties(List)
+ */
+ public void setAuthProperties(List<AuthPropertyType> authList)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException
+ {
+ for(AuthPropertyType auth: authList)
+ {
+ this.authPropsMap.put(auth.getKey(), auth.getValue());
+ }
+
+ this.keyStoreURL = this.authPropsMap.get(KEYSTORE_URL);
+ this.keyStorePass = this.authPropsMap.get(KEYSTORE_PASS);
+
+
+ this.signingAlias = this.authPropsMap.get(SIGNING_KEY_ALIAS);
+
+ String keypass = this.authPropsMap.get(SIGNING_KEY_PASS);
+ if(keypass == null || keypass.length() == 0)
+ throw new RuntimeException("Signing Key Pass is null");
+ this.signingKeyPass = keypass.toCharArray();
+ }
+
+ /**
+ * @see TrustKeyManager#setValidatingAlias(List)
+ */
+ public void setValidatingAlias(List<KeyValueType> aliases)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException
+ {
+ for(KeyValueType alias: aliases)
+ {
+ domainAliasMap.put(alias.getKey(), alias.getValue());
+ }
+ }
+
+ /**
+ * @throws GeneralSecurityException
+ * @see TrustKeyManager#getEncryptionKey(String)
+ */
+ public SecretKey getEncryptionKey(String domain,String encryptionAlgorithm, int keyLength)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException
+ {
+ SecretKey key = keys.get(domain);
+ if(key == null)
+ {
+ try
+ {
+ key = EncryptionKeyUtil.getSecretKey(encryptionAlgorithm, keyLength);
+ }
+ catch (GeneralSecurityException e)
+ {
+ throw new TrustKeyProcessingException(e);
+ }
+ keys.put(domain, key);
+ }
+ return key;
+ }
+
+ private void setUpKeyStore() throws GeneralSecurityException, IOException
+ {
+ //Keystore URL/Pass can be either by configuration or on the HTTPS connector
+ if(this.keyStoreURL == null)
+ {
+ this.keyStoreURL = SecurityActions.getProperty("javax.net.ssl.keyStore", null);
+ }
+ if(this.keyStorePass == null)
+ {
+ this.keyStorePass = SecurityActions.getProperty("javax.net.ssl.keyStorePassword", null);
+ }
+
+ InputStream is = this.getKeyStoreInputStream(this.keyStoreURL);
+ ks = KeyStoreUtil.getKeyStore(is, keyStorePass.toCharArray());
+ }
+
+ /**
+ * Seek the input stream to the KeyStore
+ * @param keyStore
+ * @return
+ */
+ private InputStream getKeyStoreInputStream(String keyStore)
+ {
+ InputStream is = null;
+
+ try
+ {
+ //Try the file method
+ File file = new File(keyStore);
+ is = new FileInputStream(file);
+ }
+ catch(Exception e)
+ {
+ try
+ {
+ URL url = new URL(keyStore);
+ is = url.openStream();
+ }
+ catch(Exception ex)
+ {
+ is = SecurityActions.getContextClassLoader().getResourceAsStream(keyStore);
+ }
+ }
+
+ if(is == null)
+ {
+ //Try the user.home dir
+ String userHome = SecurityActions.getSystemProperty("user.home", "") + "/jbid-keystore";
+ File ksDir = new File(userHome);
+ if(ksDir.exists())
+ {
+ try
+ {
+ is = new FileInputStream(new File(userHome + "/" + keyStore));
+ }
+ catch (FileNotFoundException e)
+ {
+ is = null;
+ }
+ }
+ }
+ if(is == null)
+ throw new RuntimeException("Keystore not located:" + keyStore);
+ return is;
+ }
+
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/impl/SecurityActions.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/impl/SecurityActions.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/impl/SecurityActions.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,82 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.impl;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+
+/**
+ * Privileged Blocks
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Dec 9, 2008
+ */
+class SecurityActions
+{
+ /**
+ * Get the Thread Context ClassLoader
+ * @return
+ */
+ static ClassLoader getContextClassLoader()
+ {
+ return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>()
+ {
+ public ClassLoader run()
+ {
+ return Thread.currentThread().getContextClassLoader();
+ }
+ });
+ }
+
+ /**
+ * Get a system property
+ * @param key the key for the property
+ * @param defaultValue A default value to return if the property is not set (Can be null)
+ * @return
+ */
+ static String getProperty(final String key, final String defaultValue)
+ {
+ return AccessController.doPrivileged(new PrivilegedAction<String>()
+ {
+ public String run()
+ {
+ return System.getProperty(key,defaultValue);
+ }
+ });
+ }
+
+ /**
+ * Get the system property
+ * @param key
+ * @param defaultValue
+ * @return
+ */
+ static String getSystemProperty(final String key, final String defaultValue)
+ {
+ return AccessController.doPrivileged(new PrivilegedAction<String>()
+ {
+ public String run()
+ {
+ return System.getProperty(key, defaultValue);
+ }
+ });
+ }
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyConfigurationException.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyConfigurationException.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyConfigurationException.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,54 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.interfaces;
+
+import org.jboss.identity.federation.core.exceptions.ConfigurationException;
+
+/**
+ * ConfigurationException in the TrustKeyManager
+ * @author Anil.Saldhana(a)redhat.com
+ * @since May 22, 2009
+ */
+public class TrustKeyConfigurationException extends ConfigurationException
+{
+ private static final long serialVersionUID = 1L;
+
+ public TrustKeyConfigurationException()
+ {
+ super();
+ }
+
+ public TrustKeyConfigurationException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+
+ public TrustKeyConfigurationException(String message)
+ {
+ super(message);
+ }
+
+ public TrustKeyConfigurationException(Throwable cause)
+ {
+ super(cause);
+ }
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyManager.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyManager.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyManager.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,117 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.interfaces;
+
+import java.security.KeyPair;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.Certificate;
+import java.util.List;
+
+import javax.crypto.SecretKey;
+
+import org.jboss.identity.federation.core.config.AuthPropertyType;
+import org.jboss.identity.federation.core.config.KeyValueType;
+
+
+/**
+ * Key Manager interface used in trust decisions
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Jan 22, 2009
+ */
+public interface TrustKeyManager
+{
+ /**
+ * Provide a set of properties used for authentication
+ * into the storage of keys - keystore, ldap, db, HSM etc
+ * @param authList
+ * @throws {@link IOException}
+ */
+ void setAuthProperties(List<AuthPropertyType> authList)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException;
+
+ /**
+ * Set a list of (domain,alias) tuple to trust domains
+ * The alias is a string that represents the validating key stored
+ * for a domain
+ * @param aliases
+ * @throws {@link IOException}
+ */
+ void setValidatingAlias(List<KeyValueType> aliases)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException;
+
+ /**
+ * Get the Signing Key
+ * @return
+ * @throws {@link CertificateException}
+ */
+ PrivateKey getSigningKey()
+ throws TrustKeyConfigurationException, TrustKeyProcessingException;
+
+ /**
+ * <p>
+ * Constructs a {@code KeyPair} instance containing the signing key ({@code PrivateKey}) and associated
+ * {@code PublicKey}.
+ * </p>
+ *
+ * @return the constructed {@code KeyPair} object.
+ */
+ KeyPair getSigningKeyPair()
+ throws TrustKeyConfigurationException, TrustKeyProcessingException;
+
+ /**
+ * Get the certificate given an alias
+ * @param alias
+ * @return
+ * @throws {@link CertificateException}
+ */
+ Certificate getCertificate(String alias)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException;
+
+ /**
+ * Get a Public Key given an alias
+ * @param alias
+ * @return
+ * @throws {@link CertificateException}
+ */
+ PublicKey getPublicKey(String alias)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException;
+
+ /**
+ * Given a domain, obtain a secret key
+ * @see {@code EncryptionKeyUtil}
+ * @param domain
+ * @param encryptionAlgorithm Encryption Algorithm
+ * @param keyLength length of keys
+ * @return
+ */
+ SecretKey getEncryptionKey(String domain, String encryptionAlgorithm, int keyLength)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException;
+
+ /**
+ * Get the Validating Public Key of the domain
+ * @param domain
+ * @return
+ */
+ PublicKey getValidatingKey(String domain)
+ throws TrustKeyConfigurationException, TrustKeyProcessingException;
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyProcessingException.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyProcessingException.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/interfaces/TrustKeyProcessingException.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,54 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.interfaces;
+
+import org.jboss.identity.federation.core.exceptions.ProcessingException;
+
+/**
+ * Processing Exception in the trust key manager
+ * @author Anil.Saldhana(a)redhat.com
+ * @since May 22, 2009
+ */
+public class TrustKeyProcessingException extends ProcessingException
+{
+ private static final long serialVersionUID = 1L;
+
+ public TrustKeyProcessingException()
+ {
+ super();
+ }
+
+ public TrustKeyProcessingException(String message, Throwable cause)
+ {
+ super(message, cause);
+ }
+
+ public TrustKeyProcessingException(String message)
+ {
+ super(message);
+ }
+
+ public TrustKeyProcessingException(Throwable cause)
+ {
+ super(cause);
+ }
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/util/EncryptionKeyUtil.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/util/EncryptionKeyUtil.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/util/EncryptionKeyUtil.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,52 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.util;
+
+import java.security.GeneralSecurityException;
+
+import javax.crypto.KeyGenerator;
+import javax.crypto.SecretKey;
+
+/**
+ * Utility to generate symmetric key
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Feb 4, 2009
+ */
+public class EncryptionKeyUtil
+{
+ /**
+ * Generate a secret key useful for encryption/decryption
+ * @param encAlgo
+ * @param keySize Length of the key (if 0, defaults to 128 bits)
+ * @return
+ * @throws GeneralSecurityException
+ */
+ public static SecretKey getSecretKey(String encAlgo, int keySize) throws GeneralSecurityException
+ {
+ KeyGenerator keyGenerator = KeyGenerator.getInstance(encAlgo);
+ if(keySize == 0)
+ keySize = 128;
+ keyGenerator.init(keySize);
+ return keyGenerator.generateKey();
+ }
+
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/util/KeyStoreUtil.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/util/KeyStoreUtil.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/util/KeyStoreUtil.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,181 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.util;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.Certificate;
+
+/**
+ * Utility to handle Java Keystore
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Jan 12, 2009
+ */
+public class KeyStoreUtil
+{
+ /**
+ * Get the KeyStore
+ * @param keyStoreFile
+ * @param storePass
+ * @return
+ * @throws GeneralSecurityException
+ * @throws IOException
+ */
+ public static KeyStore getKeyStore(File keyStoreFile, char[] storePass) throws GeneralSecurityException, IOException
+ {
+ FileInputStream fis = new FileInputStream(keyStoreFile);
+ return getKeyStore(fis,storePass);
+ }
+
+ /**
+ * Get the Keystore given the url to the keystore file as a string
+ * @param fileURL
+ * @param storePass
+ * @return
+ * @throws GeneralSecurityException
+ * @throws IOException
+ */
+ public static KeyStore getKeyStore(String fileURL, char[] storePass) throws GeneralSecurityException, IOException
+ {
+ if(fileURL == null)
+ throw new IllegalArgumentException("fileURL is null");
+
+ File file = new File(fileURL);
+ FileInputStream fis = new FileInputStream(file);
+ return getKeyStore(fis,storePass);
+ }
+
+ /**
+ * Get the Keystore given the URL to the keystore
+ * @param url
+ * @param storePass
+ * @return
+ * @throws GeneralSecurityException
+ * @throws IOException
+ */
+ public static KeyStore getKeyStore(URL url, char[] storePass) throws GeneralSecurityException, IOException
+ {
+ if(url == null)
+ throw new IllegalArgumentException("url is null");
+
+ return getKeyStore(url.openStream(), storePass);
+ }
+
+ /**
+ * Get the Key Store
+ * <b>Note:</b> This method wants the InputStream to be not null.
+ * @param ksStream
+ * @param storePass
+ * @return
+ * @throws GeneralSecurityException
+ * @throws IOException
+ * @throws IllegalArgumentException if ksStream is null
+ */
+ public static KeyStore getKeyStore(InputStream ksStream, char[] storePass) throws GeneralSecurityException, IOException
+ {
+ if(ksStream == null)
+ throw new IllegalArgumentException("InputStream for the KeyStore is null");
+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
+ ks.load(ksStream, storePass);
+ return ks;
+ }
+
+ /**
+ * Generate a Key Pair
+ * @param algo (RSA, DSA etc)
+ * @return
+ * @throws GeneralSecurityException
+ */
+ public static KeyPair generateKeyPair(String algo) throws GeneralSecurityException
+ {
+ KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
+ return kpg.genKeyPair();
+ }
+
+ /**
+ * Get the Public Key from the keystore
+ * @param ks
+ * @param alias
+ * @param password
+ * @return
+ * @throws GeneralSecurityException
+ */
+ public static PublicKey getPublicKey(KeyStore ks, String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, GeneralSecurityException
+ {
+ PublicKey publicKey = null;
+
+ // Get private key
+ Key key = ks.getKey(alias, password);
+ if (key instanceof PrivateKey)
+ {
+ // Get certificate of public key
+ Certificate cert = ks.getCertificate(alias);
+
+ // Get public key
+ publicKey = cert.getPublicKey();
+ }
+ // if alias is a certificate alias, get the public key from the certificate.
+ if(publicKey == null)
+ {
+ Certificate cert = ks.getCertificate(alias);
+ if(cert != null)
+ publicKey = cert.getPublicKey();
+ }
+ return publicKey;
+ }
+
+ /**
+ * Add a certificate to the KeyStore
+ * @param keystoreFile
+ * @param storePass
+ * @param alias
+ * @param cert
+ * @throws GeneralSecurityException
+ * @throws IOException
+ */
+ public static void addCertificate(File keystoreFile, char[] storePass, String alias, Certificate cert)
+ throws GeneralSecurityException, IOException
+ {
+ KeyStore keystore = getKeyStore(keystoreFile, storePass);
+
+ // Add the certificate
+ keystore.setCertificateEntry(alias, cert);
+
+ // Save the new keystore contents
+ FileOutputStream out = new FileOutputStream(keystoreFile);
+ keystore.store(out, storePass);
+ out.close();
+ }
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/JBossSTS.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/JBossSTS.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/JBossSTS.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,209 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2009, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.wstrust;
+
+import java.io.InputStream;
+import java.net.URL;
+
+import javax.annotation.Resource;
+import javax.xml.bind.JAXBElement;
+import javax.xml.transform.Source;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.ws.Service;
+import javax.xml.ws.ServiceMode;
+import javax.xml.ws.WebServiceContext;
+import javax.xml.ws.WebServiceException;
+import javax.xml.ws.WebServiceProvider;
+
+import org.jboss.identity.federation.core.config.STSType;
+import org.jboss.identity.federation.core.exceptions.ConfigurationException;
+import org.jboss.identity.federation.core.exceptions.ParsingException;
+import org.jboss.identity.federation.core.saml.v2.common.SAMLDocumentHolder;
+import org.jboss.identity.federation.core.util.JAXBUtil;
+import org.jboss.identity.federation.core.wstrust.STSConfiguration;
+import org.jboss.identity.federation.core.wstrust.SecurityTokenService;
+import org.jboss.identity.federation.core.wstrust.WSTrustConstants;
+import org.jboss.identity.federation.core.wstrust.WSTrustException;
+import org.jboss.identity.federation.core.wstrust.WSTrustJAXBFactory;
+import org.jboss.identity.federation.core.wstrust.WSTrustRequestHandler;
+import org.jboss.identity.federation.core.wstrust.wrappers.BaseRequestSecurityToken;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityToken;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenCollection;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponse;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponseCollection;
+import org.w3c.dom.Document;
+
+/**
+ * <p>
+ * Default implementation of the {@code SecurityTokenService} interface.
+ * </p>
+ *
+ * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
+ */
+@WebServiceProvider(serviceName = "JBossSTS", portName = "JBossSTSPort", targetNamespace = "http://org.jboss.identity.trust/sts", wsdlLocation = "WEB-INF/wsdl/JBossSTS.wsdl")
+@ServiceMode(value = Service.Mode.PAYLOAD)
+public class JBossSTS implements SecurityTokenService
+{
+
+ @Resource
+ protected WebServiceContext context;
+
+ protected STSConfiguration config;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.SecurityTokenService#invoke(javax.xml.transform.Source)
+ */
+ public Source invoke(Source request)
+ {
+ BaseRequestSecurityToken baseRequest;
+ try
+ {
+ baseRequest = WSTrustJAXBFactory.getInstance().parseRequestSecurityToken(request);
+ }
+ catch (ParsingException e)
+ {
+ throw new RuntimeException(e);
+ }
+
+ if (baseRequest instanceof RequestSecurityToken)
+ return this.handleTokenRequest((RequestSecurityToken) baseRequest);
+ else if (baseRequest instanceof RequestSecurityTokenCollection)
+ return this.handleTokenRequestCollection((RequestSecurityTokenCollection) baseRequest);
+ else
+ throw new WebServiceException("Invalid security token request");
+ }
+
+ /**
+ * <p>
+ * Process a security token request.
+ * </p>
+ *
+ * @param request a {@code RequestSecurityToken} instance that contains the request information.
+ * @return a {@code Source} instance representing the marshalled response.
+ * @throws WebServiceException Any exception encountered in handling token
+ */
+ protected Source handleTokenRequest(RequestSecurityToken request)
+ {
+ SAMLDocumentHolder holder = WSTrustJAXBFactory.getInstance().getSAMLDocumentHolderOnThread();
+
+ /**
+ * The RST Document is very important for XML Signatures
+ */
+ request.setRSTDocument(holder.getSamlDocument());
+
+ if(this.config == null)
+ try
+ {
+ this.config = this.getConfiguration();
+ }
+ catch (ConfigurationException e)
+ {
+ throw new WebServiceException("Encountered configuration exception:", e);
+ }
+
+ WSTrustRequestHandler handler = this.config.getRequestHandler();
+ String requestType = request.getRequestType().toString();
+
+ try
+ {
+ if (requestType.equals(WSTrustConstants.ISSUE_REQUEST))
+ {
+ Source source = this.marshallResponse(handler.issue(request, this.context.getUserPrincipal()));
+ Document doc = handler.postProcess((Document)((DOMSource)source).getNode(), request);
+ return new DOMSource(doc);
+ }
+
+ else if (requestType.equals(WSTrustConstants.RENEW_REQUEST))
+ return this.marshallResponse(handler.renew(request, this.context.getUserPrincipal()));
+ else if (requestType.equals(WSTrustConstants.CANCEL_REQUEST))
+ return this.marshallResponse(handler.cancel(request, this.context.getUserPrincipal()));
+ else if (requestType.equals(WSTrustConstants.VALIDATE_REQUEST))
+ return this.marshallResponse(handler.validate(request, this.context.getUserPrincipal()));
+ else
+ throw new WSTrustException("Invalid request type: " + requestType);
+ }
+ catch (WSTrustException we)
+ {
+ throw new WebServiceException("Exception in handling token request:", we);
+ }
+ }
+
+ /**
+ * <p>
+ * Process a collection of security token requests.
+ * </p>
+ *
+ * @param requestCollection a {@code RequestSecurityTokenCollection} containing the various requests information.
+ * @return a {@code Source} instance representing the marshalled response.
+ */
+ protected Source handleTokenRequestCollection(RequestSecurityTokenCollection requestCollection)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * <p>
+ * Marshalls the specified {@code RequestSecurityTokenResponse} into a {@code Source} instance.
+ * </p>
+ *
+ * @param response the {@code RequestSecurityTokenResponse} to be marshalled.
+ * @return the resulting {@code Source} instance.
+ */
+ protected Source marshallResponse(RequestSecurityTokenResponse response)
+ {
+ // add the single response to a RequestSecurityTokenResponse collection, as per the specification.
+ RequestSecurityTokenResponseCollection responseCollection = new RequestSecurityTokenResponseCollection();
+ responseCollection.addRequestSecurityTokenResponse(response);
+ return WSTrustJAXBFactory.getInstance().marshallRequestSecurityTokenResponse(responseCollection);
+ }
+
+ /**
+ * <p>
+ * Obtains the STS configuration options.
+ * </p>
+ *
+ * @return an instance of {@code STSConfiguration} containing the STS configuration properties.
+ */
+ @SuppressWarnings("unchecked")
+ protected STSConfiguration getConfiguration() throws ConfigurationException
+ {
+ // get the configuration file and parse it.
+ URL configurationFile = SecurityActions.getContextClassLoader().getResource("jboss-sts.xml");
+ if (configurationFile == null)
+ return new JBossSTSConfiguration();
+
+ try
+ {
+ String pkgName = "org.jboss.identity.federation.core.config";
+ InputStream stream = configurationFile.openStream();
+ JAXBElement<STSType> element = (JAXBElement<STSType>) JAXBUtil.getUnmarshaller(pkgName).unmarshal(stream);
+ STSType stsConfig = element.getValue();
+ return new JBossSTSConfiguration(stsConfig);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error parsing the configuration file:", e);
+ }
+ }
+}
Added: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/JBossSTSConfiguration.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/JBossSTSConfiguration.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/JBossSTSConfiguration.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,282 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2009, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.core.wstrust;
+
+import java.security.KeyPair;
+import java.security.PublicKey;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.jboss.identity.federation.core.config.KeyProviderType;
+import org.jboss.identity.federation.core.config.PropertyType;
+import org.jboss.identity.federation.core.config.STSType;
+import org.jboss.identity.federation.core.config.ServiceProviderType;
+import org.jboss.identity.federation.core.config.ServiceProvidersType;
+import org.jboss.identity.federation.core.config.TokenProviderType;
+import org.jboss.identity.federation.core.config.TokenProvidersType;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
+
+/**
+ * <p>
+ * Standard JBoss STS configuration implementation.
+ * </p>
+ *
+ * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
+ */
+public class JBossSTSConfiguration implements STSConfiguration
+{
+
+ // the delegate contains all the information extracted from the jboss-sts.xml configuration file.
+ private final STSType delegate;
+
+ private final Map<String, SecurityTokenProvider> tokenProviders = new HashMap<String, SecurityTokenProvider>();
+
+ private final Map<String, ServiceProviderType> spMetadata = new HashMap<String, ServiceProviderType>();
+
+ private TrustKeyManager trustManager;
+
+ private WSTrustRequestHandler handler;
+
+ /**
+ * <p>
+ * Creates an instance of {@code JBossSTSConfiguration} with default configuration values.
+ * </p>
+ */
+ public JBossSTSConfiguration()
+ {
+ this.delegate = new STSType();
+ this.delegate.setRequestHandler("org.jboss.identity.federation.core.wstrust.StandardRequestHandler");
+ // TODO: add default token provider classes.
+ }
+
+ /**
+ * <p>
+ * Creates an instance of {@code JBossSTSConfiguration} with the specified configuration.
+ * </p>
+ *
+ * @param config a reference to the object that holds the configuration of the STS.
+ */
+ public JBossSTSConfiguration(STSType config)
+ {
+ this.delegate = config;
+ // set the default request handler if one hasn't been specified.
+ if (this.delegate.getRequestHandler() == null)
+ this.delegate.setRequestHandler("org.jboss.identity.federation.core.wstrust.StandardRequestHandler");
+
+ // build the token-provider and service-metadata maps.
+ TokenProvidersType providers = this.delegate.getTokenProviders();
+ if (providers != null)
+ {
+ WSTrustServiceFactory serviceFactory = WSTrustServiceFactory.getInstance();
+ for (TokenProviderType provider : providers.getTokenProvider())
+ {
+ // create and initialize the token provider.
+ SecurityTokenProvider tokenProvider = serviceFactory.createTokenProvider(provider.getProviderClass());
+ Map<String, String> properties = new HashMap<String, String>();
+ for(PropertyType propertyType : provider.getProperty())
+ properties.put(propertyType.getName(), propertyType.getValue());
+ tokenProvider.initialize(properties);
+ // token providers can be keyed by the token type and by token element + namespace.
+ this.tokenProviders.put(provider.getTokenType(), tokenProvider);
+ String tokenElementAndNS = provider.getTokenElement() + "$" + provider.getTokenElementNS();
+ this.tokenProviders.put(tokenElementAndNS, tokenProvider);
+ }
+ }
+ ServiceProvidersType serviceProviders = this.delegate.getServiceProviders();
+ if (serviceProviders != null)
+ {
+ for (ServiceProviderType provider : serviceProviders.getServiceProvider())
+ this.spMetadata.put(provider.getEndpoint(), provider);
+ }
+ // setup the key store.
+ KeyProviderType keyProviderType = config.getKeyProvider();
+ if (keyProviderType != null)
+ {
+ String keyManagerClassName = keyProviderType.getClassName();
+ try
+ {
+ this.trustManager = (TrustKeyManager) SecurityActions.instantiateClass(keyManagerClassName);
+ this.trustManager.setAuthProperties(keyProviderType.getAuth());
+ this.trustManager.setValidatingAlias(keyProviderType.getValidatingAlias());
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Unable to construct the key manager:", e);
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getSTSName()
+ */
+ public String getSTSName()
+ {
+ return this.delegate.getSTSName();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getEncryptIssuedToken()
+ */
+ public boolean encryptIssuedToken()
+ {
+ return this.delegate.isEncryptToken();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#signIssuedToken()
+ */
+ public boolean signIssuedToken()
+ {
+ return this.delegate.isSignToken();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getIssuedTokenTimeout()
+ */
+ public long getIssuedTokenTimeout()
+ {
+ // return the timeout value in milliseconds.
+ return this.delegate.getTokenTimeout() * 1000;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getRequestHandlerClass()
+ */
+ public WSTrustRequestHandler getRequestHandler()
+ {
+ if (this.handler == null)
+ this.handler = WSTrustServiceFactory.getInstance().createRequestHandler(this.delegate.getRequestHandler(),
+ this);
+ return this.handler;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getProviderForService(java.lang.String)
+ */
+ public SecurityTokenProvider getProviderForService(String serviceName)
+ {
+ ServiceProviderType provider = this.spMetadata.get(serviceName);
+ if (provider != null)
+ {
+ return this.tokenProviders.get(provider.getTokenType());
+ }
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getProviderForTokenType(java.lang.String)
+ */
+ public SecurityTokenProvider getProviderForTokenType(String tokenType)
+ {
+ return this.tokenProviders.get(tokenType);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getProviderForTokenElementNS(java.lang.String, java.lang.String)
+ */
+ public SecurityTokenProvider getProviderForTokenElementNS(String tokenLocalName, String tokenNamespace)
+ {
+ return this.tokenProviders.get(tokenLocalName + "$" + tokenNamespace);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getTokenTypeForService(java.lang.String)
+ */
+ public String getTokenTypeForService(String serviceName)
+ {
+ ServiceProviderType provider = this.spMetadata.get(serviceName);
+ if (provider != null)
+ return provider.getTokenType();
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getServiceProviderPublicKey(java.lang.String)
+ */
+ public PublicKey getServiceProviderPublicKey(String serviceName)
+ {
+ PublicKey key = null;
+ if (this.trustManager != null)
+ {
+ try
+ {
+ // try using the truststore alias from the service provider metadata.
+ ServiceProviderType provider = this.spMetadata.get(serviceName);
+ if(provider != null && provider.getTruststoreAlias() != null)
+ {
+ key = this.trustManager.getPublicKey(provider.getTruststoreAlias());
+ }
+ // if there was no truststore alias or no PKC under that alias, use the KeyProvider mapping.
+ if(key == null)
+ {
+ key = this.trustManager.getValidatingKey(serviceName);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error obtaining public key for service " + serviceName, e);
+ }
+ }
+ return key;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getSTSKeyPair()
+ */
+ public KeyPair getSTSKeyPair()
+ {
+ KeyPair keyPair = null;
+ if (this.trustManager != null)
+ {
+ try
+ {
+ keyPair = this.trustManager.getSigningKeyPair();
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error obtaining signing key pair:", e);
+ }
+ }
+ return keyPair;
+ }
+
+}
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/StandardRequestHandler.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/StandardRequestHandler.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/StandardRequestHandler.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -214,6 +214,8 @@
response.setTokenType(request.getTokenType());
response.setLifetime(request.getLifetime());
response.setAppliesTo(appliesTo);
+ response.setKeySize(keySize);
+ response.setKeyType(keyType);
response.setRequestedSecurityToken(requestedSecurityToken);
if(requestedProofToken != null)
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAMLUtil.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAMLUtil.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAMLUtil.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -31,7 +31,6 @@
import org.jboss.identity.federation.core.util.JAXBUtil;
import org.jboss.identity.federation.saml.v2.assertion.AssertionType;
import org.jboss.identity.federation.saml.v2.assertion.ObjectFactory;
-import org.w3c.dom.DOMConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/util/KeystoreUtilUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/util/KeystoreUtilUnitTestCase.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/util/KeystoreUtilUnitTestCase.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,93 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.identity.federation.core.util;
+
+import java.io.InputStream;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.util.Enumeration;
+
+import junit.framework.TestCase;
+
+import org.jboss.identity.federation.core.saml.v2.util.SignatureUtil;
+import org.jboss.identity.federation.core.util.KeyStoreUtil;
+
+/**
+ * Test the KeyStore Util
+ * @author Anil.Saldhana(a)redhat.com
+ * @since Jan 15, 2009
+ */
+public class KeystoreUtilUnitTestCase extends TestCase
+{
+
+ /**
+ * Keystore (created 15Jan2009 and valid for 200K days)
+ * The Keystore has been created with the command (all in one line)
+keytool -genkey -alias servercert
+ -keyalg RSA
+ -keysize 1024
+ -dname "CN=jbossidentity.jboss.org,OU=RD,O=JBOSS,L=Chicago,S=Illinois,C=US"
+ -keypass test123
+ -keystore jbid_test_keystore.jks
+ -storepass store123
+ -validity 200000
+ */
+ private String keystoreLocation = "keystore/jbid_test_keystore.jks";
+ private String keystorePass = "store123";
+ private String alias = "servercert";
+ private String keyPass = "test123";
+
+
+ /**
+ Generated a selfsigned cert
+ keytool -selfcert
+ -alias servercert
+ -keypass test123
+ -keystore jbid_test_keystore.jks
+ -dname "cn=jbid test, ou=JBoss, o=JBoss, c=US"
+ -storepass store123
+ */
+ public void testSignatureValidationInvalidation() throws Exception
+ {
+ ClassLoader tcl = Thread.currentThread().getContextClassLoader();
+ InputStream ksStream = tcl.getResourceAsStream(keystoreLocation);
+ assertNotNull("Input keystore stream is not null", ksStream);
+
+ KeyStore ks = KeyStoreUtil.getKeyStore(ksStream, keystorePass.toCharArray());
+ assertNotNull("KeyStore is not null",ks);
+
+ //Check that there are aliases in the keystore
+ Enumeration<String> aliases = ks.aliases();
+ assertTrue("Aliases are not empty", aliases.hasMoreElements());
+
+ PublicKey publicKey = KeyStoreUtil.getPublicKey(ks, alias, keyPass.toCharArray());
+ assertNotNull("Public Key is not null", publicKey);
+
+ PrivateKey privateKey = (PrivateKey) ks.getKey(alias, keyPass.toCharArray());
+
+ String content = "Hello";
+ byte[] sigValue = SignatureUtil.sign(content, privateKey);
+ boolean isValid = SignatureUtil.validate(content.getBytes("UTF-8"), sigValue, publicKey);
+ assertTrue("Valid sig?", isValid);
+ }
+}
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/JBossSTSUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/JBossSTSUnitTestCase.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/JBossSTSUnitTestCase.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,875 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2009, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.identity.federation.core.wstrust;
+
+import java.net.URI;
+import java.security.Principal;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.Unmarshaller;
+import javax.xml.namespace.QName;
+import javax.xml.transform.Source;
+import javax.xml.ws.EndpointReference;
+import javax.xml.ws.WebServiceContext;
+import javax.xml.ws.WebServiceException;
+import javax.xml.ws.handler.MessageContext;
+
+import junit.framework.TestCase;
+
+import org.jboss.identity.federation.core.exceptions.ConfigurationException;
+import org.jboss.identity.federation.core.wstrust.JBossSTS;
+import org.jboss.identity.federation.core.wstrust.STSConfiguration;
+import org.jboss.identity.federation.core.wstrust.SecurityTokenProvider;
+import org.jboss.identity.federation.core.wstrust.StandardRequestHandler;
+import org.jboss.identity.federation.core.wstrust.WSTrustConstants;
+import org.jboss.identity.federation.core.wstrust.WSTrustException;
+import org.jboss.identity.federation.core.wstrust.WSTrustJAXBFactory;
+import org.jboss.identity.federation.core.wstrust.WSTrustRequestHandler;
+import org.jboss.identity.federation.core.wstrust.WSTrustUtil;
+import org.jboss.identity.federation.core.wstrust.plugins.saml.SAML20TokenProvider;
+import org.jboss.identity.federation.core.wstrust.plugins.saml.SAMLUtil;
+import org.jboss.identity.federation.core.wstrust.wrappers.BaseRequestSecurityTokenResponse;
+import org.jboss.identity.federation.core.wstrust.wrappers.Lifetime;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityToken;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponse;
+import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityTokenResponseCollection;
+import org.jboss.identity.federation.saml.v2.assertion.AssertionType;
+import org.jboss.identity.federation.saml.v2.assertion.AudienceRestrictionType;
+import org.jboss.identity.federation.saml.v2.assertion.ConditionAbstractType;
+import org.jboss.identity.federation.saml.v2.assertion.ConditionsType;
+import org.jboss.identity.federation.saml.v2.assertion.NameIDType;
+import org.jboss.identity.federation.saml.v2.assertion.SubjectConfirmationDataType;
+import org.jboss.identity.federation.saml.v2.assertion.SubjectConfirmationType;
+import org.jboss.identity.federation.ws.addressing.AttributedURIType;
+import org.jboss.identity.federation.ws.addressing.EndpointReferenceType;
+import org.jboss.identity.federation.ws.addressing.ObjectFactory;
+import org.jboss.identity.federation.ws.policy.AppliesTo;
+import org.jboss.identity.federation.ws.trust.BinarySecretType;
+import org.jboss.identity.federation.ws.trust.EntropyType;
+import org.jboss.identity.federation.ws.trust.RequestedProofTokenType;
+import org.jboss.identity.federation.ws.trust.RequestedReferenceType;
+import org.jboss.identity.federation.ws.trust.RequestedSecurityTokenType;
+import org.jboss.identity.federation.ws.trust.StatusType;
+import org.jboss.identity.federation.ws.trust.ValidateTargetType;
+import org.jboss.identity.federation.ws.wss.secext.KeyIdentifierType;
+import org.jboss.identity.federation.ws.wss.secext.SecurityTokenReferenceType;
+import org.jboss.identity.xmlsec.w3.xmldsig.KeyInfoType;
+import org.jboss.identity.xmlsec.w3.xmldsig.X509DataType;
+import org.jboss.identity.xmlsec.w3.xmlenc.EncryptedKeyType;
+import org.w3c.dom.Element;
+
+/**
+ * <p>
+ * This {@code TestCase} tests the behavior of the {@code JBossSTS} service.
+ * </p>
+ *
+ * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
+ */
+public class JBossSTSUnitTestCase extends TestCase
+{
+
+ private TestSTS tokenService;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see junit.framework.TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception
+ {
+ super.setUp();
+ // for testing purposes we can instantiate the TestSTS as a regular POJO.
+ this.tokenService = new TestSTS();
+ TestContext context = new TestContext();
+ context.setUserPrincipal(new TestPrincipal("sguilhen"));
+ this.tokenService.setContext(context);
+ }
+
+ /**
+ * <p>
+ * This test verifies that the STS service can read and load all configuration parameters correctly. The
+ * configuration file (jboss-sts.xml) looks like the following:
+ *
+ * <pre>
+ * <JBossSTS xmlns="urn:jboss:identity-federation:config:1.0"
+ * STSName="Test STS" TokenTimeout="7200" EncryptToken="true">
+ * <KeyProvider ClassName="org.jboss.identity.federation.bindings.tomcat.KeyStoreKeyManager">
+ * <Auth Key="KeyStoreURL" Value="keystore/sts_keystore.jks"/>
+ * <Auth Key="KeyStorePass" Value="testpass"/>
+ * <Auth Key="SigningKeyAlias" Value="sts"/>
+ * <Auth Key="SigningKeyPass" Value="keypass"/>
+ * <ValidatingAlias Key="http://services.testcorp.org/provider1" Value="service1"/>
+ * <ValidatingAlias Key="http://services.testcorp.org/provider2" Value="service2"/>
+ * </KeyProvider>
+ * <RequestHandler>org.jboss.identity.federation.core.wstrust.StandardRequestHandler</RequestHandler>
+ * <TokenProviders>
+ * <TokenProvider ProviderClass="org.jboss.test.identity.federation.bindings.trust.SpecialTokenProvider"
+ * TokenType="http://www.tokens.org/SpecialToken"/>
+ * <TokenProvider ProviderClass="org.jboss.identity.federation.core.wstrust.SAML20TokenProvider"
+ * TokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profi...
+ * </TokenProviders>
+ * <ServiceProviders>
+ * <ServiceProvider Endpoint="http://services.testcorp.org/provider1" TokenType="http://www.tokens.org/SpecialToken"
+ * TruststoreAlias="service1"/>
+ * <ServiceProvider Endpoint="http://services.testcorp.org/provider2" TokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profi...
+ * TruststoreAlias="service2"/>
+ * </ServiceProviders>
+ * </JBossSTS> *
+ * </pre>
+ *
+ * </p>
+ *
+ * @throws Exception
+ * if an error occurs while running the test.
+ */
+ public void testSTSConfiguration() throws Exception
+ {
+ // make the STS read the configuration file.
+ STSConfiguration config = this.tokenService.getConfiguration();
+
+ // check the values that have been configured.
+ assertEquals("Unexpected service name", "Test STS", config.getSTSName());
+ assertEquals("Unexpected token timeout value", 7200 * 1000, config.getIssuedTokenTimeout());
+ assertTrue("Encrypt token should be true", config.encryptIssuedToken());
+ WSTrustRequestHandler handler = config.getRequestHandler();
+ assertNotNull("Unexpected null request handler found", handler);
+ assertTrue("Unexpected request handler type", handler instanceof StandardRequestHandler);
+
+ // check the token type -> token provider mapping.
+ SecurityTokenProvider provider = config.getProviderForTokenType("http://www.tokens.org/SpecialToken");
+ assertNotNull("Unexpected null token provider", provider);
+ assertTrue("Unexpected token provider type", provider instanceof SpecialTokenProvider);
+ Map<String, String> properties = ((SpecialTokenProvider) provider).getProperties();
+ assertNotNull("Unexpected null properties map", properties);
+ assertEquals("Unexpected number of properties", 2, properties.size());
+ assertEquals("Invalid property found", "Value1", properties.get("Property1"));
+ assertEquals("Invalid property found", "Value2", properties.get("Property2"));
+ provider = config.getProviderForTokenType(SAMLUtil.SAML2_TOKEN_TYPE);
+ assertNotNull("Unexpected null token provider", provider);
+ assertTrue("Unexpected token provider type", provider instanceof SAML20TokenProvider);
+ assertNull(config.getProviderForTokenType("unexistentType"));
+
+ // check the service provider -> token provider mapping.
+ provider = config.getProviderForService("http://services.testcorp.org/provider1");
+ assertNotNull("Unexpected null token provider", provider);
+ assertTrue("Unexpected token provider type", provider instanceof SpecialTokenProvider);
+ provider = config.getProviderForService("http://services.testcorp.org/provider2");
+ assertNotNull("Unexpected null token provider", provider);
+ assertTrue("Unexpected token provider type", provider instanceof SAML20TokenProvider);
+ assertNull(config.getProviderForService("http://invalid.service/service"));
+
+ // check the token element and namespace -> token provider mapping.
+ provider = config.getProviderForTokenElementNS("SpecialToken", "http://www.tokens.org");
+ assertNotNull("Unexpected null token provider", provider);
+ assertTrue("Unexpected token provider type", provider instanceof SpecialTokenProvider);
+ provider = config.getProviderForTokenElementNS("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion");
+ assertNotNull("Unexpected null token provider", provider);
+ assertTrue("Unexpected token provider type", provider instanceof SAML20TokenProvider);
+ assertNull(config.getProviderForTokenElementNS("SpecialToken", "InvalidNamespace"));
+
+ // check the service provider -> token type mapping.
+ assertEquals("Invalid token type for service provider 1", "http://www.tokens.org/SpecialToken", config
+ .getTokenTypeForService("http://services.testcorp.org/provider1"));
+ assertEquals("Invalid token type for service provider 2", SAMLUtil.SAML2_TOKEN_TYPE, config
+ .getTokenTypeForService("http://services.testcorp.org/provider2"));
+ assertNull(config.getTokenTypeForService("http://invalid.service/service"));
+
+ // check the keystore configuration.
+ assertNotNull("Invalid null STS key pair", config.getSTSKeyPair());
+ assertNotNull("Invalid null STS public key", config.getSTSKeyPair().getPublic());
+ assertNotNull("Invalid null STS private key", config.getSTSKeyPair().getPrivate());
+ assertNotNull("Invalid null validating key for service provider 1", config
+ .getServiceProviderPublicKey("http://services.testcorp.org/provider1"));
+ assertNotNull("Invalid null validating key for service provider 2", config
+ .getServiceProviderPublicKey("http://services.testcorp.org/provider2"));
+ }
+
+ /**
+ * <p>
+ * This tests sends a security token request to JBossSTS custom {@code SpecialTokenProvider}. The returned response
+ * is verified to make sure the expected tokens have been returned by the service. The token that is generated in
+ * this test looks as follows:
+ *
+ * <pre>
+ * <token:SpecialToken xmlns:token="http://www.tokens.org" TokenType="http://www.tokens.org/SpecialToken">
+ * Principal:sguilhen
+ * </token:SpecialToken>
+ * </pre>
+ *
+ * </p>
+ *
+ * @throws Exception
+ * if an error occurs while running the test.
+ */
+ public void testInvokeCustom() throws Exception
+ {
+ // create a simple token request, asking for a "special" test token.
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST,
+ "http://www.tokens.org/SpecialToken", null);
+
+ // use the factory to marshall the request.
+ WSTrustJAXBFactory factory = WSTrustJAXBFactory.getInstance();
+ Source requestMessage = factory.marshallRequestSecurityToken(request);
+
+ // invoke the token service.
+ Source responseMessage = this.tokenService.invoke(requestMessage);
+ BaseRequestSecurityTokenResponse baseResponse = WSTrustJAXBFactory.getInstance()
+ .parseRequestSecurityTokenResponse(responseMessage);
+
+ // validate the security token response.
+ this.validateCustomTokenResponse(baseResponse);
+ }
+
+ /**
+ * <p>
+ * This tests sends a SAMLV2.0 security token request to JBossSTS. This request should be handled by the standard
+ * {@code SAML20TokenProvider} and should result in a SAMLV2.0 assertion that looks like the following:
+ *
+ * <pre>
+ * <saml2:Assertion xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"
+ * xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
+ * xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"
+ * ID="ID-cc541137-74dc-4fc0-8bcc-7e9e3a4c899d"
+ * IssueInstant="2009-05-29T18:02:13.458Z">
+ * <saml2:Issuer>
+ * JBossSTS
+ * </saml2:Issuer>
+ * <saml2:Subject>
+ * <saml2:NameID NameQualifier="http://www.jboss.org">
+ * sguilhen
+ * </saml2:NameID>
+ * <saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"/>
+ * </saml2:Subject>
+ * <saml2:Conditions NotBefore="2009-05-29T18:02:13.458Z" NotOnOrAfter="2009-05-29T19:02:13.458Z">
+ * <saml2:AudienceRestriction>
+ * <saml2:Audience>
+ * http://services.testcorp.org/provider2
+ * </saml2:Audience>
+ * </saml2:AudienceRestriction>
+ * </saml2:Conditions>
+ * <ds:Signature>
+ * ...
+ * </ds:Signature>
+ * </saml2:Assertion>
+ * </pre>
+ *
+ * </p>
+ *
+ * @throws Exception
+ * if an error occurs while running the test.
+ */
+ public void testInvokeSAML20() throws Exception
+ {
+ // create a simple token request, asking for a SAMLv2.0 token.
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST,
+ SAMLUtil.SAML2_TOKEN_TYPE, null);
+
+ // use the factory to marshall the request.
+ WSTrustJAXBFactory factory = WSTrustJAXBFactory.getInstance();
+ Source requestMessage = factory.marshallRequestSecurityToken(request);
+
+ // invoke the token service.
+ Source responseMessage = this.tokenService.invoke(requestMessage);
+ BaseRequestSecurityTokenResponse baseResponse = WSTrustJAXBFactory.getInstance()
+ .parseRequestSecurityTokenResponse(responseMessage);
+
+ // validate the security token response.
+ this.validateSAMLAssertionResponse(baseResponse, SAMLUtil.SAML2_BEARER_URI);
+ }
+
+ /**
+ * <p>
+ * This test requests a token to the STS using the {@code AppliesTo} to identify the service provider. The STS must
+ * be able to find out the type of the token that must be issued using the service provider URI. In this specific
+ * case, the request should be handled by the custom {@code SpecialTokenProvider}.
+ * </p>
+ *
+ * @throws Exception
+ * if an error occurs while running the test.
+ */
+ public void testInvokeCustomAppliesTo() throws Exception
+ {
+ // create a simple token request, this time using the applies to get to the token type.
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST, null,
+ "http://services.testcorp.org/provider1");
+
+ // use the factory to marshall the request.
+ WSTrustJAXBFactory factory = WSTrustJAXBFactory.getInstance();
+ Source requestMessage = factory.marshallRequestSecurityToken(request);
+
+ // invoke the token service.
+ Source responseMessage = this.tokenService.invoke(requestMessage);
+ BaseRequestSecurityTokenResponse baseResponse = WSTrustJAXBFactory.getInstance()
+ .parseRequestSecurityTokenResponse(responseMessage);
+
+ // validate the security token response.
+ this.validateCustomTokenResponse(baseResponse);
+ }
+
+ /**
+ * <p>
+ * This test requests a token to the STS using the {@code AppliesTo} to identify the service provider. The STS must
+ * be able to find out the type of the token that must be issued using the service provider URI. In this specific
+ * case, the request should be handled by the standard {@code SAML20TokenProvider}.
+ * </p>
+ *
+ * @throws Exception
+ * if an error occurs while running the test.
+ */
+ public void testInvokeSAML20AppliesTo() throws Exception
+ {
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST, null,
+ "http://services.testcorp.org/provider2");
+
+ // use the factory to marshall the request.
+ WSTrustJAXBFactory factory = WSTrustJAXBFactory.getInstance();
+ Source requestMessage = factory.marshallRequestSecurityToken(request);
+
+ // invoke the token service.
+ Source responseMessage = this.tokenService.invoke(requestMessage);
+ BaseRequestSecurityTokenResponse baseResponse = WSTrustJAXBFactory.getInstance()
+ .parseRequestSecurityTokenResponse(responseMessage);
+
+ // validate the security token response.
+ AssertionType assertion = this.validateSAMLAssertionResponse(baseResponse, SAMLUtil.SAML2_BEARER_URI);
+
+ // in this scenario, the conditions section should have an audience restriction.
+ ConditionsType conditions = assertion.getConditions();
+ assertEquals("Unexpected restriction list size", 1, conditions.getConditionOrAudienceRestrictionOrOneTimeUse()
+ .size());
+ ConditionAbstractType abstractType = conditions.getConditionOrAudienceRestrictionOrOneTimeUse().get(0);
+ assertTrue("Unexpected restriction type", abstractType instanceof AudienceRestrictionType);
+ AudienceRestrictionType audienceRestriction = (AudienceRestrictionType) abstractType;
+ assertEquals("Unexpected audience restriction list size", 1, audienceRestriction.getAudience().size());
+ assertEquals("Unexpected audience restriction item", "http://services.testcorp.org/provider2",
+ audienceRestriction.getAudience().get(0));
+ }
+
+ /**
+ * <p>
+ * This test requests a SAMLV2.0 assertion and requires a symmetric key to be used as a proof-of-possession token.
+ * As the request doesn't contain any client-specified key, the STS is responsible for generating a random key and
+ * use this key as the proof token. The WS-Trust response should contain the STS-generated key.
+ * </p>
+ *
+ * @throws Exception if an error occurs while running the test.
+ */
+ @SuppressWarnings("unchecked")
+ public void testInvokeSAML20WithSTSGeneratedSymmetricKey() throws Exception
+ {
+ // create a simple token request, asking for a SAMLv2.0 token.
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST, null,
+ "http://services.testcorp.org/provider2");
+
+ // add a symmetric key type to the request, but don't supply any client key - STS should generate one.
+ request.setKeyType(URI.create(WSTrustConstants.KEY_TYPE_SYMMETRIC));
+
+ // use the factory to marshall the request.
+ WSTrustJAXBFactory factory = WSTrustJAXBFactory.getInstance();
+ Source requestMessage = factory.marshallRequestSecurityToken(request);
+
+ // invoke the token service.
+ Source responseMessage = this.tokenService.invoke(requestMessage);
+ BaseRequestSecurityTokenResponse baseResponse = WSTrustJAXBFactory.getInstance()
+ .parseRequestSecurityTokenResponse(responseMessage);
+
+ // validate the security token response.
+ this.validateSAMLAssertionResponse(baseResponse, SAMLUtil.SAML2_HOLDER_OF_KEY_URI);
+
+ // check if the response contains the STS-generated key.
+ RequestSecurityTokenResponseCollection collection = (RequestSecurityTokenResponseCollection) baseResponse;
+ RequestSecurityTokenResponse response = collection.getRequestSecurityTokenResponses().get(0);
+ RequestedProofTokenType proofToken = response.getRequestedProofToken();
+ assertNotNull("Unexpected null proof token", proofToken);
+ assertTrue(proofToken.getAny() instanceof JAXBElement);
+ JAXBElement proofElement = (JAXBElement) proofToken.getAny();
+ assertEquals("Unexpected proof token content", BinarySecretType.class, proofElement.getDeclaredType());
+ BinarySecretType serverBinarySecret = (BinarySecretType) proofElement.getValue();
+ assertNotNull("Unexpected null secret", serverBinarySecret.getValue());
+ // default key size is 256 bits (32 bytes).
+ assertEquals("Unexpected secret size", 32, serverBinarySecret.getValue().length);
+ }
+
+ /**
+ * <p>
+ * This test requests a SAMLV2.0 assertion and requires a symmetric key to be used as a proof-of-possession token.
+ * In this case, the client supplies a secret key in the WS-Trust request, so the STS should combine the client-
+ * specified key with the STS-generated key and use this combined key as the proof token. The WS-Trust response
+ * should include the STS key to allow reconstruction of the combined key and the algorithm used to combine the keys.
+ * </p>
+ *
+ * @throws Exception if an error occurs while running the test.
+ */
+ @SuppressWarnings("unchecked")
+ public void testInvokeSAML20WithCombinedSymmetricKey() throws Exception
+ {
+ // create a 128-bit random client secret.
+ byte[] clientSecret = WSTrustUtil.createRandomSecret(16);
+ BinarySecretType clientBinarySecret = new BinarySecretType();
+ clientBinarySecret.setType(WSTrustConstants.BS_TYPE_NONCE);
+ clientBinarySecret.setValue(clientSecret);
+
+ // set the client secret in the client entropy.
+ EntropyType clientEntropy = new EntropyType();
+ clientEntropy.getAny().add(
+ new org.jboss.identity.federation.ws.trust.ObjectFactory().createBinarySecret(clientBinarySecret));
+
+ // create a token request specifying the key type, key size, and client entropy.
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST, null,
+ "http://services.testcorp.org/provider2");
+ request.setKeyType(URI.create(WSTrustConstants.KEY_TYPE_SYMMETRIC));
+ request.setEntropy(clientEntropy);
+ request.setKeySize(128);
+
+ // invoke the token service.
+ Source requestMessage = WSTrustJAXBFactory.getInstance().marshallRequestSecurityToken(request);
+ Source responseMessage = this.tokenService.invoke(requestMessage);
+ BaseRequestSecurityTokenResponse baseResponse = WSTrustJAXBFactory.getInstance()
+ .parseRequestSecurityTokenResponse(responseMessage);
+
+ // validate the security token response.
+ this.validateSAMLAssertionResponse(baseResponse, SAMLUtil.SAML2_HOLDER_OF_KEY_URI);
+
+ RequestSecurityTokenResponseCollection collection = (RequestSecurityTokenResponseCollection) baseResponse;
+ RequestSecurityTokenResponse response = collection.getRequestSecurityTokenResponses().get(0);
+ RequestedProofTokenType proofToken = response.getRequestedProofToken();
+ assertNotNull("Unexpected null proof token", proofToken);
+ assertTrue(proofToken.getAny() instanceof JAXBElement);
+ JAXBElement<?> proofElement = (JAXBElement<?>) proofToken.getAny();
+
+ // proof token should contain only the computed key algorithm.
+ assertEquals("Unexpected proof token content", "ComputedKey", proofElement.getName().getLocalPart());
+ assertEquals("Unexpected computed key algorithm", WSTrustConstants.CK_PSHA1, proofElement.getValue());
+
+ // server entropy must have been included in the response to allow reconstruction of the computed key.
+ EntropyType serverEntropy = response.getEntropy();
+ assertNotNull("Unexpected null server entropy");
+ assertEquals("Invalid number of elements in server entropy", 1, serverEntropy.getAny().size());
+ JAXBElement serverEntropyContent = (JAXBElement) serverEntropy.getAny().get(0);
+ assertEquals("Unexpected proof token content", BinarySecretType.class, serverEntropyContent.getDeclaredType());
+ BinarySecretType serverBinarySecret = (BinarySecretType) serverEntropyContent.getValue();
+ assertEquals("Unexpected binary secret type", WSTrustConstants.BS_TYPE_NONCE, serverBinarySecret.getType());
+ assertNotNull("Unexpected null secret value", serverBinarySecret.getValue());
+ assertEquals("Unexpected secret size", 16, serverBinarySecret.getValue().length);
+ }
+
+ /**
+ * <p>
+ * This test case first generates a SAMLV2.0 assertion and then sends a WS-Trust validate message to the STS to get
+ * the assertion validated, checking the validation results.
+ * </p>
+ *
+ * @throws Exception
+ * if an error occurs while running the test.
+ */
+ public void testInvokeSAML20Validate() throws Exception
+ {
+ // create a simple token request, this time using the applies to get to the token type.
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST,
+ SAMLUtil.SAML2_TOKEN_TYPE, null);
+
+ // use the factory to marshall the request.
+ WSTrustJAXBFactory factory = WSTrustJAXBFactory.getInstance();
+ Source requestMessage = factory.marshallRequestSecurityToken(request);
+
+ // invoke the token service.
+ Source responseMessage = this.tokenService.invoke(requestMessage);
+ BaseRequestSecurityTokenResponse baseResponse = factory.parseRequestSecurityTokenResponse(responseMessage);
+
+ // get the SAML assertion from the request.
+ RequestSecurityTokenResponseCollection collection = (RequestSecurityTokenResponseCollection) baseResponse;
+ Element assertion = (Element) collection.getRequestSecurityTokenResponses().get(0).getRequestedSecurityToken()
+ .getAny();
+
+ // now construct a WS-Trust validate request with the generated assertion.
+ request = this.createRequest("validatecontext", WSTrustConstants.VALIDATE_REQUEST, WSTrustConstants.STATUS_TYPE,
+ null);
+ ValidateTargetType validateTarget = new ValidateTargetType();
+ validateTarget.setAny(assertion);
+ request.setValidateTarget(validateTarget);
+
+ // invoke the token service.
+ responseMessage = this.tokenService.invoke(factory.marshallRequestSecurityToken(request));
+ baseResponse = factory.parseRequestSecurityTokenResponse(responseMessage);
+
+ // validate the response contents.
+ assertNotNull("Unexpected null response", baseResponse);
+ assertTrue("Unexpected response type", baseResponse instanceof RequestSecurityTokenResponseCollection);
+ collection = (RequestSecurityTokenResponseCollection) baseResponse;
+ assertEquals("Unexpected number of responses", 1, collection.getRequestSecurityTokenResponses().size());
+ RequestSecurityTokenResponse response = collection.getRequestSecurityTokenResponses().get(0);
+ assertEquals("Unexpected response context", "validatecontext", response.getContext());
+ assertEquals("Unexpected token type", WSTrustConstants.STATUS_TYPE, response.getTokenType().toString());
+ StatusType status = response.getStatus();
+ assertNotNull("Unexpected null status", status);
+ assertEquals("Unexpected status code", WSTrustConstants.STATUS_CODE_VALID, status.getCode());
+ assertEquals("Unexpected status reason", "SAMLV2.0 Assertion successfuly validated", status.getReason());
+
+ // now let's temper the SAML assertion and try to validate it again.
+ assertion.getFirstChild().getFirstChild().setNodeValue("Tempered Issuer");
+ request.getValidateTarget().setAny(assertion);
+ responseMessage = this.tokenService.invoke(factory.marshallRequestSecurityToken(request));
+ collection = (RequestSecurityTokenResponseCollection) WSTrustJAXBFactory.getInstance()
+ .parseRequestSecurityTokenResponse(responseMessage);
+ assertEquals("Unexpected number of responses", 1, collection.getRequestSecurityTokenResponses().size());
+ response = collection.getRequestSecurityTokenResponses().get(0);
+ assertEquals("Unexpected response context", "validatecontext", response.getContext());
+ assertEquals("Unexpected token type", WSTrustConstants.STATUS_TYPE, response.getTokenType().toString());
+ status = response.getStatus();
+ assertNotNull("Unexpected null status", status);
+ assertEquals("Unexpected status code", WSTrustConstants.STATUS_CODE_INVALID, status.getCode());
+ assertEquals("Unexpected status reason", "Validation failure: digital signature is invalid", status.getReason());
+ }
+
+ /**
+ * <p>
+ * This test tries to request a token of an unknown type, checking if an exception is correctly thrown by the
+ * security token service.
+ * </p>
+ *
+ * @throws Exception
+ * if an error occurs while running the test.
+ */
+ public void testInvokeUnknownTokenType() throws Exception
+ {
+ // create a simple token request, asking for an "unknown" test token.
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST,
+ "http://www.tokens.org/UnknownToken", null);
+
+ // use the factory to marshall the request.
+ WSTrustJAXBFactory factory = WSTrustJAXBFactory.getInstance();
+ Source requestMessage = factory.marshallRequestSecurityToken(request);
+
+ // invoke the security token service.
+ try
+ {
+ this.tokenService.invoke(requestMessage);
+ fail("An exception should have been raised by the security token service");
+ }
+ catch (WebServiceException we)
+ {
+ assertEquals("Unexpected exception message", "Exception in handling token request:", we.getMessage());
+ assertNotNull("Unexpected null cause", we.getCause());
+ assertTrue("Unexpected cause type", we.getCause() instanceof WSTrustException);
+ assertEquals("Unexpected exception message", "Unable to find a token provider for the token request", we
+ .getCause().getMessage());
+ }
+ }
+
+ /**
+ * <p>
+ * Validates the contents of a WS-Trust response message that contains a custom token issued by the test {@code
+ * SpecialTokenProvider}.
+ * </p>
+ *
+ * @param baseResponse
+ * a reference to the WS-Trust response that was sent by the STS.
+ * @throws Exception
+ * if one of the validation performed fail.
+ */
+ private void validateCustomTokenResponse(BaseRequestSecurityTokenResponse baseResponse) throws Exception
+ {
+
+ // =============================== WS-Trust Security Token Response Validation ===============================//
+
+ assertNotNull("Unexpected null response", baseResponse);
+ assertTrue("Unexpected response type", baseResponse instanceof RequestSecurityTokenResponseCollection);
+ RequestSecurityTokenResponseCollection collection = (RequestSecurityTokenResponseCollection) baseResponse;
+ assertEquals("Unexpected number of responses", 1, collection.getRequestSecurityTokenResponses().size());
+ RequestSecurityTokenResponse response = collection.getRequestSecurityTokenResponses().get(0);
+ assertEquals("Unexpected response context", "testcontext", response.getContext());
+ assertEquals("Unexpected token type", "http://www.tokens.org/SpecialToken", response.getTokenType().toString());
+ Lifetime lifetime = response.getLifetime();
+ assertNotNull("Unexpected null token lifetime", lifetime);
+
+ // ========================================= Custom Token Validation =========================================//
+
+ RequestedSecurityTokenType requestedToken = response.getRequestedSecurityToken();
+ assertNotNull("Unexpected null requested security token", requestedToken);
+ Object token = requestedToken.getAny();
+ assertNotNull("Unexpected null token", token);
+ assertTrue("Unexpected token class", token instanceof Element);
+ Element element = (Element) requestedToken.getAny();
+ assertEquals("Unexpected namespace value", "http://www.tokens.org", element.getNamespaceURI());
+
+ assertEquals("Unexpected attribute value", "http://www.tokens.org/SpecialToken", element.getAttributeNS(
+ "http://www.tokens.org", "TokenType"));
+ assertEquals("Unexpected token value", "Principal:sguilhen", element.getFirstChild().getNodeValue());
+ }
+
+ /**
+ * <p>
+ * Validates the contents of a WS-Trust response message that contains a SAMLV2.0 assertion issued by the {@code
+ * SAML20TokenProvider}.
+ * </p>
+ *
+ * @param baseResponse
+ * a reference to the WS-Trust response that was sent by the STS.
+ * @return the SAMLV2.0 assertion that has been extracted from the response. This object can be used by the test
+ * methods to perform extra validations depending on the scenario being tested.
+ * @throws Exception
+ * if one of the validation performed fail.
+ */
+ private AssertionType validateSAMLAssertionResponse(BaseRequestSecurityTokenResponse baseResponse,
+ String confirmationMethod) throws Exception
+ {
+
+ // =============================== WS-Trust Security Token Response Validation ===============================//
+
+ assertNotNull("Unexpected null response", baseResponse);
+ assertTrue("Unexpected response type", baseResponse instanceof RequestSecurityTokenResponseCollection);
+ RequestSecurityTokenResponseCollection collection = (RequestSecurityTokenResponseCollection) baseResponse;
+ assertEquals("Unexpected number of responses", 1, collection.getRequestSecurityTokenResponses().size());
+ RequestSecurityTokenResponse response = collection.getRequestSecurityTokenResponses().get(0);
+ assertEquals("Unexpected response context", "testcontext", response.getContext());
+ assertEquals("Unexpected token type", SAMLUtil.SAML2_TOKEN_TYPE, response.getTokenType().toString());
+ Lifetime lifetime = response.getLifetime();
+ assertNotNull("Unexpected null token lifetime", lifetime);
+
+ // validate the attached token reference.
+ RequestedReferenceType reference = response.getRequestedAttachedReference();
+ assertNotNull("Unexpected null attached reference", reference);
+ SecurityTokenReferenceType securityRef = reference.getSecurityTokenReference();
+ assertNotNull("Unexpected null security reference", securityRef);
+ String tokenTypeAttr = securityRef.getOtherAttributes().get(new QName(WSTrustConstants.WSSE11_NS, "TokenType"));
+ assertNotNull("Required attribute TokenType is missing", tokenTypeAttr);
+ assertEquals("TokenType attribute has an unexpected value", SAMLUtil.SAML2_TOKEN_TYPE, tokenTypeAttr);
+ JAXBElement<?> keyIdElement = (JAXBElement<?>) securityRef.getAny().get(0);
+ KeyIdentifierType keyId = (KeyIdentifierType) keyIdElement.getValue();
+ assertEquals("Unexpected key value type", SAMLUtil.SAML2_VALUE_TYPE, keyId.getValueType());
+ assertNotNull("Unexpected null key identifier value", keyId.getValue());
+
+ // ====================================== SAMLV2.0 Assertion Validation ======================================//
+
+ RequestedSecurityTokenType requestedToken = response.getRequestedSecurityToken();
+ assertNotNull("Unexpected null requested security token", requestedToken);
+
+ // unmarshall the SAMLV2.0 assertion.
+ JAXBContext jaxbContext = JAXBContext.newInstance("org.jboss.identity.federation.saml.v2.assertion");
+ Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
+ JAXBElement<?> assertionElement = (JAXBElement<?>) unmarshaller.unmarshal((Element) requestedToken.getAny());
+ assertEquals("Unexpected assertion type", AssertionType.class, assertionElement.getDeclaredType());
+ AssertionType assertion = (AssertionType) assertionElement.getValue();
+
+ // verify the contents of the unmarshalled assertion.
+ assertNotNull("Invalid null assertion ID", assertion.getID());
+ assertEquals(keyId.getValue().substring(1), assertion.getID());
+ assertEquals(lifetime.getCreated(), assertion.getIssueInstant());
+
+ // validate the assertion issuer.
+ assertNotNull("Unexpected null assertion issuer", assertion.getIssuer());
+ assertEquals("Unexpected assertion issuer name", "Test STS", assertion.getIssuer().getValue());
+
+ // validate the assertion subject.
+ assertNotNull("Unexpected null subject", assertion.getSubject());
+ List<JAXBElement<?>> content = assertion.getSubject().getContent();
+ assertNotNull("Unexpected null subject content");
+ assertEquals(2, content.size());
+ assertEquals("Unexpected type found", NameIDType.class, content.get(0).getDeclaredType());
+ NameIDType nameID = (NameIDType) content.get(0).getValue();
+ assertEquals("Unexpected name id qualifier", "urn:jboss:identity-federation", nameID.getNameQualifier());
+ assertEquals("Unexpected name id value", "sguilhen", nameID.getValue());
+ assertEquals("Unexpected type found", SubjectConfirmationType.class, content.get(1).getDeclaredType());
+ SubjectConfirmationType subjType = (SubjectConfirmationType) content.get(1).getValue();
+ assertEquals("Unexpected confirmation method", confirmationMethod, subjType.getMethod());
+
+ // if confirmation method is holder of key, make sure the assertion contains a KeyInfo with the proof token.
+ if (SAMLUtil.SAML2_HOLDER_OF_KEY_URI.equals(confirmationMethod))
+ {
+ SubjectConfirmationDataType subjConfirmationDataType = subjType.getSubjectConfirmationData();
+ assertNotNull("Unexpected null subject confirmation data", subjConfirmationDataType);
+ List<Object> confirmationContent = subjConfirmationDataType.getContent();
+ assertEquals("Unexpected subject confirmation content size", 1, confirmationContent.size());
+ JAXBElement<?> keyInfoElement = (JAXBElement<?>) confirmationContent.get(0);
+ assertEquals("Unexpected subject confirmation context type", KeyInfoType.class, keyInfoElement
+ .getDeclaredType());
+ KeyInfoType keyInfo = (KeyInfoType) keyInfoElement.getValue();
+ assertEquals("Unexpected key info content size", 1, keyInfo.getContent().size());
+
+ // if they key is a symmetric key, the KeyInfo should contain an encrypted element.
+ if (WSTrustConstants.KEY_TYPE_SYMMETRIC.equals(response.getKeyType().toString()))
+ {
+ JAXBElement<?> encKeyElement = (JAXBElement<?>) keyInfo.getContent().get(0);
+ assertEquals("Unexpected key info content type", EncryptedKeyType.class, encKeyElement.getDeclaredType());
+ }
+ // if the key is a public key, the KeyInfo should contain an encoded certificate.
+ else if(WSTrustConstants.KEY_TYPE_PUBLIC.equals(response.getKeyType().toString()))
+ {
+ JAXBElement<?> x509DataElement = (JAXBElement<?>) keyInfo.getContent().get(0);
+ assertEquals("Unexpected key info content type", X509DataType.class, x509DataElement.getDeclaredType());
+ X509DataType x509Data = (X509DataType) x509DataElement.getValue();
+ assertEquals("Unexpected X509 data content size", 1, x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName().
+ size());
+ JAXBElement<?> x509CertElement = (JAXBElement<?>) x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName().get(0);
+ assertEquals("Unexpected X509 data content type", byte[].class, x509CertElement.getDeclaredType());
+ }
+ }
+
+ // validate the assertion conditions.
+ assertNotNull("Unexpected null conditions", assertion.getConditions());
+ assertEquals(lifetime.getCreated(), assertion.getConditions().getNotBefore());
+ assertEquals(lifetime.getExpires(), assertion.getConditions().getNotOnOrAfter());
+
+ // verify if the assertion has been signed.
+ assertNotNull("Assertion should have been signed", assertion.getSignature());
+
+ return assertion;
+ }
+
+ /**
+ * <p>
+ * Utility method that creates a simple WS-Trust request using the specified information.
+ * </p>
+ *
+ * @param context
+ * a {@code String} that represents the request context.
+ * @param requestType
+ * a {@code String} that represents the WS-Trust request type.
+ * @param tokenType
+ * a {@code String} that represents the requested token type.
+ * @param appliesToString
+ * a {@code String} that represents the URL of a service provider.
+ * @return the constructed {@code RequestSecurityToken} object.
+ */
+ private RequestSecurityToken createRequest(String context, String requestType, String tokenType,
+ String appliesToString)
+ {
+ RequestSecurityToken request = new RequestSecurityToken();
+ request.setContext(context);
+ request.setRequestType(URI.create(requestType));
+ if (tokenType != null)
+ request.setTokenType(URI.create(tokenType));
+ if (appliesToString != null)
+ {
+ AttributedURIType attributedURI = new AttributedURIType();
+ attributedURI.setValue(appliesToString);
+ EndpointReferenceType reference = new EndpointReferenceType();
+ reference.setAddress(attributedURI);
+ AppliesTo appliesTo = new AppliesTo();
+ appliesTo.getAny().add(new ObjectFactory().createEndpointReference(reference));
+ request.setAppliesTo(appliesTo);
+ }
+ return request;
+ }
+
+ /**
+ * <p>
+ * Helper class that exposes the JBossSTS methods as public for the tests to work.
+ * </p>
+ *
+ * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
+ */
+ class TestSTS extends JBossSTS
+ {
+
+ @Override
+ public STSConfiguration getConfiguration() throws ConfigurationException
+ {
+ return super.getConfiguration();
+ }
+
+ public void setContext(WebServiceContext context)
+ {
+ super.context = context;
+ }
+ }
+
+ /**
+ * <p>
+ * Helper class that mocks a {@code WebServiceContext}. It is used in the JBoss STS test cases.
+ * </p>
+ *
+ * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
+ */
+ class TestContext implements WebServiceContext
+ {
+
+ private Principal principal;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.ws.WebServiceContext#getEndpointReference(java.lang.Class, org.w3c.dom.Element[])
+ */
+ public <T extends EndpointReference> T getEndpointReference(Class<T> arg0, Element... arg1)
+ {
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.ws.WebServiceContext#getEndpointReference(org.w3c.dom.Element[])
+ */
+ public EndpointReference getEndpointReference(Element... arg0)
+ {
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.ws.WebServiceContext#getMessageContext()
+ */
+ public MessageContext getMessageContext()
+ {
+ return null;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.ws.WebServiceContext#getUserPrincipal()
+ */
+ public Principal getUserPrincipal()
+ {
+ return this.principal;
+ }
+
+ /**
+ * <p>
+ * Sets the principal to be used in the test case.
+ * </p>
+ *
+ * @param principal
+ * the {@code Principal} to be set.
+ */
+ public void setUserPrincipal(Principal principal)
+ {
+ this.principal = principal;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see javax.xml.ws.WebServiceContext#isUserInRole(java.lang.String)
+ */
+ public boolean isUserInRole(String arg0)
+ {
+ return false;
+ }
+ }
+}
Deleted: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/MockSTSConfiguration.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/MockSTSConfiguration.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/MockSTSConfiguration.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,151 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2009, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.test.identity.federation.core.wstrust;
-
-import java.security.KeyPair;
-import java.security.PublicKey;
-
-import org.jboss.identity.federation.core.wstrust.STSConfiguration;
-import org.jboss.identity.federation.core.wstrust.SecurityTokenProvider;
-import org.jboss.identity.federation.core.wstrust.WSTrustRequestHandler;
-
-/**
- * <p>
- * Mock implementation of {@code STSConfiguration} used in the test scenarios.
- * </p>
- *
- * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
- * @version $Revision: 631 $
- */
-public class MockSTSConfiguration implements STSConfiguration
-{
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getEncryptIssuedToken()
- */
- public boolean encryptIssuedToken()
- {
- return false;
- }
-
- /*
- * (non-Javadoc)
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#signIssuedToken()
- */
- public boolean signIssuedToken()
- {
- return true;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getIssuedTokenTimeout()
- */
- public long getIssuedTokenTimeout()
- {
- return 0;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getProviderForService(java.lang.String)
- */
- public SecurityTokenProvider getProviderForService(String serviceName)
- {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getProviderForTokenType(java.lang.String)
- */
- public SecurityTokenProvider getProviderForTokenType(String tokenType)
- {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getProviderForTokenElementNS(java.lang.String, java.lang.String)
- */
- public SecurityTokenProvider getProviderForTokenElementNS(String tokenLocalName, String tokenNamespace)
- {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getTokenTypeForService(java.lang.String)
- */
- public String getTokenTypeForService(String serviceName)
- {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getRequestHandler()
- */
- public WSTrustRequestHandler getRequestHandler()
- {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getSTSName()
- */
- public String getSTSName()
- {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getServiceProviderPublicKey(java.lang.String)
- */
- public PublicKey getServiceProviderPublicKey(String serviceName)
- {
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.jboss.identity.federation.core.wstrust.STSConfiguration#getSTSKeyPair()
- */
- public KeyPair getSTSKeyPair()
- {
- return null;
- }
-
-}
Modified: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SAML20TokenProviderUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SAML20TokenProviderUnitTestCase.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SAML20TokenProviderUnitTestCase.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -24,7 +24,6 @@
import java.io.InputStream;
import java.net.URI;
import java.security.KeyStore;
-import java.security.Principal;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.util.Arrays;
@@ -358,38 +357,4 @@
Certificate certificate = keyStore.getCertificate(certificateAlias);
return certificate;
}
-
- /**
- * <p>
- * Simple {@code Principal} implementation used in the test scenarios.
- * </p>
- *
- * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
- */
- private class TestPrincipal implements Principal
- {
- private final String name;
-
- /**
- * <p>
- * Creates an instance of {@code TestPrincipal} with the specified name.
- * </p>
- *
- * @param name a {@code String} representing the principal name.
- */
- public TestPrincipal(String name)
- {
- this.name = name;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.security.Principal#getName()
- */
- public String getName()
- {
- return this.name;
- }
- }
}
Modified: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SpecialTokenProvider.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SpecialTokenProvider.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SpecialTokenProvider.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -21,11 +21,21 @@
*/
package org.jboss.test.identity.federation.core.wstrust;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.util.Map;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.jboss.identity.federation.core.saml.v2.common.IDGenerator;
+import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
+import org.jboss.identity.federation.core.wstrust.SecurityToken;
import org.jboss.identity.federation.core.wstrust.SecurityTokenProvider;
+import org.jboss.identity.federation.core.wstrust.StandardSecurityToken;
import org.jboss.identity.federation.core.wstrust.WSTrustException;
import org.jboss.identity.federation.core.wstrust.WSTrustRequestContext;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
/**
* <p>
@@ -36,7 +46,9 @@
*/
public class SpecialTokenProvider implements SecurityTokenProvider
{
-
+
+ private Map<String, String> properties;
+
/*
* (non-Javadoc)
*
@@ -44,8 +56,9 @@
*/
public void initialize(Map<String, String> properties)
{
+ this.properties = properties;
}
-
+
/*
* (non-Javadoc)
*
@@ -62,6 +75,40 @@
*/
public void issueToken(WSTrustRequestContext context) throws WSTrustException
{
+ // create a simple sample token using the info from the request.
+ String caller = context.getCallerPrincipal() == null ? "anonymous" : context.getCallerPrincipal().getName();
+ URI tokenType = context.getRequestSecurityToken().getTokenType();
+ if (tokenType == null)
+ {
+ try
+ {
+ tokenType = new URI("http://www.tokens.org/SpecialToken");
+ }
+ catch (URISyntaxException ignore)
+ {
+ }
+ }
+
+ // we will use DOM to create the token.
+ try
+ {
+ Document doc = DocumentUtil.createDocument();
+
+ String namespaceURI = "http://www.tokens.org";
+ Element root = doc.createElementNS(namespaceURI, "token:SpecialToken");
+ root.appendChild(doc.createTextNode("Principal:" + caller));
+ String id = IDGenerator.create("ID_");
+ root.setAttributeNS(namespaceURI, "ID", id);
+ root.setAttributeNS(namespaceURI, "TokenType", tokenType.toString());
+ doc.appendChild(root);
+
+ SecurityToken token = new StandardSecurityToken(tokenType.toString(), root, id);
+ context.setSecurityToken(token);
+ }
+ catch (ParserConfigurationException pce)
+ {
+ pce.printStackTrace();
+ }
}
/*
@@ -81,5 +128,16 @@
public void validateToken(WSTrustRequestContext context) throws WSTrustException
{
}
-
+
+ /**
+ * <p>
+ * Just returns a reference to the properties that have been configured for testing purposes.
+ * </p>
+ *
+ * @return a reference to the properties map.
+ */
+ public Map<String, String> getProperties()
+ {
+ return this.properties;
+ }
}
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/TestPrincipal.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/TestPrincipal.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/TestPrincipal.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,59 @@
+/*
+ * JBoss, Home of Professional Open Source.
+
+ * Copyright 2009, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.identity.federation.core.wstrust;
+
+import java.security.Principal;
+
+/**
+ * <p>
+ * Simple {@code Principal} implementation used in the test scenarios.
+ * </p>
+ *
+ * @author <a href="mailto:sguilhen@redhat.com">Stefan Guilhen</a>
+ */
+public class TestPrincipal implements Principal
+{
+ private final String name;
+
+ /**
+ * <p>
+ * Creates an instance of {@code TestPrincipal} with the specified name.
+ * </p>
+ *
+ * @param name a {@code String} representing the principal name.
+ */
+ public TestPrincipal(String name)
+ {
+ this.name = name;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.security.Principal#getName()
+ */
+ public String getName()
+ {
+ return this.name;
+ }
+}
Modified: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/WSTrustServiceFactoryUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/WSTrustServiceFactoryUnitTestCase.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/WSTrustServiceFactoryUnitTestCase.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -25,6 +25,7 @@
import junit.framework.TestCase;
+import org.jboss.identity.federation.core.wstrust.JBossSTSConfiguration;
import org.jboss.identity.federation.core.wstrust.STSConfiguration;
import org.jboss.identity.federation.core.wstrust.SecurityTokenProvider;
import org.jboss.identity.federation.core.wstrust.StandardRequestHandler;
@@ -51,7 +52,7 @@
*/
public void testCreateRequestHandler() throws Exception
{
- STSConfiguration config = new MockSTSConfiguration();
+ STSConfiguration config = new JBossSTSConfiguration();
WSTrustServiceFactory factory = WSTrustServiceFactory.getInstance();
// tests the creation of the request handler.
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/jboss-sts.xml
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/resources/jboss-sts.xml (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/resources/jboss-sts.xml 2009-09-24 01:24:30 UTC (rev 808)
@@ -0,0 +1,31 @@
+<JBossSTS xmlns="urn:jboss:identity-federation:config:1.0"
+ STSName="Test STS" TokenTimeout="7200" EncryptToken="true">
+ <KeyProvider ClassName="org.jboss.identity.federation.core.impl.KeyStoreKeyManager">
+ <Auth Key="KeyStoreURL" Value="keystore/sts_keystore.jks"/>
+ <Auth Key="KeyStorePass" Value="testpass"/>
+ <Auth Key="SigningKeyAlias" Value="sts"/>
+ <Auth Key="SigningKeyPass" Value="keypass"/>
+ <ValidatingAlias Key="http://services.testcorp.org/provider1" Value="service1"/>
+ <ValidatingAlias Key="http://services.testcorp.org/provider2" Value="service2"/>
+ </KeyProvider>
+ <RequestHandler>org.jboss.identity.federation.core.wstrust.StandardRequestHandler</RequestHandler>
+ <TokenProviders>
+ <TokenProvider ProviderClass="org.jboss.test.identity.federation.core.wstrust.SpecialTokenProvider"
+ TokenType="http://www.tokens.org/SpecialToken"
+ TokenElement="SpecialToken"
+ TokenElementNS="http://www.tokens.org">
+ <Property Name="Property1" Value="Value1"/>
+ <Property Name="Property2" Value="Value2"/>
+ </TokenProvider>
+ <TokenProvider ProviderClass="org.jboss.identity.federation.core.wstrust.plugins.saml.SAML20TokenProvider"
+ TokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
+ TokenElement="Assertion"
+ TokenElementNS="urn:oasis:names:tc:SAML:2.0:assertion"/>
+ </TokenProviders>
+ <ServiceProviders>
+ <ServiceProvider Endpoint="http://services.testcorp.org/provider1" TokenType="http://www.tokens.org/SpecialToken"
+ TruststoreAlias="service1"/>
+ <ServiceProvider Endpoint="http://services.testcorp.org/provider2" TokenType="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
+ TruststoreAlias="service2"/>
+ </ServiceProviders>
+</JBossSTS>
\ No newline at end of file
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/keystore/jbid_test_keystore.jks
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/keystore/jbid_test_keystore.jks
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Modified: identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/filters/SPFilter.java
===================================================================
--- identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/filters/SPFilter.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/filters/SPFilter.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -58,6 +58,9 @@
import org.jboss.identity.federation.core.config.TrustType;
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.exceptions.ParsingException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyConfigurationException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.core.saml.v2.common.IDGenerator;
import org.jboss.identity.federation.core.saml.v2.common.SAMLDocumentHolder;
import org.jboss.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
@@ -76,9 +79,6 @@
import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
import org.jboss.identity.federation.saml.v2.protocol.StatusType;
import org.jboss.identity.federation.web.interfaces.IRoleValidator;
-import org.jboss.identity.federation.web.interfaces.TrustKeyConfigurationException;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
-import org.jboss.identity.federation.web.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.web.roles.DefaultRoleValidator;
import org.jboss.identity.federation.web.util.ConfigurationUtil;
import org.jboss.identity.federation.web.util.PostBindingUtil;
Deleted: identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyConfigurationException.java
===================================================================
--- identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyConfigurationException.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyConfigurationException.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,54 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.identity.federation.web.interfaces;
-
-import org.jboss.identity.federation.core.exceptions.ConfigurationException;
-
-/**
- * ConfigurationException in the TrustKeyManager
- * @author Anil.Saldhana(a)redhat.com
- * @since May 22, 2009
- */
-public class TrustKeyConfigurationException extends ConfigurationException
-{
- private static final long serialVersionUID = 1L;
-
- public TrustKeyConfigurationException()
- {
- super();
- }
-
- public TrustKeyConfigurationException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- public TrustKeyConfigurationException(String message)
- {
- super(message);
- }
-
- public TrustKeyConfigurationException(Throwable cause)
- {
- super(cause);
- }
-}
\ No newline at end of file
Deleted: identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyManager.java
===================================================================
--- identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyManager.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyManager.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,117 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.identity.federation.web.interfaces;
-
-import java.security.KeyPair;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.cert.Certificate;
-import java.util.List;
-
-import javax.crypto.SecretKey;
-
-import org.jboss.identity.federation.core.config.AuthPropertyType;
-import org.jboss.identity.federation.core.config.KeyValueType;
-
-
-/**
- * Key Manager interface used in trust decisions
- * @author Anil.Saldhana(a)redhat.com
- * @since Jan 22, 2009
- */
-public interface TrustKeyManager
-{
- /**
- * Provide a set of properties used for authentication
- * into the storage of keys - keystore, ldap, db, HSM etc
- * @param authList
- * @throws {@link IOException}
- */
- void setAuthProperties(List<AuthPropertyType> authList)
- throws TrustKeyConfigurationException, TrustKeyProcessingException;
-
- /**
- * Set a list of (domain,alias) tuple to trust domains
- * The alias is a string that represents the validating key stored
- * for a domain
- * @param aliases
- * @throws {@link IOException}
- */
- void setValidatingAlias(List<KeyValueType> aliases)
- throws TrustKeyConfigurationException, TrustKeyProcessingException;
-
- /**
- * Get the Signing Key
- * @return
- * @throws {@link CertificateException}
- */
- PrivateKey getSigningKey()
- throws TrustKeyConfigurationException, TrustKeyProcessingException;
-
- /**
- * <p>
- * Constructs a {@code KeyPair} instance containing the signing key ({@code PrivateKey}) and associated
- * {@code PublicKey}.
- * </p>
- *
- * @return the constructed {@code KeyPair} object.
- */
- KeyPair getSigningKeyPair()
- throws TrustKeyConfigurationException, TrustKeyProcessingException;
-
- /**
- * Get the certificate given an alias
- * @param alias
- * @return
- * @throws {@link CertificateException}
- */
- Certificate getCertificate(String alias)
- throws TrustKeyConfigurationException, TrustKeyProcessingException;
-
- /**
- * Get a Public Key given an alias
- * @param alias
- * @return
- * @throws {@link CertificateException}
- */
- PublicKey getPublicKey(String alias)
- throws TrustKeyConfigurationException, TrustKeyProcessingException;
-
- /**
- * Given a domain, obtain a secret key
- * @see {@code EncryptionKeyUtil}
- * @param domain
- * @param encryptionAlgorithm Encryption Algorithm
- * @param keyLength length of keys
- * @return
- */
- SecretKey getEncryptionKey(String domain, String encryptionAlgorithm, int keyLength)
- throws TrustKeyConfigurationException, TrustKeyProcessingException;
-
- /**
- * Get the Validating Public Key of the domain
- * @param domain
- * @return
- */
- PublicKey getValidatingKey(String domain)
- throws TrustKeyConfigurationException, TrustKeyProcessingException;
-}
\ No newline at end of file
Deleted: identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyProcessingException.java
===================================================================
--- identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyProcessingException.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/interfaces/TrustKeyProcessingException.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,54 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.identity.federation.web.interfaces;
-
-import org.jboss.identity.federation.core.exceptions.ProcessingException;
-
-/**
- * Processing Exception in the trust key manager
- * @author Anil.Saldhana(a)redhat.com
- * @since May 22, 2009
- */
-public class TrustKeyProcessingException extends ProcessingException
-{
- private static final long serialVersionUID = 1L;
-
- public TrustKeyProcessingException()
- {
- super();
- }
-
- public TrustKeyProcessingException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- public TrustKeyProcessingException(String message)
- {
- super(message);
- }
-
- public TrustKeyProcessingException(Throwable cause)
- {
- super(cause);
- }
-}
\ No newline at end of file
Modified: identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/servlets/IDPServlet.java
===================================================================
--- identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/servlets/IDPServlet.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/servlets/IDPServlet.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -45,15 +45,15 @@
import org.jboss.identity.federation.core.exceptions.ParsingException;
import org.jboss.identity.federation.core.impl.DelegatedAttributeManager;
import org.jboss.identity.federation.core.interfaces.AttributeManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyConfigurationException;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssueInstantMissingException;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssuerNotTrustedException;
import org.jboss.identity.federation.saml.v2.protocol.AuthnRequestType;
import org.jboss.identity.federation.saml.v2.protocol.RequestAbstractType;
import org.jboss.identity.federation.web.interfaces.RoleGenerator;
-import org.jboss.identity.federation.web.interfaces.TrustKeyConfigurationException;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
-import org.jboss.identity.federation.web.interfaces.TrustKeyProcessingException;
import org.jboss.identity.federation.web.roles.DefaultRoleGenerator;
import org.jboss.identity.federation.web.util.ConfigurationUtil;
import org.jboss.identity.federation.web.util.IDPWebRequestUtil;
Modified: identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/util/IDPWebRequestUtil.java
===================================================================
--- identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/util/IDPWebRequestUtil.java 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-web/src/main/java/org/jboss/identity/federation/web/util/IDPWebRequestUtil.java 2009-09-24 01:24:30 UTC (rev 808)
@@ -48,6 +48,7 @@
import org.jboss.identity.federation.core.exceptions.ConfigurationException;
import org.jboss.identity.federation.core.exceptions.ParsingException;
import org.jboss.identity.federation.core.interfaces.AttributeManager;
+import org.jboss.identity.federation.core.interfaces.TrustKeyManager;
import org.jboss.identity.federation.core.saml.v2.common.IDGenerator;
import org.jboss.identity.federation.core.saml.v2.constants.JBossSAMLURIConstants;
import org.jboss.identity.federation.core.saml.v2.exceptions.IssueInstantMissingException;
@@ -62,7 +63,6 @@
import org.jboss.identity.federation.saml.v2.assertion.AttributeStatementType;
import org.jboss.identity.federation.saml.v2.protocol.RequestAbstractType;
import org.jboss.identity.federation.saml.v2.protocol.ResponseType;
-import org.jboss.identity.federation.web.interfaces.TrustKeyManager;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
Modified: identity-federation/trunk/jboss-identity-webapps/jboss-sts/src/main/resources/jboss-sts.xml
===================================================================
--- identity-federation/trunk/jboss-identity-webapps/jboss-sts/src/main/resources/jboss-sts.xml 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-webapps/jboss-sts/src/main/resources/jboss-sts.xml 2009-09-24 01:24:30 UTC (rev 808)
@@ -1,6 +1,6 @@
<JBossSTS xmlns="urn:jboss:identity-federation:config:1.0"
STSName="JBossSTS" TokenTimeout="7200" EncryptToken="true">
- <KeyProvider ClassName="org.jboss.identity.federation.bindings.tomcat.KeyStoreKeyManager">
+ <KeyProvider ClassName="org.jboss.identity.federation.core.impl.KeyStoreKeyManager">
<Auth Key="KeyStoreURL" Value="sts_keystore.jks"/>
<Auth Key="KeyStorePass" Value="testpass"/>
<Auth Key="SigningKeyAlias" Value="sts"/>
Modified: identity-federation/trunk/jboss-identity-webapps/jboss-sts/src/main/webapp/WEB-INF/web.xml
===================================================================
--- identity-federation/trunk/jboss-identity-webapps/jboss-sts/src/main/webapp/WEB-INF/web.xml 2009-09-23 23:08:09 UTC (rev 807)
+++ identity-federation/trunk/jboss-identity-webapps/jboss-sts/src/main/webapp/WEB-INF/web.xml 2009-09-24 01:24:30 UTC (rev 808)
@@ -6,7 +6,7 @@
<web-app>
<servlet>
<servlet-name>JBossSTS</servlet-name>
- <servlet-class>org.jboss.identity.federation.bindings.jboss.wstrust.JBossSTS</servlet-class>
+ <servlet-class>org.jboss.identity.federation.core.wstrust.JBossSTS</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JBossSTS</servlet-name>
14 years, 7 months
JBoss Identity SVN: r807 - in identity-federation/trunk: jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/factories and 7 other directories.
by jboss-identity-commits@lists.jboss.org
Author: sguilhen(a)redhat.com
Date: 2009-09-23 19:08:09 -0400 (Wed, 23 Sep 2009)
New Revision: 807
Added:
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/serializer.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xalan.jar
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/keystore/
identity-federation/trunk/jboss-identity-fed-core/src/test/resources/keystore/sts_keystore.jks
Modified:
identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/wstrust/JBossSTSUnitTestCase.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/factories/SAMLAssertionFactory.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/StandardRequestHandler.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/WSTrustRequestContext.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/WSTrustUtil.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAML20TokenProvider.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAMLUtil.java
identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/wrappers/RequestSecurityToken.java
identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SAML20TokenProviderUnitTestCase.java
Log:
JBID-138: StandardRequestHandler now sets the proof token in a KeyInfoType object and then sets this KeyInfoType in the request context. SAML20TokenProvider gets the KeyInfo from the context and sets it in the SubjectConfirmation, as required by the SAML token profile. Tests have been updated.
Modified: identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/wstrust/JBossSTSUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/wstrust/JBossSTSUnitTestCase.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-bindings/src/test/java/org/jboss/test/identity/federation/bindings/wstrust/JBossSTSUnitTestCase.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -294,7 +294,7 @@
.parseRequestSecurityTokenResponse(responseMessage);
// validate the security token response.
- this.validateSAMLAssertionResponse(baseResponse);
+ this.validateSAMLAssertionResponse(baseResponse, SAMLUtil.SAML2_BEARER_URI);
}
/**
@@ -351,7 +351,7 @@
.parseRequestSecurityTokenResponse(responseMessage);
// validate the security token response.
- AssertionType assertion = this.validateSAMLAssertionResponse(baseResponse);
+ AssertionType assertion = this.validateSAMLAssertionResponse(baseResponse, SAMLUtil.SAML2_BEARER_URI);
// in this scenario, the conditions section should have an audience restriction.
ConditionsType conditions = assertion.getConditions();
@@ -379,7 +379,7 @@
public void testInvokeSAML20WithProofToken() throws Exception
{
// create a simple token request, asking for a SAMLv2.0 token.
- RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST,
+ RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST,
SAMLUtil.SAML2_TOKEN_TYPE, null);
// add a symmetric key type to the request, but don't supply any client key - STS should generate one.
@@ -395,7 +395,7 @@
.parseRequestSecurityTokenResponse(responseMessage);
// validate the security token response.
- this.validateSAMLAssertionResponse(baseResponse);
+ this.validateSAMLAssertionResponse(baseResponse, SAMLUtil.SAML2_BEARER_URI);
// check if the response contains the STS-generated key.
RequestSecurityTokenResponseCollection collection = (RequestSecurityTokenResponseCollection) baseResponse;
@@ -427,7 +427,7 @@
baseResponse = WSTrustJAXBFactory.getInstance().parseRequestSecurityTokenResponse(responseMessage);
// validate the security token response.
- this.validateSAMLAssertionResponse(baseResponse);
+ this.validateSAMLAssertionResponse(baseResponse, SAMLUtil.SAML2_BEARER_URI);
collection = (RequestSecurityTokenResponseCollection) baseResponse;
response = collection.getRequestSecurityTokenResponses().get(0);
@@ -607,7 +607,8 @@
* @throws Exception
* if one of the validation performed fail.
*/
- private AssertionType validateSAMLAssertionResponse(BaseRequestSecurityTokenResponse baseResponse) throws Exception
+ private AssertionType validateSAMLAssertionResponse(BaseRequestSecurityTokenResponse baseResponse,
+ String confirmationMethod) throws Exception
{
// =============================== WS-Trust Security Token Response Validation ===============================//
@@ -667,8 +668,14 @@
assertEquals("Unexpected name id value", "sguilhen", nameID.getValue());
assertEquals("Unexpected type found", SubjectConfirmationType.class, content.get(1).getDeclaredType());
SubjectConfirmationType subjType = (SubjectConfirmationType) content.get(1).getValue();
- assertEquals("Unexpected confirmation method", SAMLUtil.SAML2_BEARER_URI, subjType.getMethod());
+ assertEquals("Unexpected confirmation method", confirmationMethod, subjType.getMethod());
+ // if confirmation method is holder of key, make sure the assertion contains a KeyInfo with the proof token.
+ if(SAMLUtil.SAML2_HOLDER_OF_KEY_URI.equals(confirmationMethod))
+ {
+
+ }
+
// validate the assertion conditions.
assertNotNull("Unexpected null conditions", assertion.getConditions());
assertEquals(lifetime.getCreated(), assertion.getConditions().getNotBefore());
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/factories/SAMLAssertionFactory.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/factories/SAMLAssertionFactory.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/saml/v2/factories/SAMLAssertionFactory.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -37,6 +37,7 @@
import org.jboss.identity.federation.saml.v2.assertion.StatementAbstractType;
import org.jboss.identity.federation.saml.v2.assertion.SubjectConfirmationType;
import org.jboss.identity.federation.saml.v2.assertion.SubjectType;
+import org.jboss.identity.xmlsec.w3.xmldsig.KeyInfoType;
/**
* Get the SAML Assertion Object Factory
@@ -111,6 +112,21 @@
/**
* <p>
+ * Creates a {@code KeyInfoConfirmationDataType} with the specified {@code KeyInfoType}.
+ * </p>
+ *
+ * @param keyInfo the {@code KeyInfoType} object that wraps the proof-of-possession token.
+ * @return the constructed {@code KeyInfoConfirmationDataType} instance.
+ */
+ public static KeyInfoConfirmationDataType createKeyInfoConfirmation(KeyInfoType keyInfo)
+ {
+ KeyInfoConfirmationDataType type = getObjectFactory().createKeyInfoConfirmationDataType();
+ type.getContent().add(new org.jboss.identity.xmlsec.w3.xmldsig.ObjectFactory().createKeyInfo(keyInfo));
+ return type;
+ }
+
+ /**
+ * <p>
* Creates a {@code SubjectConfirmationType} object with the specified values.
* </p>
*
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/StandardRequestHandler.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/StandardRequestHandler.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/StandardRequestHandler.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -22,13 +22,11 @@
package org.jboss.identity.federation.core.wstrust;
import java.net.URI;
-import java.security.InvalidKeyException;
import java.security.KeyPair;
-import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PublicKey;
+import java.security.cert.Certificate;
-import javax.xml.bind.JAXBElement;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.SignatureMethod;
@@ -141,6 +139,9 @@
keySize = KEY_SIZE;
request.setKeySize(keySize);
}
+
+ // get the key wrap algorithm.
+ URI keyWrapAlgo = request.getKeyWrapAlgorithm();
// create proof-of-possession token and server entropy (if needed).
RequestedProofTokenType requestedProofToken = null;
@@ -148,9 +149,10 @@
if (WSTrustConstants.KEY_TYPE_SYMMETRIC.equalsIgnoreCase(keyType.toString()))
{
+ // symmetric key case: if client entropy is found, compute a key. If not, generate a new key.
requestedProofToken = new RequestedProofTokenType();
ObjectFactory objFactory = new ObjectFactory();
- // symmetric key case: if client entropy is found, compute a key. If not, generate a new key.
+
byte[] clientSecret = null;
EntropyType clientEntropy = request.getEntropy();
if (clientEntropy != null)
@@ -167,26 +169,32 @@
{
// client secret has been specified - combine it with the sts secret.
requestedProofToken.setAny(objFactory.createComputedKey(WSTrustConstants.CK_PSHA1));
+ byte[] combinedSecret = null;
try
{
- byte[] combinedSecret = WSTrustUtil.P_SHA1(clientSecret, serverSecret, (int) keySize / 8);
- requestContext.setProofToken(combinedSecret);
+ combinedSecret = WSTrustUtil.P_SHA1(clientSecret, serverSecret, (int) keySize / 8);
}
catch (Exception e)
{
throw new WSTrustException("Error generating combined secret key", e);
}
+ requestContext.setProofTokenInfo(WSTrustUtil.createKeyInfo(combinedSecret, providerPublicKey, keyWrapAlgo));
}
else
{
// client secret has not been specified - use the sts secret only.
requestedProofToken.setAny(objFactory.createBinarySecret(serverBinarySecret));
- requestContext.setProofToken(serverSecret);
+ requestContext.setProofTokenInfo(WSTrustUtil.createKeyInfo(serverSecret, providerPublicKey, keyWrapAlgo));
}
}
else if (WSTrustConstants.KEY_TYPE_PUBLIC.equalsIgnoreCase(keyType.toString()))
{
- // TODO: implement public key case.
+ // TODO: get the client certificate from a metadata provider or from the UseKey section of the WS-T request.
+ Certificate certificate = null;
+ if(certificate != null)
+ requestContext.setProofTokenInfo(WSTrustUtil.createKeyInfo(certificate));
+ else
+ throw new WSTrustException("Unable to locate client public key");
}
// issue the security token using the constructed context.
@@ -458,4 +466,5 @@
return rstrDocument;
}
+
}
\ No newline at end of file
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/WSTrustRequestContext.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/WSTrustRequestContext.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/WSTrustRequestContext.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -27,6 +27,7 @@
import org.jboss.identity.federation.core.wstrust.wrappers.RequestSecurityToken;
import org.jboss.identity.federation.ws.trust.RequestedReferenceType;
import org.jboss.identity.federation.ws.trust.StatusType;
+import org.jboss.identity.xmlsec.w3.xmldsig.KeyInfoType;
/**
* <p>
@@ -49,7 +50,7 @@
private final RequestSecurityToken request;
- private Object proofToken;
+ private KeyInfoType proofTokenInfo;
// information supplied by the token provider.
private SecurityToken securityToken;
@@ -149,26 +150,26 @@
/**
* <p>
- * Obtains the proof-of-possession token.
+ * Obtains the {@code KeyInfoType} that contains the proof-of-possession token.
* </p>
*
- * @return an {@code Object} representing the proof-of-possession token.
+ * @return a reference to the {@code KeyInfoType} that wraps the proof-of-possession token.
*/
- public Object getProofToken()
+ public KeyInfoType getProofTokenInfo()
{
- return this.proofToken;
+ return this.proofTokenInfo;
}
/**
* <p>
- * Sets the proof-of-possession token in the request context.
+ * Sets the {@code KeyInfoType} that contains the proof-of-possession token.
* </p>
*
- * @param proofToken an {@code Object} representing the proof-of-possession token.
+ * @param proofTokenInfo a reference to the {@code KeyInfoType} that wraps the proof-of-possession token.
*/
- public void setProofToken(Object proofToken)
+ public void setProofTokenInfo(KeyInfoType proofTokenInfo)
{
- this.proofToken = proofToken;
+ this.proofTokenInfo = proofTokenInfo;
}
/**
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/WSTrustUtil.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/WSTrustUtil.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/WSTrustUtil.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -21,9 +21,12 @@
*/
package org.jboss.identity.federation.core.wstrust;
+import java.net.URI;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
+import java.security.PublicKey;
import java.security.SecureRandom;
+import java.security.cert.Certificate;
import java.util.GregorianCalendar;
import java.util.Map;
@@ -32,6 +35,10 @@
import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
+import org.apache.xml.security.encryption.EncryptedKey;
+import org.apache.xml.security.encryption.XMLCipher;
+import org.jboss.identity.federation.core.saml.v2.util.DocumentUtil;
+import org.jboss.identity.federation.core.util.XMLEncryptionUtil;
import org.jboss.identity.federation.core.wstrust.wrappers.Lifetime;
import org.jboss.identity.federation.ws.addressing.AttributedURIType;
import org.jboss.identity.federation.ws.addressing.EndpointReferenceType;
@@ -42,6 +49,10 @@
import org.jboss.identity.federation.ws.trust.RequestedReferenceType;
import org.jboss.identity.federation.ws.wss.secext.KeyIdentifierType;
import org.jboss.identity.federation.ws.wss.secext.SecurityTokenReferenceType;
+import org.jboss.identity.xmlsec.w3.xmldsig.KeyInfoType;
+import org.jboss.identity.xmlsec.w3.xmldsig.X509DataType;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
/**
* <p>
@@ -202,7 +213,7 @@
random.nextBytes(secret);
return secret;
}
-
+
/**
* <p>
* This method implements the {@code P_SHA-1} function as defined in the <i>RFC 2246 - The TLS Protocol Version 1.0
@@ -263,4 +274,79 @@
return result;
}
+ /**
+ * <p>
+ * Creates a {@code KeyInfoType} that wraps the specified secret. If the {@code encryptionKey} parameter is not
+ * null, the secret is encrypted using the specified public key before it is set in the {@code KeyInfoType}.
+ * </p>
+ *
+ * @param secret a {@code byte[]} representing the secret (symmetric key).
+ * @param encryptionKey the {@code PublicKey} that must be used to encrypt the secret.
+ * @param keyWrapAlgo the key wrap algorithm to be used.
+ * @return the constructed {@code KeyInfoType} instance.
+ * @throws WSTrustException if an error occurs while creating the {@code KeyInfoType} object.
+ */
+ public static KeyInfoType createKeyInfo(byte[] secret, PublicKey encryptionKey, URI keyWrapAlgo)
+ throws WSTrustException
+ {
+ KeyInfoType keyInfo = null;
+
+ // if a public key has been specified, encrypt the secret using the public key.
+ if (encryptionKey != null)
+ {
+ try
+ {
+ Document document = DocumentUtil.createDocument();
+ // TODO: XMLEncryptionUtil should allow for the specification of the key wrap algorithm.
+ EncryptedKey key = XMLEncryptionUtil.encryptKey(document, new SecretKeySpec(secret, "AES"), encryptionKey,
+ secret.length);
+ Element encryptedKeyElement = XMLCipher.getInstance().martial(key);
+ keyInfo = new KeyInfoType();
+ keyInfo.getContent().add(encryptedKeyElement);
+ }
+ catch (Exception e)
+ {
+ throw new WSTrustException("Error creating KeyInfoType", e);
+ }
+ }
+ else
+ {
+ // TODO: log a warn message or throw an exception to inform client that the secret could not be encrypted.
+ }
+ return keyInfo;
+ }
+
+ /**
+ * <p>
+ * Creates a {@code KeyInfoType} that wraps the specified certificate.
+ * </p>
+ *
+ * @param certificate the {@code Certificate} to be wrapped as a {@code X509DataType} inside the {@code KeyInfoType}.
+ * @return the constructed {@code KeyInfoType} object.
+ * @throws WSTrustException if an error occurs while creating the {@code KeyInfoType}.
+ */
+ public static KeyInfoType createKeyInfo(Certificate certificate) throws WSTrustException
+ {
+ KeyInfoType keyInfo = null;
+ try
+ {
+ // TODO: check if we need to store the certificate using a base64 format.
+ byte[] encodedCert = certificate.getEncoded();
+
+ // first create a X509DataType that contains the encoded certificate.
+ org.jboss.identity.xmlsec.w3.xmldsig.ObjectFactory factory = new org.jboss.identity.xmlsec.w3.xmldsig.ObjectFactory();
+ X509DataType dataType = factory.createX509DataType();
+ dataType.getX509IssuerSerialOrX509SKIOrX509SubjectName().add(
+ factory.createX509DataTypeX509Certificate(encodedCert));
+
+ // set the X509DataType in the KeyInfoType.
+ keyInfo = new KeyInfoType();
+ keyInfo.getContent().add(factory.createX509Data(dataType));
+ }
+ catch (Exception e)
+ {
+ throw new WSTrustException("Error creating KeyInfoType", e);
+ }
+ return keyInfo;
+ }
}
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAML20TokenProvider.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAML20TokenProvider.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAML20TokenProvider.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -43,6 +43,7 @@
import org.jboss.identity.federation.saml.v2.assertion.AssertionType;
import org.jboss.identity.federation.saml.v2.assertion.AudienceRestrictionType;
import org.jboss.identity.federation.saml.v2.assertion.ConditionsType;
+import org.jboss.identity.federation.saml.v2.assertion.KeyInfoConfirmationDataType;
import org.jboss.identity.federation.saml.v2.assertion.NameIDType;
import org.jboss.identity.federation.saml.v2.assertion.SubjectConfirmationType;
import org.jboss.identity.federation.saml.v2.assertion.SubjectType;
@@ -211,10 +212,20 @@
ConditionsType conditions = SAMLAssertionFactory.createConditions(lifetime.getCreated(), lifetime.getExpires(),
restriction);
- // TODO: implement support for the other confirmation methods.
- String confirmationMethod = SAMLUtil.SAML2_BEARER_URI;
+ String confirmationMethod = null;
+ KeyInfoConfirmationDataType keyInfoDataType = null;
+ // if there is a proof-of-possession token in the context, we have the holder of key confirmation method.
+ if (context.getProofTokenInfo() != null)
+ {
+ confirmationMethod = SAMLUtil.SAML2_HOLDER_OF_KEY_URI;
+ keyInfoDataType = SAMLAssertionFactory.createKeyInfoConfirmation(context.getProofTokenInfo());
+ }
+ else
+ confirmationMethod = SAMLUtil.SAML2_BEARER_URI;
+ // TODO: implement the SENDER_VOUCHES scenario.
+
SubjectConfirmationType subjectConfirmation = SAMLAssertionFactory.createSubjectConfirmation(null,
- confirmationMethod, null);
+ confirmationMethod, keyInfoDataType);
// create a subject using the caller principal.
Principal principal = context.getCallerPrincipal();
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAMLUtil.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAMLUtil.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/plugins/saml/SAMLUtil.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -47,6 +47,10 @@
public static final String SAML2_BEARER_URI = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
+ public static final String SAML2_HOLDER_OF_KEY_URI = "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key";
+
+ public static final String SAML2_SENDER_VOUCHES_URI = "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches";
+
public static final String SAML2_TOKEN_TYPE = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0";
public static final String SAML2_VALUE_TYPE = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID";
@@ -70,11 +74,11 @@
marshaller.marshal(new ObjectFactory().createAssertion(assertion), result);
// normalize the document to remove unused namespaces.
- DOMConfiguration docConfig = document.getDomConfig();
- docConfig.setParameter("namespaces", Boolean.TRUE);
- docConfig.setParameter("namespace-declarations", Boolean.FALSE);
- document.normalizeDocument();
-
+ // DOMConfiguration docConfig = document.getDomConfig();
+ // docConfig.setParameter("namespaces", Boolean.TRUE);
+ // docConfig.setParameter("namespace-declarations", Boolean.FALSE);
+ // document.normalizeDocument();
+
return document.getDocumentElement();
}
Modified: identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/wrappers/RequestSecurityToken.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/wrappers/RequestSecurityToken.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-fed-core/src/main/java/org/jboss/identity/federation/core/wstrust/wrappers/RequestSecurityToken.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -135,6 +135,8 @@
private URI canonicalizationAlgorithm;
+ private URI keyWrapAlgorithm;
+
private ProofEncryptionType proofEncryption;
private UseKeyType useKey;
@@ -236,6 +238,8 @@
this.encryptionAlgorithm = URI.create((String) element.getValue());
else if (localName.equalsIgnoreCase("CanonicalizationAlgorithm"))
this.canonicalizationAlgorithm = URI.create((String) element.getValue());
+ else if (localName.equalsIgnoreCase("KeyWrapAlgorithm"))
+ this.keyWrapAlgorithm = URI.create((String) element.getValue());
else if (localName.equalsIgnoreCase("ProofEncryption"))
this.proofEncryption = (ProofEncryptionType) element.getValue();
else if (localName.equalsIgnoreCase("UseKey"))
@@ -716,6 +720,30 @@
/**
* <p>
+ * Obtains the key wrap algorithm that has been set in the request.
+ * </p>
+ *
+ * @return a {@code URI} that represents the key wrap algorithm.
+ */
+ public URI getKeyWrapAlgorithm()
+ {
+ return this.keyWrapAlgorithm;
+ }
+
+ /**
+ * <p>
+ * Sets the key wrap algorithm in the request.
+ * </p>
+ *
+ * @param keyWrapAlgorithm a {@code URI} that represents the algorithm to be set.
+ */
+ public void setKeyWrapAlgorithm(URI keyWrapAlgorithm)
+ {
+ this.keyWrapAlgorithm = keyWrapAlgorithm;
+ }
+
+ /**
+ * <p>
* Obtains the {@code ProofEncryption} section of the request. The {@code ProofEncryption} indicates that the
* requester desires any returned secrets in issued security tokens to be encrypted.
* </p>
Modified: identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SAML20TokenProviderUnitTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SAML20TokenProviderUnitTestCase.java 2009-09-23 08:31:30 UTC (rev 806)
+++ identity-federation/trunk/jboss-identity-fed-core/src/test/java/org/jboss/test/identity/federation/core/wstrust/SAML20TokenProviderUnitTestCase.java 2009-09-23 23:08:09 UTC (rev 807)
@@ -21,9 +21,15 @@
*/
package org.jboss.test.identity.federation.core.wstrust;
+import java.io.InputStream;
import java.net.URI;
+import java.security.KeyStore;
import java.security.Principal;
+import java.security.PublicKey;
+import java.security.cert.Certificate;
+import java.util.Arrays;
import java.util.GregorianCalendar;
+import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
@@ -51,6 +57,9 @@
import org.jboss.identity.federation.ws.trust.ValidateTargetType;
import org.jboss.identity.federation.ws.wss.secext.KeyIdentifierType;
import org.jboss.identity.federation.ws.wss.secext.SecurityTokenReferenceType;
+import org.jboss.identity.xmlsec.w3.xmldsig.KeyInfoType;
+import org.jboss.identity.xmlsec.w3.xmldsig.X509DataType;
+import org.jboss.identity.xmlsec.w3.xmlenc.EncryptedKeyType;
import org.w3c.dom.Element;
/**
@@ -144,6 +153,96 @@
/**
* <p>
+ * This method tests the creation of SAMLV.20 assertions that contain a proof-of-possession token - that is,
+ * assertions that use the Holder Of Key confirmation method.
+ * </p>
+ *
+ * @throws Exception if an error occurs while running the test.
+ */
+ public void testIssueSAMLV20HolderOfKeyToken() throws Exception
+ {
+ // create a WSTrustRequestContext with a simple WS-Trust request.
+ RequestSecurityToken request = new RequestSecurityToken();
+ request.setLifetime(WSTrustUtil.createDefaultLifetime(3600000));
+ request.setAppliesTo(WSTrustUtil.createAppliesTo("http://services.testcorp.org/provider2"));
+ request.setTokenType(URI.create(SAMLUtil.SAML2_TOKEN_TYPE));
+
+ WSTrustRequestContext context = new WSTrustRequestContext(request, new TestPrincipal("sguilhen"));
+ context.setTokenIssuer("JBossSTS");
+
+ // let's set a symmetric key proof-of-possession token in the context.
+ byte[] secret = WSTrustUtil.createRandomSecret(32);
+ PublicKey serviceKey = this.getCertificate("keystore/sts_keystore.jks", "testpass", "service2").getPublicKey();
+ context.setProofTokenInfo(WSTrustUtil.createKeyInfo(secret, serviceKey, null));
+
+ // call the SAML token provider and check the generated token.
+ new SAML20TokenProvider().issueToken(context);
+ assertNotNull("Unexpected null security token", context.getSecurityToken());
+
+ // check if the assertion has a subject confirmation that contains the encrypted symmetric key.
+ AssertionType assertion = SAMLUtil.fromElement((Element) context.getSecurityToken().getTokenValue());
+ SubjectType subject = assertion.getSubject();
+ assertNotNull("Unexpected null subject", subject);
+ assertEquals("Unexpected subject content size", 2, subject.getContent().size());
+ JAXBElement<?> content = subject.getContent().get(0);
+ assertEquals("Unexpected content type", NameIDType.class, content.getDeclaredType());
+ NameIDType nameID = (NameIDType) content.getValue();
+ assertEquals("Unexpected name id qualifier", "urn:jboss:identity-federation", nameID.getNameQualifier());
+ assertEquals("Unexpected name id", "sguilhen", nameID.getValue());
+ content = subject.getContent().get(1);
+ assertEquals("Unexpected content type", SubjectConfirmationType.class, content.getDeclaredType());
+ SubjectConfirmationType confirmation = (SubjectConfirmationType) content.getValue();
+ assertEquals("Unexpected confirmation method", SAMLUtil.SAML2_HOLDER_OF_KEY_URI, confirmation.getMethod());
+ List<Object> confirmationContent = confirmation.getSubjectConfirmationData().getContent();
+ assertEquals("Unexpected subject confirmation content size", 1, confirmationContent.size());
+ JAXBElement<?> keyInfoElement = (JAXBElement<?>) confirmationContent.get(0);
+ assertEquals("Unexpected subject confirmation context type", KeyInfoType.class, keyInfoElement.getDeclaredType());
+ KeyInfoType keyInfo = (KeyInfoType) keyInfoElement.getValue();
+ assertEquals("Unexpected key info content size", 1, keyInfo.getContent().size());
+ JAXBElement<?> encKeyElement = (JAXBElement<?>) keyInfo.getContent().get(0);
+ assertEquals("Unexpected key info content type", EncryptedKeyType.class, encKeyElement.getDeclaredType());
+
+ // Now let's set an asymmetric proof of possession token in the context.
+ Certificate certificate = this.getCertificate("keystore/sts_keystore.jks", "testpass", "service1");
+ context.setProofTokenInfo(WSTrustUtil.createKeyInfo(certificate));
+
+ // call the SAML token provider and check the generated token.
+ new SAML20TokenProvider().issueToken(context);
+ assertNotNull("Unexpected null security token", context.getSecurityToken());
+
+ // check if the assertion has a subject confirmation that contains the encoded certificate.
+ assertion = SAMLUtil.fromElement((Element) context.getSecurityToken().getTokenValue());
+ subject = assertion.getSubject();
+ content = subject.getContent().get(0);
+ assertEquals("Unexpected content type", NameIDType.class, content.getDeclaredType());
+ nameID = (NameIDType) content.getValue();
+ assertEquals("Unexpected name id qualifier", "urn:jboss:identity-federation", nameID.getNameQualifier());
+ assertEquals("Unexpected name id", "sguilhen", nameID.getValue());
+ content = subject.getContent().get(1);
+ assertEquals("Unexpected content type", SubjectConfirmationType.class, content.getDeclaredType());
+ confirmation = (SubjectConfirmationType) content.getValue();
+ assertEquals("Unexpected confirmation method", SAMLUtil.SAML2_HOLDER_OF_KEY_URI, confirmation.getMethod());
+ confirmationContent = confirmation.getSubjectConfirmationData().getContent();
+ assertEquals("Unexpected subject confirmation content size", 1, confirmationContent.size());
+ keyInfoElement = (JAXBElement<?>) confirmationContent.get(0);
+ assertEquals("Unexpected subject confirmation context type", KeyInfoType.class, keyInfoElement.getDeclaredType());
+ keyInfo = (KeyInfoType) keyInfoElement.getValue();
+ assertEquals("Unexpected key info content size", 1, keyInfo.getContent().size());
+
+ // key info should contain a X509Data section with the encoded certificate.
+ JAXBElement<?> x509DataElement = (JAXBElement<?>) keyInfo.getContent().get(0);
+ assertEquals("Unexpected key info content type", X509DataType.class, x509DataElement.getDeclaredType());
+ X509DataType x509Data = (X509DataType) x509DataElement.getValue();
+ assertEquals("Unexpected X509 data content size", 1, x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName().
+ size());
+ JAXBElement<?> x509CertElement = (JAXBElement<?>) x509Data.getX509IssuerSerialOrX509SKIOrX509SubjectName().get(0);
+ assertEquals("Unexpected X509 data content type", byte[].class, x509CertElement.getDeclaredType());
+ byte[] encodedCert = (byte[]) x509CertElement.getValue();
+ assertTrue("Invalid encoded certificate found", Arrays.equals(certificate.getEncoded(), encodedCert));
+ }
+
+ /**
+ * <p>
* Tests the validation of a SAMLV2.0 Assertion.
* </p>
*
@@ -241,6 +340,27 @@
/**
* <p>
+ * Obtains the {@code Certificate} stored under the specified alias in the specified keystore.
+ * </p>
+ *
+ * @param keyStoreFile the name of the file that contains a JKS keystore.
+ * @param passwd the keystore password.
+ * @param certificateAlias the alias of a certificate in the keystore.
+ * @return a reference to the {@code Certificate} stored under the given alias.
+ * @throws Exception if an error occurs while handling the keystore.
+ */
+ private Certificate getCertificate(String keyStoreFile, String passwd, String certificateAlias) throws Exception
+ {
+ InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreFile);
+ KeyStore keyStore = KeyStore.getInstance("JKS");
+ keyStore.load(stream, passwd.toCharArray());
+
+ Certificate certificate = keyStore.getCertificate(certificateAlias);
+ return certificate;
+ }
+
+ /**
+ * <p>
* Simple {@code Principal} implementation used in the test scenarios.
* </p>
*
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/serializer.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/serializer.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xalan.jar
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/endorsed/xalan.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/keystore/sts_keystore.jks
===================================================================
(Binary files differ)
Property changes on: identity-federation/trunk/jboss-identity-fed-core/src/test/resources/keystore/sts_keystore.jks
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
14 years, 7 months
JBoss Identity SVN: r806 - identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers.
by jboss-identity-commits@lists.jboss.org
Author: beve
Date: 2009-09-23 04:31:30 -0400 (Wed, 23 Sep 2009)
New Revision: 806
Modified:
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSecurityHandler.java
Log:
A late change cause the handler to not deploy since the method annotated with @PostConstruct though a checked exception.
Modified: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSecurityHandler.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSecurityHandler.java 2009-09-23 07:35:32 UTC (rev 805)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSecurityHandler.java 2009-09-23 08:31:30 UTC (rev 806)
@@ -133,7 +133,7 @@
* @throws WebServiceException
*/
@PostConstruct
- public void createWSTrustClient() throws WebServiceException
+ public void createWSTrustClient()
{
if (wsTrustClient == null)
{
@@ -144,7 +144,7 @@
}
catch (final ParsingException e)
{
- throw new WebServiceException(e.getMessage(), e);
+ throw new IllegalStateException(e.getMessage(), e);
}
}
}
14 years, 7 months
JBoss Identity SVN: r805 - in identity-federation/trunk/jboss-identity-fed-api: src/main/java/org/jboss/identity/federation/api/wstrust and 4 other directories.
by jboss-identity-commits@lists.jboss.org
Author: beve
Date: 2009-09-23 03:35:32 -0400 (Wed, 23 Sep 2009)
New Revision: 805
Added:
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientConfig.java
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientFactory.java
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSaml20Handler.java
identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSecurityHandler.java
identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/handlers/
identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/handlers/JBossSTSSaml20HandlerTestCase.java
identity-federation/trunk/jboss-identity-fed-api/src/test/resources/wstrust/jboss-sts-client.properties
Modified:
identity-federation/trunk/jboss-identity-fed-api/pom.xml
Log:
Work for https://jira.jboss.org/jira/browse/JBID-194 "Add a JAX-WS SOAP Protocol handler for JBossSTS"
Modified: identity-federation/trunk/jboss-identity-fed-api/pom.xml
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/pom.xml 2009-09-22 14:34:10 UTC (rev 804)
+++ identity-federation/trunk/jboss-identity-fed-api/pom.xml 2009-09-23 07:35:32 UTC (rev 805)
@@ -127,6 +127,12 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-all</artifactId>
+ <version>1.8.0</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<reporting>
Added: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientConfig.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientConfig.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientConfig.java 2009-09-23 07:35:32 UTC (rev 805)
@@ -0,0 +1,242 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.api.wstrust;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * WSTrustClientConfig has the ability to either programatically construct
+ * the configuration needed for {@link WSTrustClient} or parse a file
+ * containing the configuration parameters.
+ * <p/>
+ *
+ * <h3>Configure programatically</h3>
+ * <pre>{@code
+ *
+ * Builder builder = new WSTrustClientConfig.Builder();
+ * builder.serviceName("JBossSTS");
+ * builder.portName("JBossSTSPort");
+ * ...
+ * WSTrustClientConfig config = builder.build();
+ *
+ * }</pre>
+ *
+ * <h3>Configure from file</h3>
+ * <pre>{@code
+ *
+ * WSTrustClientConfig config = new WSTrustClientConfig.Builder().build(configFile);
+ *
+ * }</pre>
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ */
+public class WSTrustClientConfig
+{
+ public static final String DEFAULT_CONFIG_FILE = "jboss-sts-client.properties";
+
+ public static final String SERVICE_NAME = "serviceName";
+ public static final String PORT_NAME = "portName";
+ public static final String ENDPOINT_ADDRESS = "endpointAddress";
+ public static final String USERNAME = "username";
+ public static final String PASSWORD = "password";
+ public static final String TOKEN_TYPE = "tokenType";
+
+ private String serviceName;
+ private String portName;
+ private String endpointAddress;
+ private String username;
+ private String password;
+
+ private WSTrustClientConfig(final Builder builder)
+ {
+ serviceName = builder.serviceName;
+ portName = builder.portName;
+ endpointAddress = builder.endpointAddress;
+ username = builder.username;
+ password = builder.password;
+ }
+
+ public String getServiceName()
+ {
+ return serviceName;
+ }
+
+ public String getPortName()
+ {
+ return portName;
+ }
+
+ public String getEndPointAddress()
+ {
+ return endpointAddress;
+ }
+
+ public String getUsername()
+ {
+ return username;
+ }
+
+ public String getPassword()
+ {
+ return password;
+ }
+
+ public String toString()
+ {
+ return getClass().getSimpleName() + "[serviceName=" + serviceName + ", portName=" + portName + ", endpointAddress=" + endpointAddress + "]";
+ }
+
+ public static class Builder
+ {
+ private String serviceName;
+ private String portName;
+ private String endpointAddress;
+ private String username;
+ private String password;
+
+ public Builder serviceName(final String serviceName)
+ {
+ this.serviceName = serviceName;
+ return this;
+ }
+
+ public Builder portName(final String portName)
+ {
+ this.portName = portName;
+ return this;
+ }
+
+ public Builder endpointAddress(final String address)
+ {
+ this.endpointAddress = address;
+ return this;
+ }
+
+ public Builder username(final String username)
+ {
+ this.username = username;
+ return this;
+ }
+
+ public Builder password(final String password)
+ {
+ this.password = password;
+ return this;
+ }
+
+ public WSTrustClientConfig build()
+ {
+ validate(this);
+ return new WSTrustClientConfig(this);
+ }
+
+ private void validate(Builder builder)
+ {
+ checkPropertyShowValue(serviceName, SERVICE_NAME);
+ checkPropertyShowValue(portName, PORT_NAME);
+ checkPropertyShowValue(endpointAddress, endpointAddress);
+ checkProperty(username, USERNAME);
+ checkProperty(password, PASSWORD);
+ }
+
+ private void checkPropertyShowValue(final String propertyName, final String propertyValue)
+ {
+ if (propertyValue == null || propertyValue.equals(""))
+ throw new IllegalArgumentException(propertyName + " property must not be null or empty was:" + propertyValue);
+ }
+
+ private void checkProperty(final String propertyName, final String propertyValue)
+ {
+ if (propertyValue == null || propertyValue.equals(""))
+ throw new IllegalArgumentException(propertyName + " property must not be null");
+ }
+
+ public WSTrustClientConfig build(final String configFile)
+ {
+ InputStream in = null;
+
+ try
+ {
+ in = getResource(configFile);
+ if (in == null)
+ {
+ throw new IllegalStateException("Could not find properties file " + configFile);
+
+ }
+ final Properties properties = new Properties();
+ properties.load(in);
+ this.serviceName = properties.getProperty(SERVICE_NAME);
+ this.portName = properties.getProperty(PORT_NAME);
+ this.endpointAddress = properties.getProperty(ENDPOINT_ADDRESS);
+ this.username = properties.getProperty(USERNAME);
+ this.password = properties.getProperty(PASSWORD);
+ }
+ catch (IOException e)
+ {
+ throw new IllegalStateException("Could not load properties from " + configFile);
+ }
+ finally
+ {
+ try
+ {
+ if (in != null)
+ in.close();
+ }
+ catch (final IOException ignored)
+ {
+ ignored.printStackTrace();
+ }
+ }
+
+ validate(this);
+ return new WSTrustClientConfig(this);
+ }
+ }
+
+ private static InputStream getResource(String resource) throws IOException
+ {
+ // Try it as a File resource...
+ final File file = new File(resource);
+
+ if (file.exists() && !file.isDirectory())
+ {
+ return new FileInputStream(file);
+ }
+ // Try it as a classpath resource ...
+ final ClassLoader threadClassLoader = Thread.currentThread().getContextClassLoader() ;
+ if (threadClassLoader != null)
+ {
+ final InputStream is = threadClassLoader.getResourceAsStream(resource) ;
+ if (is != null)
+ {
+ return is ;
+ }
+ }
+
+ return null;
+ }
+
+}
+
Added: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientFactory.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientFactory.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/WSTrustClientFactory.java 2009-09-23 07:35:32 UTC (rev 805)
@@ -0,0 +1,50 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.api.wstrust;
+
+import org.jboss.identity.federation.api.wstrust.WSTrustClient;
+import org.jboss.identity.federation.api.wstrust.WSTrustClient.SecurityInfo;
+import org.jboss.identity.federation.core.exceptions.ParsingException;
+
+/**
+ * Simple factory for creating {@link WSTrustClient}s.
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ */
+public final class WSTrustClientFactory
+{
+ private static final WSTrustClientFactory INSTANCE = new WSTrustClientFactory();
+
+ private WSTrustClientFactory()
+ {
+ }
+
+ public static WSTrustClientFactory getInstance()
+ {
+ return INSTANCE;
+ }
+
+ public WSTrustClient create(final WSTrustClientConfig c) throws ParsingException
+ {
+ return new WSTrustClient(c.getServiceName(), c.getPortName(), c.getEndPointAddress(), new SecurityInfo(c.getUsername(), c.getPassword()));
+ }
+}
+
Added: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSaml20Handler.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSaml20Handler.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSaml20Handler.java 2009-09-23 07:35:32 UTC (rev 805)
@@ -0,0 +1,67 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.api.wstrust.handlers;
+
+import static org.jboss.identity.federation.core.wstrust.WSTrustConstants.WSSE_NS;
+import static org.jboss.identity.federation.core.wstrust.WSTrustConstants.SAML2_ASSERTION_NS;
+import javax.xml.namespace.QName;
+
+
+/**
+ * A concrete implementation of {@link JBossSTSSecurityHandler} that can
+ * handle SAML version 2.0 Assertion inside of {@link WSTrustConstants#WSSE_NS} elements
+ * <p/>
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ */
+public class JBossSTSSaml20Handler extends JBossSTSSecurityHandler
+{
+ /**
+ * Qualified name for WSSE Security Header ({@link WSTrustConstants#WSSE_NS}:"Security")
+ */
+ public static final QName SECURITY_QNAME = new QName(WSSE_NS, "Security");
+
+ /**
+ * Qualified name for SAML Version 2.0 ({@link WSTrustConstants#SAML2_ASSERTION_NS}:"Assertion")
+ */
+ public static final QName SAML_TOKEN_QNAME = new QName(SAML2_ASSERTION_NS, "Assertion");
+
+ /*
+ * (non-Javadoc)
+ * @see org.jboss.identity.federation.api.wstrust.handlers.JBossSTSSecurityHandler#getSecurityElementQName()
+ */
+ @Override
+ public QName getSecurityElementQName()
+ {
+ return SECURITY_QNAME;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see org.jboss.identity.federation.api.wstrust.handlers.JBossSTSSecurityHandler#getTokenElementQName()
+ */
+ @Override
+ public QName getTokenElementQName()
+ {
+ return SAML_TOKEN_QNAME;
+ }
+
+}
Added: identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSecurityHandler.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSecurityHandler.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-api/src/main/java/org/jboss/identity/federation/api/wstrust/handlers/JBossSTSSecurityHandler.java 2009-09-23 07:35:32 UTC (rev 805)
@@ -0,0 +1,266 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.identity.federation.api.wstrust.handlers;
+
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.Resource;
+import javax.xml.namespace.QName;
+import javax.xml.soap.SOAPException;
+import javax.xml.soap.SOAPHeader;
+import javax.xml.soap.SOAPHeaderElement;
+import javax.xml.ws.WebServiceException;
+import javax.xml.ws.handler.MessageContext;
+import javax.xml.ws.handler.soap.SOAPHandler;
+import javax.xml.ws.handler.soap.SOAPMessageContext;
+
+import org.jboss.identity.federation.api.wstrust.WSTrustClient;
+import org.jboss.identity.federation.api.wstrust.WSTrustClientConfig;
+import org.jboss.identity.federation.api.wstrust.WSTrustClientFactory;
+import org.jboss.identity.federation.core.exceptions.ParsingException;
+import org.jboss.identity.federation.core.wstrust.WSTrustException;
+import org.w3c.dom.Element;
+
+/**
+ * JBossSTSSecurityHandler is a server-side JAX-WS SOAP Protocol handler that will extract
+ * a Security Token from the SOAP Security Header and validate the token with JBoss Security
+ * Token Service (STS)
+ * <p/>
+ *
+ * <h3>Concrete implementations</h3>
+ * Subclasses a required to implement two methods:
+ * <ul>
+ * <li> {@link #getSecurityElementQName()}
+ * This should return the qualified name of the security header. This lets us support
+ * different versions. </li>
+ *
+ * <li>{@link #getTokenElementQName()}
+ * This should return the qualified name of the security token element that should exist
+ * in the security header. This lets us support different tokens that can be validated
+ * with JBossSTS.</li>
+ * </ul>
+ *
+ * This class is abstract to simpify is usage as the intention is for a handler to be specified
+ * in a server side handler chain. Here different Security Header specifications and security token
+ * specifications can be specified using class names instead of using properties which would force
+ * users to finding and setting the correct namespaces. Hopefully this will be easier and less
+ * error prone.
+ *
+ * handlerchain.xml example:
+ * <pre>{@code
+ * <?xml version="1.0" encoding="UTF-8"?>
+ * <jws:handler-config xmlns:jws="http://java.sun.com/xml/ns/javaee">
+ * <jws:handler-chains>
+ * <jws:handler-chain>
+ * <jws:handler>
+ * <jws:handler-class>org.jboss.identity.federation.api.wstrust.handlers.JBossSTSSaml20Handler</jws:handler-class>
+ * </jws:handler>
+ * </jws:handler-chain>
+ * </jws:handler-chains>
+ * </jws:handler-config>
+ * }</pre>
+ * <p/>
+ *
+ * <h3>Configuration</h3>
+ * This class uses {@link WSTrustClient} to interact with JBossSTS. By default the configuration
+ * properties are set in a file named {@link WSTrustClientConfig#DEFAULT_CONFIG_FILE}.
+ * This can be overridden by specifying environment entries in a deployment descriptor.
+ *
+ * For example in web.xml:
+ * <pre>{@code
+ * <env-entry>
+ * <env-entry-name>JBossSTSClientConfig</env-entry-name>
+ * <env-entry-type>java.lang.String</env-entry-type>
+ * <env-entry-value>/jboss-sts-client.properties</env-entry-value>
+ * </env-entry>
+ * }</pre>
+ *
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ */
+public abstract class JBossSTSSecurityHandler implements SOAPHandler<SOAPMessageContext>
+{
+ /**
+ * The path to the jboss-sts-client.properties file.
+ */
+ private String configFile = WSTrustClientConfig.DEFAULT_CONFIG_FILE;
+
+ /**
+ * The {@link WSTrustClient client} that will call JBossSTS.
+ */
+ private WSTrustClient wsTrustClient;
+
+ /**
+ * Subclasses can return the QName of the Security header element in usage.
+ *
+ * @return QName
+ */
+ public abstract QName getSecurityElementQName();
+
+ /**
+ * Subclasses can return the QName of the Security Element that should be used
+ * as the token for validation.
+ *
+ * @return QName
+ */
+ public abstract QName getTokenElementQName();
+
+
+ /**
+ * Post constuct will be called when the handler is deployed.
+ *
+ * @throws WebServiceException
+ */
+ @PostConstruct
+ public void createWSTrustClient() throws WebServiceException
+ {
+ if (wsTrustClient == null)
+ {
+ try
+ {
+ final WSTrustClientConfig config = new WSTrustClientConfig.Builder().build(configFile);
+ wsTrustClient = WSTrustClientFactory.getInstance().create(config);
+ }
+ catch (final ParsingException e)
+ {
+ throw new WebServiceException(e.getMessage(), e);
+ }
+ }
+ }
+
+ /**
+ * Will process in-bound messages and extract a security token from the SOAP Header. This token
+ * will then be validated using by calling JBossSTS.
+ *
+ * @param messageContext The {@link SOAPMessageContext messageContext}.
+ * @return true If the security token was correctly validated or if this call was an outbound message.
+ * @throws WebServiceException If the security token could not be validated.
+ */
+ public boolean handleMessage(final SOAPMessageContext messageContext)
+ {
+ if (isOutBound(messageContext))
+ {
+ return true;
+ }
+
+ try
+ {
+ final Element securityToken = extractSecurityToken(messageContext, getSecurityElementQName(), getTokenElementQName());
+
+ if (wsTrustClient.validateToken(securityToken))
+ {
+ return true;
+ }
+ else
+ {
+ throw new WebServiceException("Could not validate security token "+ securityToken);
+ }
+ }
+ catch (final SOAPException e)
+ {
+ throw new WebServiceException(e.getMessage(), e);
+ }
+ catch (final WSTrustException e)
+ {
+ throw new WebServiceException(e.getMessage(), e);
+ }
+ }
+
+ /**
+ * Allows the {@link WSTrustClient} to be injected if required.
+ *
+ * @param client The WSTrustClient to be used by this handler.
+ */
+ public void setWSTrustClient(final WSTrustClient client)
+ {
+ wsTrustClient = client;
+ }
+
+
+ public Set<QName> getHeaders()
+ {
+ return Collections.singleton(getSecurityElementQName());
+ }
+
+ /**
+ *
+ */
+ public boolean handleFault(final SOAPMessageContext messageContext)
+ {
+ return true;
+ }
+
+ public void close(final MessageContext messageContext)
+ {
+ // NoOp.
+ }
+
+ /**
+ * This setter enables the injection of the jboss-sts-client.properties file
+ * path.
+ *
+ * Note: This resource injection does not work with AS4.2.3 but with AS 5.1.0 this works as expected.
+ *
+ * @param configFile
+ */
+ @Resource (name = "JBossSTSClientConfig")
+ public void setConfigFile(final String configFile)
+ {
+ if (configFile != null)
+ {
+ this.configFile = configFile;
+ }
+ }
+
+ private boolean isOutBound(final SOAPMessageContext messageContext)
+ {
+ return ((Boolean) messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue();
+ }
+
+ @SuppressWarnings("unchecked")
+ private Element extractSecurityToken(final SOAPMessageContext messageContext, final QName securityQName, final QName tokenQName) throws SOAPException
+ {
+ if (securityQName == null)
+ throw new IllegalStateException("securityQName from subclass cannot be null!");
+ if (tokenQName == null)
+ throw new IllegalStateException("tokenQName from subclass cannot be null!");
+
+ final SOAPHeader soapHeader = messageContext.getMessage().getSOAPHeader();
+ final Iterator securityHeaders = soapHeader.getChildElements(securityQName);
+ while (securityHeaders.hasNext())
+ {
+ final SOAPHeaderElement elem = (SOAPHeaderElement) securityHeaders.next();
+ // Check if the header is equal to the one this Handler is configured for.
+ if (elem.getElementQName().equals(securityQName))
+ {
+ final Iterator childElements = elem.getChildElements(tokenQName);
+ while (childElements.hasNext())
+ {
+ return (Element) childElements.next();
+ }
+ }
+ }
+ return null;
+ }
+}
Added: identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/handlers/JBossSTSSaml20HandlerTestCase.java
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/handlers/JBossSTSSaml20HandlerTestCase.java (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-api/src/test/java/org/jboss/test/identity/federation/api/wstrust/handlers/JBossSTSSaml20HandlerTestCase.java 2009-09-23 07:35:32 UTC (rev 805)
@@ -0,0 +1,153 @@
+/*
+ * JBoss, Home of Professional Open Source Copyright 2009, Red Hat Middleware
+ * LLC, and individual contributors by the @authors tag. See the copyright.txt
+ * in the distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU Lesser General Public License as published by the Free
+ * Software Foundation; either version 2.1 of the License, or (at your option)
+ * any later version.
+ *
+ * This software is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this software; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
+ * site: http://www.fsf.org.
+ */
+package org.jboss.test.identity.federation.api.wstrust.handlers;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import javax.xml.namespace.QName;
+import javax.xml.soap.MessageFactory;
+import javax.xml.soap.SOAPElement;
+import javax.xml.soap.SOAPException;
+import javax.xml.soap.SOAPHeader;
+import javax.xml.soap.SOAPHeaderElement;
+import javax.xml.soap.SOAPMessage;
+import javax.xml.ws.WebServiceException;
+import javax.xml.ws.handler.MessageContext;
+import javax.xml.ws.handler.soap.SOAPMessageContext;
+
+import junit.framework.TestCase;
+
+import org.jboss.identity.federation.api.wstrust.WSTrustClient;
+import org.jboss.identity.federation.api.wstrust.handlers.JBossSTSSaml20Handler;
+import org.jboss.identity.federation.api.wstrust.handlers.JBossSTSSecurityHandler;
+import org.w3c.dom.Element;
+
+/**
+ * Unit test for {@link JBossSTSSaml20Handler}.
+ *
+ * @author <a href="mailto:dbevenius@jboss.com">Daniel Bevenius</a>
+ *
+ */
+public class JBossSTSSaml20HandlerTestCase extends TestCase
+{
+ private SOAPMessageContext soapMessageContext;
+ private SOAPMessage soapMessage;
+ private WSTrustClient wsTrustClient;
+ private JBossSTSSaml20Handler samlHandler;
+
+ public void testHandleMessageOutbound() throws SOAPException
+ {
+ setOutbound(soapMessageContext, true);
+ assertTrue(new JBossSTSSaml20Handler().handleMessage(soapMessageContext));
+ }
+
+ public void testHandleMessageInboundValidToken() throws Exception
+ {
+ final SOAPHeader soapHeader = soapMessage.getSOAPHeader();
+
+ // Make the Mocked WSTrustClient validateToken method return true.
+ when(wsTrustClient.validateToken((any(Element.class)))).thenReturn(true);
+
+ final SOAPHeaderElement securityHeader = addSecurityHeader(samlHandler, soapHeader);
+ addAssertionElement(samlHandler, securityHeader);
+
+ setOutbound(soapMessageContext, false);
+ setMessageOnContext(soapMessageContext, soapMessage);
+
+ boolean result = samlHandler.handleMessage(soapMessageContext);
+ assertTrue(result);
+ }
+
+ public void testHandleMessageInValidToken() throws Exception
+ {
+ final SOAPHeader soapHeader = soapMessage.getSOAPHeader();
+
+ // Make the Mocked WSTrustClient validateToken method return false.
+ when(wsTrustClient.validateToken((any(Element.class)))).thenReturn(false);
+
+ final SOAPHeaderElement securityHeader = addSecurityHeader(samlHandler, soapHeader);
+ addAssertionElement(samlHandler, securityHeader);
+
+ setOutbound(soapMessageContext, false);
+ setMessageOnContext(soapMessageContext, soapMessage);
+ try
+ {
+ samlHandler.handleMessage(soapMessageContext);
+ fail("handleMessage should have thrown a exception!");
+ }
+ catch(final Exception e)
+ {
+ assertTrue (e instanceof WebServiceException);
+ }
+ }
+
+ public void setUp()
+ {
+ // Create a Mock for WSTrustClient.
+ wsTrustClient = mock(WSTrustClient.class);
+
+ samlHandler = new JBossSTSSaml20Handler();
+ // Set the WSTrustClient to our mocked client.
+ samlHandler.setWSTrustClient(wsTrustClient);
+ // Simulate the WS Engine calling @PostConstruct.
+ samlHandler.createWSTrustClient();
+
+ soapMessageContext = mock(SOAPMessageContext.class);
+
+ try
+ {
+ soapMessage = MessageFactory.newInstance().createMessage();
+ }
+ catch (SOAPException e)
+ {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
+ private SOAPHeaderElement addSecurityHeader(final JBossSTSSecurityHandler handler, final SOAPHeader soapHeader) throws SOAPException
+ {
+ final QName securityQName = handler.getSecurityElementQName();
+ final SOAPHeaderElement securityHeader = soapHeader.addHeaderElement(new QName(securityQName.getNamespaceURI(), securityQName.getLocalPart(), "wsse"));
+ soapHeader.addChildElement(securityHeader);
+ return securityHeader;
+ }
+
+ private SOAPElement addAssertionElement(final JBossSTSSecurityHandler handler, final SOAPHeaderElement securityHeader) throws SOAPException
+ {
+ final QName tokenElementQName = handler.getTokenElementQName();
+ final SOAPElement tokenElement = securityHeader.addChildElement(new QName(tokenElementQName.getNamespaceURI(), tokenElementQName.getLocalPart(), "saml"));
+ return securityHeader.addChildElement(tokenElement);
+ }
+
+ private void setMessageOnContext(final SOAPMessageContext messageContext, final SOAPMessage soapMessage)
+ {
+ when(messageContext.getMessage()).thenReturn(soapMessage);
+ }
+
+ private void setOutbound(MessageContext messageContext, boolean outbound)
+ {
+ when(messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY)).thenReturn(outbound);
+ }
+
+}
+
Added: identity-federation/trunk/jboss-identity-fed-api/src/test/resources/wstrust/jboss-sts-client.properties
===================================================================
--- identity-federation/trunk/jboss-identity-fed-api/src/test/resources/wstrust/jboss-sts-client.properties (rev 0)
+++ identity-federation/trunk/jboss-identity-fed-api/src/test/resources/wstrust/jboss-sts-client.properties 2009-09-23 07:35:32 UTC (rev 805)
@@ -0,0 +1,5 @@
+serviceName=JBossSTS
+portName=JBossSTSPort
+endpointAddress=http://localhost:8080/jboss-sts/JBossSTS
+username=admin
+password=admin
14 years, 7 months
JBoss Identity SVN: r803 - in idm/trunk: idm-testsuite/src/test/java/org/jboss/identity/idm/impl/api and 1 other directories.
by jboss-identity-commits@lists.jboss.org
Author: bdaw
Date: 2009-09-21 11:56:43 -0400 (Mon, 21 Sep 2009)
New Revision: 803
Modified:
idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreImpl.java
idm/trunk/idm-testsuite/src/test/java/org/jboss/identity/idm/impl/api/APILDAPTestCase.java
idm/trunk/parent/pom.xml
Log:
- fix sort without LDAP control issue
- add up to 4 custom test jdbc providers
Modified: idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreImpl.java
===================================================================
--- idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreImpl.java 2009-09-21 15:15:13 UTC (rev 802)
+++ idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreImpl.java 2009-09-21 15:56:43 UTC (rev 803)
@@ -685,6 +685,12 @@
}
}
+ // In case sort extension is not supported
+ if (criteria != null && criteria.isSorted() && !configuration.isSortExtensionSupported())
+ {
+ sortByName(objects, criteria.isAscending());
+ }
+
if (criteria != null && criteria.isPaged())
{
objects = (LinkedList)cutPageFromResults(objects, criteria);
Modified: idm/trunk/idm-testsuite/src/test/java/org/jboss/identity/idm/impl/api/APILDAPTestCase.java
===================================================================
--- idm/trunk/idm-testsuite/src/test/java/org/jboss/identity/idm/impl/api/APILDAPTestCase.java 2009-09-21 15:15:13 UTC (rev 802)
+++ idm/trunk/idm-testsuite/src/test/java/org/jboss/identity/idm/impl/api/APILDAPTestCase.java 2009-09-21 15:56:43 UTC (rev 803)
@@ -22,27 +22,13 @@
package org.jboss.identity.idm.impl.api;
-import junit.framework.TestCase;
-import org.jboss.identity.idm.impl.HibernateTestSupport;
-import org.jboss.identity.idm.impl.IdentityTestPOJO;
+import org.jboss.identity.idm.api.IdentitySessionFactory;
import org.jboss.identity.idm.impl.LDAPTestPOJO;
import org.jboss.identity.idm.impl.configuration.IdentityConfigurationImpl;
-import org.jboss.identity.idm.api.IdentitySessionFactory;
-import org.jboss.identity.idm.api.cfg.IdentityConfiguration;
-import org.jboss.identity.idm.opends.OpenDSService;
import org.jboss.unit.api.pojo.annotations.Create;
import org.jboss.unit.api.pojo.annotations.Destroy;
import org.jboss.unit.api.pojo.annotations.Test;
-import org.opends.server.tools.LDAPModify;
-import javax.naming.directory.DirContext;
-import javax.naming.Context;
-import javax.naming.NamingEnumeration;
-import javax.naming.Binding;
-import javax.naming.ldap.InitialLdapContext;
-import java.util.Hashtable;
-import java.io.File;
-
/**
* @author <a href="mailto:boleslaw.dawidowicz at redhat.com">Boleslaw Dawidowicz</a>
* @version : 0.1 $
Modified: idm/trunk/parent/pom.xml
===================================================================
--- idm/trunk/parent/pom.xml 2009-09-21 15:15:13 UTC (rev 802)
+++ idm/trunk/parent/pom.xml 2009-09-21 15:56:43 UTC (rev 803)
@@ -105,6 +105,30 @@
</dependency>
</dependencies>
</profile>
+ <profile>
+ <id>provided-jdbc-driver3</id>
+ <dependencies>
+ <dependency>
+ <groupId>privided</groupId>
+ <artifactId>jdbc-driver3</artifactId>
+ <version>NA</version>
+ <scope>system</scope>
+ <systemPath>${provided.jdbc.driver.path3}</systemPath>
+ </dependency>
+ </dependencies>
+ </profile>
+ <profile>
+ <id>provided-jdbc-driver4</id>
+ <dependencies>
+ <dependency>
+ <groupId>privided</groupId>
+ <artifactId>jdbc-driver4</artifactId>
+ <version>NA</version>
+ <scope>system</scope>
+ <systemPath>${provided.jdbc.driver.path4}</systemPath>
+ </dependency>
+ </dependencies>
+ </profile>
</profiles>
<repositories>
14 years, 7 months
JBoss Identity SVN: r802 - in idm/trunk: idm-testsuite/src/test/java/org/jboss/identity/idm/impl/store/ldap and 1 other directories.
by jboss-identity-commits@lists.jboss.org
Author: bdaw
Date: 2009-09-21 11:15:13 -0400 (Mon, 21 Sep 2009)
New Revision: 802
Modified:
idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreConfiguration.java
idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreImpl.java
idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/SimpleLDAPIdentityStoreConfiguration.java
idm/trunk/idm-testsuite/src/test/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreTestCase.java
idm/trunk/idm-testsuite/src/test/resources/test-identity-config-openldapds.xml
Log:
make sort extension support configurable
Modified: idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreConfiguration.java
===================================================================
--- idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreConfiguration.java 2009-09-21 14:11:12 UTC (rev 801)
+++ idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreConfiguration.java 2009-09-21 15:15:13 UTC (rev 802)
@@ -82,4 +82,6 @@
String getNamedRelationshipMemberAttributeName();
+ boolean isSortExtensionSupported();
+
}
Modified: idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreImpl.java
===================================================================
--- idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreImpl.java 2009-09-21 14:11:12 UTC (rev 801)
+++ idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreImpl.java 2009-09-21 15:15:13 UTC (rev 802)
@@ -47,6 +47,7 @@
import org.jboss.identity.idm.spi.store.IdentityStoreInvocationContext;
import org.jboss.identity.idm.spi.store.IdentityStoreSession;
+import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -63,7 +64,6 @@
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
-import java.io.UnsupportedEncodingException;
import javax.naming.Context;
import javax.naming.InitialContext;
@@ -105,22 +105,13 @@
IdentityStoreConfigurationMetaData configurationMD;
- private static Set<IdentityObjectSearchCriteriaType> supportedSearchCriteriaTypes =
+ private final Set<IdentityObjectSearchCriteriaType> supportedSearchCriteriaTypes =
new HashSet<IdentityObjectSearchCriteriaType>();
// <IdentityObjectType name, <Attribute name, MD>
private Map<String, Map<String, IdentityObjectAttributeMetaData>> attributesMetaData = new HashMap<String, Map<String, IdentityObjectAttributeMetaData>>();
- static {
- // List all supported controls classes
- //TODO: attribute filter
- supportedSearchCriteriaTypes.add(IdentityObjectSearchCriteriaType.SORT);
- supportedSearchCriteriaTypes.add(IdentityObjectSearchCriteriaType.PAGE);
- supportedSearchCriteriaTypes.add(IdentityObjectSearchCriteriaType.NAME_FILTER);
- //supportedSearchControls.add(AttributeFilterSearchControl.class);
- }
-
public LDAPIdentityStoreImpl(String id)
{
this.id = id;
@@ -147,6 +138,15 @@
}
}
+ supportedSearchCriteriaTypes.clear();
+ if (configuration.isSortExtensionSupported())
+ {
+ supportedSearchCriteriaTypes.add(IdentityObjectSearchCriteriaType.SORT);
+ }
+ supportedSearchCriteriaTypes.add(IdentityObjectSearchCriteriaType.PAGE);
+ supportedSearchCriteriaTypes.add(IdentityObjectSearchCriteriaType.NAME_FILTER);
+
+
supportedFeatures = new FeaturesMetaDataImpl(configurationMD, supportedSearchCriteriaTypes, false, false, readOnlyObjectTypes);
// Attribute mappings - helper structures
@@ -577,12 +577,11 @@
Control[] requestControls = null;
// Sort control
- if (criteria != null && criteria.isSorted())
+ if (criteria != null && criteria.isSorted() && configuration.isSortExtensionSupported())
{
- //TODO: make criticallity optional
//TODO sort by attribute name
requestControls = new Control[]{
- new SortControl(typeConfiguration.getIdAttributeName(), Control.NONCRITICAL)
+ new SortControl(typeConfiguration.getIdAttributeName(), Control.CRITICAL)
};
}
@@ -640,7 +639,7 @@
{
ctx = (LdapContext)res.getObject();
String dn = ctx.getNameInNamespace();
- if (criteria != null && criteria.isSorted())
+ if (criteria != null && criteria.isSorted() && configuration.isSortExtensionSupported())
{
// It seams that the sort order is not configurable and
// sort control returns entries in descending order by default...
Modified: idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/SimpleLDAPIdentityStoreConfiguration.java
===================================================================
--- idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/SimpleLDAPIdentityStoreConfiguration.java 2009-09-21 14:11:12 UTC (rev 801)
+++ idm/trunk/idm-ldap/src/main/java/org/jboss/identity/idm/impl/store/ldap/SimpleLDAPIdentityStoreConfiguration.java 2009-09-21 15:15:13 UTC (rev 802)
@@ -82,7 +82,9 @@
private final String namedRelationshipMemberAttributeName;
+ private final boolean sortExtensionSupported;
+
// Consts
public static final String PROVIDER_URL = "providerURL";
@@ -125,6 +127,8 @@
public static final String NAMED_RELATIONSHIP_MEMBER_ATTRIBUTE_NAME = "namedRelationshipMemberAttributeName";
+ public static final String SORT_EXTENSION_SUPPORTED = "sortExtensionSupported";
+
public SimpleLDAPIdentityStoreConfiguration(IdentityStoreConfigurationMetaData storeMD)
{
if (storeMD == null)
@@ -167,7 +171,17 @@
this.supportNamedRelationships = false;
}
+ String sortExtension = storeMD.getOptionSingleValue(SORT_EXTENSION_SUPPORTED);
+ if (sortExtension != null && sortExtension.equalsIgnoreCase("false"))
+ {
+ this.sortExtensionSupported = false;
+ }
+ else
+ {
+ this.sortExtensionSupported = true;
+ }
+
Map<String, LDAPIdentityObjectTypeConfiguration> types = new HashMap<String, LDAPIdentityObjectTypeConfiguration>();
for (IdentityObjectTypeMetaData identityObjectTypeMetaData : storeMD.getSupportedIdentityTypes())
@@ -460,4 +474,9 @@
{
return authenticationMethod;
}
+
+ public boolean isSortExtensionSupported()
+ {
+ return sortExtensionSupported;
+ }
}
Modified: idm/trunk/idm-testsuite/src/test/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreTestCase.java
===================================================================
--- idm/trunk/idm-testsuite/src/test/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreTestCase.java 2009-09-21 14:11:12 UTC (rev 801)
+++ idm/trunk/idm-testsuite/src/test/java/org/jboss/identity/idm/impl/store/ldap/LDAPIdentityStoreTestCase.java 2009-09-21 15:15:13 UTC (rev 802)
@@ -364,7 +364,7 @@
public void testCredentials() throws Exception
{
populateClean();
-
+
commonTest.testPasswordCredential();
}
Modified: idm/trunk/idm-testsuite/src/test/resources/test-identity-config-openldapds.xml
===================================================================
--- idm/trunk/idm-testsuite/src/test/resources/test-identity-config-openldapds.xml 2009-09-21 14:11:12 UTC (rev 801)
+++ idm/trunk/idm-testsuite/src/test/resources/test-identity-config-openldapds.xml 2009-09-21 15:15:13 UTC (rev 802)
@@ -933,6 +933,10 @@
<name>searchTimeLimit</name>
<value>10000</value>
</option>
+ <option>
+ <name>sortExtensionSupported</name>
+ <value>false</value>
+ </option>
</options>
</identity-store>
</identity-stores>
14 years, 7 months