You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by co...@apache.org on 2014/07/18 18:15:02 UTC

git commit: Lots of changes + refactoring for SAML SSO

Repository: cxf-fediz
Updated Branches:
  refs/heads/master 3c0a524ca -> e7c14feac


Lots of changes + refactoring for SAML SSO


Project: http://git-wip-us.apache.org/repos/asf/cxf-fediz/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf-fediz/commit/e7c14fea
Tree: http://git-wip-us.apache.org/repos/asf/cxf-fediz/tree/e7c14fea
Diff: http://git-wip-us.apache.org/repos/asf/cxf-fediz/diff/e7c14fea

Branch: refs/heads/master
Commit: e7c14feacd215f8424592bce0e51880f06e95f66
Parents: 3c0a524
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Fri Jul 18 17:14:36 2014 +0100
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Fri Jul 18 17:14:36 2014 +0100

----------------------------------------------------------------------
 .../cxf/fediz/core/TokenValidatorResponse.java  |  11 +
 .../fediz/core/config/FederationProtocol.java   |  52 +---
 .../apache/cxf/fediz/core/config/Protocol.java  |  48 ++++
 .../cxf/fediz/core/config/SAMLProtocol.java     |  34 +--
 .../core/processor/AbstractFedizProcessor.java  |  92 +++++++
 .../core/processor/FederationProcessorImpl.java | 141 ++++-------
 .../cxf/fediz/core/processor/FedizRequest.java  |   9 +
 .../fediz/core/processor/SAMLProcessorImpl.java | 220 +++-------------
 .../core/saml/FedizSignatureTrustValidator.java | 248 +++++++++++++++++++
 .../cxf/fediz/core/saml/SAMLTokenValidator.java |  17 +-
 .../fediz/core/saml/SamlAssertionValidator.java | 128 +---------
 .../core/samlsso/EHCacheSPStateManager.java     |  45 ----
 .../cxf/fediz/core/samlsso/ResponseState.java   |  81 ------
 .../samlsso/SAMLProtocolResponseValidator.java  |  83 +++++--
 .../cxf/fediz/core/samlsso/SPStateManager.java  |   4 -
 .../src/main/resources/schemas/FedizConfig.xsd  |   5 +-
 .../fediz/jetty/FederationAuthenticator.java    |   1 +
 .../web/FederationAuthenticationFilter.java     |   1 +
 .../web/FederationAuthenticationFilter.java     |   1 +
 .../fediz/tomcat/FederationAuthenticator.java   |   1 +
 20 files changed, 588 insertions(+), 634 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/TokenValidatorResponse.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/TokenValidatorResponse.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/TokenValidatorResponse.java
index ad093ee..a52638f 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/TokenValidatorResponse.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/TokenValidatorResponse.java
@@ -31,6 +31,7 @@ public class TokenValidatorResponse {
     private String audience;
     private List<Claim> claims;
     private Date expires;
+    private Date created;
 
 
 
@@ -73,4 +74,14 @@ public class TokenValidatorResponse {
     }
 
 
+    public Date getCreated() {
+        return created;
+    }
+
+
+    public void setCreated(Date created) {
+        this.created = created;
+    }
+
+
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FederationProtocol.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FederationProtocol.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FederationProtocol.java
index c98bb7b..17d749f 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FederationProtocol.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FederationProtocol.java
@@ -24,14 +24,12 @@ import java.util.List;
 
 import javax.security.auth.callback.CallbackHandler;
 
-import org.apache.cxf.fediz.core.TokenValidator;
 import org.apache.cxf.fediz.core.config.jaxb.CallbackType;
 import org.apache.cxf.fediz.core.config.jaxb.ClaimType;
 import org.apache.cxf.fediz.core.config.jaxb.ClaimTypesRequested;
 import org.apache.cxf.fediz.core.config.jaxb.FederationProtocolType;
 import org.apache.cxf.fediz.core.config.jaxb.ProtocolType;
 import org.apache.cxf.fediz.core.saml.SAMLTokenValidator;
-import org.apache.cxf.fediz.core.util.ClassLoaderUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -44,39 +42,15 @@ public class FederationProtocol extends Protocol {
     private Object homeRealm;
     private Object freshness;
     private Object signInQuery;
-    private Object realm;
-    private List<TokenValidator> validators = new ArrayList<TokenValidator>();
     
     public FederationProtocol(ProtocolType protocolType) {
         super(protocolType);
         
-        FederationProtocolType fp = (FederationProtocolType)protocolType;
-        if (fp.getTokenValidators() != null && fp.getTokenValidators().getValidator() != null) {
-            for (String validatorClassname : fp.getTokenValidators().getValidator()) {
-                Object obj = null;
-                try {
-                    if (super.getClassloader() == null) {
-                        obj = ClassLoaderUtils.loadClass(validatorClassname, this.getClass()).newInstance();
-                    } else {
-                        obj = super.getClassloader().loadClass(validatorClassname).newInstance();
-                    }
-                } catch (Exception ex) {
-                    LOG.error("Failed to instantiate TokenValidator implementation class: '"
-                              + validatorClassname + "'\n" + ex.getClass().getCanonicalName() + ": " + ex.getMessage());
-                }
-                if (obj instanceof TokenValidator) {
-                    validators.add((TokenValidator)obj);
-                } else if (obj != null) {
-                    LOG.error("Invalid TokenValidator implementation class: '" + validatorClassname + "'");
-                }
-            }
-        }
-        
         // add SAMLTokenValidator as the last one
         // Fediz chooses the first validator in the list if its
         // canHandleToken or canHandleTokenType method return true
         SAMLTokenValidator validator = new SAMLTokenValidator();
-        validators.add(validators.size(), validator);
+        getTokenValidators().add(getTokenValidators().size(), validator);
     }
 
     protected FederationProtocolType getFederationProtocol() {
@@ -87,26 +61,6 @@ public class FederationProtocol extends Protocol {
         super.setProtocolType(federationProtocol);
     }
 
-    public Object getRealm() {
-        if (this.realm != null) {
-            return this.realm;
-        }
-        CallbackType cbt = getFederationProtocol().getRealm();
-        this.realm = loadCallbackType(cbt, "Realm");
-        return this.realm;
-    }
-
-    public void setRealm(Object value) {
-        final boolean isString = value instanceof String;
-        final boolean isCallbackHandler = value instanceof CallbackHandler;
-        if (isString || isCallbackHandler) {
-            this.realm = value;
-        } else {
-            LOG.error("Unsupported 'Realm' object");
-            throw new IllegalArgumentException("Unsupported 'Realm' object. Type must be "
-                                               + "java.lang.String or javax.security.auth.callback.CallbackHandler.");
-        }
-    }
 
     public String getApplicationServiceURL() {
         return getFederationProtocol().getApplicationServiceURL();
@@ -242,10 +196,6 @@ public class FederationProtocol extends Protocol {
         getFederationProtocol().setClaimTypesRequested(value);
     }
 
-    public List<TokenValidator> getTokenValidators() {
-        return validators;
-    }
-
     public String getVersion() {
         return getFederationProtocol().getVersion();
     }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/Protocol.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/Protocol.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/Protocol.java
index 1683e6e..362ae94 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/Protocol.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/Protocol.java
@@ -19,8 +19,12 @@
 
 package org.apache.cxf.fediz.core.config;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import javax.security.auth.callback.CallbackHandler;
 
+import org.apache.cxf.fediz.core.TokenValidator;
 import org.apache.cxf.fediz.core.config.jaxb.ArgumentType;
 import org.apache.cxf.fediz.core.config.jaxb.CallbackType;
 import org.apache.cxf.fediz.core.config.jaxb.ProtocolType;
@@ -34,10 +38,29 @@ public abstract class Protocol {
     private ProtocolType protocolType;
     private ClassLoader classloader;
     private Object issuer;
+    private Object realm;
+    private List<TokenValidator> validators = new ArrayList<TokenValidator>();
 
     public Protocol(ProtocolType protocolType) {
         super();
         this.protocolType = protocolType;
+        
+        if (protocolType.getTokenValidators() != null && protocolType.getTokenValidators().getValidator() != null) {
+            for (String validatorClassname : protocolType.getTokenValidators().getValidator()) {
+                Object obj = null;
+                try {
+                    obj = ClassLoaderUtils.loadClass(validatorClassname, this.getClass()).newInstance();
+                } catch (Exception ex) {
+                    LOG.error("Failed to instantiate TokenValidator implementation class: '"
+                              + validatorClassname + "'\n" + ex.getClass().getCanonicalName() + ": " + ex.getMessage());
+                }
+                if (obj instanceof TokenValidator) {
+                    validators.add((TokenValidator)obj);
+                } else if (obj != null) {
+                    LOG.error("Invalid TokenValidator implementation class: '" + validatorClassname + "'");
+                }
+            }
+        }
     }
 
     protected ProtocolType getProtocolType() {
@@ -105,6 +128,31 @@ public abstract class Protocol {
         }
     }
     
+    public Object getRealm() {
+        if (this.realm != null) {
+            return this.realm;
+        }
+        CallbackType cbt = getProtocolType().getRealm();
+        this.realm = loadCallbackType(cbt, "Realm");
+        return this.realm;
+    }
+
+    public void setRealm(Object value) {
+        final boolean isString = value instanceof String;
+        final boolean isCallbackHandler = value instanceof CallbackHandler;
+        if (isString || isCallbackHandler) {
+            this.realm = value;
+        } else {
+            LOG.error("Unsupported 'Realm' object");
+            throw new IllegalArgumentException("Unsupported 'Realm' object. Type must be "
+                                               + "java.lang.String or javax.security.auth.callback.CallbackHandler.");
+        }
+    }
+    
+    public List<TokenValidator> getTokenValidators() {
+        return validators;
+    }
+    
     protected Object loadCallbackType(CallbackType cbt, String name) {
         if (cbt == null) {
             return null;

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/SAMLProtocol.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/SAMLProtocol.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/SAMLProtocol.java
index a1dee0b..5f1dcf1 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/SAMLProtocol.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/SAMLProtocol.java
@@ -19,10 +19,6 @@
 
 package org.apache.cxf.fediz.core.config;
 
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.cxf.fediz.core.TokenValidator;
 import org.apache.cxf.fediz.core.config.jaxb.ProtocolType;
 import org.apache.cxf.fediz.core.config.jaxb.SamlProtocolType;
 import org.apache.cxf.fediz.core.saml.SAMLTokenValidator;
@@ -30,7 +26,6 @@ import org.apache.cxf.fediz.core.samlsso.AuthnRequestBuilder;
 import org.apache.cxf.fediz.core.samlsso.DefaultAuthnRequestBuilder;
 import org.apache.cxf.fediz.core.samlsso.EHCacheSPStateManager;
 import org.apache.cxf.fediz.core.samlsso.SPStateManager;
-import org.apache.cxf.fediz.core.util.ClassLoaderUtils;
 import org.apache.wss4j.common.util.Loader;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -41,38 +36,15 @@ public class SAMLProtocol extends Protocol {
     
     private AuthnRequestBuilder authnRequestBuilder;
     private SPStateManager stateManager;
-    private List<TokenValidator> validators = new ArrayList<TokenValidator>();
     
     public SAMLProtocol(ProtocolType protocolType) {
         super(protocolType);
         
-        SamlProtocolType sp = (SamlProtocolType)protocolType;
-        if (sp.getTokenValidators() != null && sp.getTokenValidators().getValidator() != null) {
-            for (String validatorClassname : sp.getTokenValidators().getValidator()) {
-                Object obj = null;
-                try {
-                    if (super.getClassloader() == null) {
-                        obj = ClassLoaderUtils.loadClass(validatorClassname, this.getClass()).newInstance();
-                    } else {
-                        obj = super.getClassloader().loadClass(validatorClassname).newInstance();
-                    }
-                } catch (Exception ex) {
-                    LOG.error("Failed to instantiate TokenValidator implementation class: '"
-                              + validatorClassname + "'\n" + ex.getClass().getCanonicalName() + ": " + ex.getMessage());
-                }
-                if (obj instanceof TokenValidator) {
-                    validators.add((TokenValidator)obj);
-                } else if (obj != null) {
-                    LOG.error("Invalid TokenValidator implementation class: '" + validatorClassname + "'");
-                }
-            }
-        }
-        
         // add SAMLTokenValidator as the last one
         // Fediz chooses the first validator in the list if its
         // canHandleToken or canHandleTokenType method return true
         SAMLTokenValidator validator = new SAMLTokenValidator();
-        validators.add(validators.size(), validator);
+        getTokenValidators().add(getTokenValidators().size(), validator);
     }
     
     protected SamlProtocolType getSAMLProtocol() {
@@ -167,9 +139,5 @@ public class SAMLProtocol extends Protocol {
         this.authnRequestBuilder = authnRequestBuilder;
     }
     
-    public List<TokenValidator> getTokenValidators() {
-        return validators;
-    }
-
     
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/AbstractFedizProcessor.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/AbstractFedizProcessor.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/AbstractFedizProcessor.java
new file mode 100644
index 0000000..cceab0c
--- /dev/null
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/AbstractFedizProcessor.java
@@ -0,0 +1,92 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.fediz.core.processor;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.cxf.fediz.core.config.FedizContext;
+import org.apache.cxf.fediz.core.spi.IDPCallback;
+import org.apache.cxf.fediz.core.spi.RealmCallback;
+
+public abstract class AbstractFedizProcessor implements FedizProcessor {
+
+    protected String resolveIssuer(HttpServletRequest request, FedizContext config) throws IOException,
+        UnsupportedCallbackException {
+        Object issuerObj = config.getProtocol().getIssuer();
+        String issuerURL = null;
+        if (issuerObj instanceof String) {
+            issuerURL = (String)issuerObj;
+        } else if (issuerObj instanceof CallbackHandler) {
+            CallbackHandler issuerCB = (CallbackHandler)issuerObj;
+            IDPCallback callback = new IDPCallback(request);
+            issuerCB.handle(new Callback[] {callback});
+            issuerURL = callback.getIssuerUrl().toString();
+        }
+        return issuerURL;
+    }
+
+    protected String resolveWTRealm(HttpServletRequest request, FedizContext config) throws IOException,
+        UnsupportedCallbackException {
+        Object wtRealmObj = config.getProtocol().getRealm();
+        String wtRealm = null;
+        if (wtRealmObj != null) {
+            if (wtRealmObj instanceof String) {
+                wtRealm = (String)wtRealmObj;
+            } else if (wtRealmObj instanceof CallbackHandler) {
+                CallbackHandler hrCB = (CallbackHandler)wtRealmObj;
+                RealmCallback callback = new RealmCallback(request);
+                hrCB.handle(new Callback[] {callback});
+                wtRealm = callback.getRealm();
+            }
+        } else {
+            wtRealm = extractFullContextPath(request); //default value
+        }
+        return wtRealm;
+    }
+
+    protected String extractFullContextPath(HttpServletRequest request) throws MalformedURLException {
+        String result = null;
+        String contextPath = request.getContextPath();
+        String requestUrl = request.getRequestURL().toString();
+        String requestPath = new URL(requestUrl).getPath();
+        // Cut request path of request url and add context path if not ROOT
+        if (requestPath != null && requestPath.length() > 0) {
+            int lastIndex = requestUrl.lastIndexOf(requestPath);
+            result = requestUrl.substring(0, lastIndex);
+        } else {
+            result = requestUrl;
+        }
+        if (contextPath != null && contextPath.length() > 0) {
+            // contextPath contains starting slash
+            result = result + contextPath + "/";
+        } else {
+            result = result + "/";
+        }
+        return result;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FederationProcessorImpl.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FederationProcessorImpl.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FederationProcessorImpl.java
index 01001a0..3bf4a93 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FederationProcessorImpl.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FederationProcessorImpl.java
@@ -25,6 +25,7 @@ import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLEncoder;
+import java.security.cert.Certificate;
 import java.text.DateFormat;
 import java.text.ParseException;
 import java.util.ArrayList;
@@ -51,8 +52,6 @@ import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
 import org.apache.cxf.fediz.core.metadata.MetadataWriter;
 import org.apache.cxf.fediz.core.spi.FreshnessCallback;
 import org.apache.cxf.fediz.core.spi.HomeRealmCallback;
-import org.apache.cxf.fediz.core.spi.IDPCallback;
-import org.apache.cxf.fediz.core.spi.RealmCallback;
 import org.apache.cxf.fediz.core.spi.SignInQueryCallback;
 import org.apache.cxf.fediz.core.spi.WAuthCallback;
 import org.apache.cxf.fediz.core.spi.WReqCallback;
@@ -73,7 +72,7 @@ import org.joda.time.DateTime;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class FederationProcessorImpl implements FedizProcessor {
+public class FederationProcessorImpl extends AbstractFedizProcessor {
 
     private static final Logger LOG = LoggerFactory.getLogger(FederationProcessorImpl.class);
 
@@ -191,32 +190,8 @@ public class FederationProcessorImpl implements FedizProcessor {
             }
         }
         
-        TokenValidatorResponse validatorResponse = null;
-        List<TokenValidator> validators = ((FederationProtocol)config.getProtocol()).getTokenValidators();
-        for (TokenValidator validator : validators) {
-            boolean canHandle = false;
-            if (tt != null) {
-                canHandle = validator.canHandleTokenType(tt);
-            } else {
-                canHandle = validator.canHandleToken(rst);
-            }
-            if (canHandle) {
-                try {
-                    TokenValidatorRequest validatorRequest = 
-                        new TokenValidatorRequest(rst, request.getCerts());
-                    validatorResponse = validator.validateAndProcessToken(validatorRequest, config);
-                } catch (ProcessingException ex) {
-                    throw ex;
-                } catch (Exception ex) {
-                    LOG.warn("Failed to validate token", ex);
-                    throw new ProcessingException(TYPE.TOKEN_INVALID);
-                }
-                break;
-            } else {
-                LOG.warn("No security token validator found for '" + tt + "'");
-                throw new ProcessingException(TYPE.BAD_REQUEST);
-            }
-        }
+        TokenValidatorResponse validatorResponse = 
+            validateToken(rst, tt, config, request.getCerts());
 
         // Check whether token already used for signin
         if (validatorResponse.getUniqueTokenId() != null
@@ -245,17 +220,63 @@ public class FederationProcessorImpl implements FedizProcessor {
             }
         }
 
+        Date created = validatorResponse.getCreated();
+        if (lifeTime != null && lifeTime.getCreated() != null) {
+            created = lifeTime.getCreated();
+        }
+        Date expires = validatorResponse.getExpires();
+        if (lifeTime != null && lifeTime.getExpires() != null) {
+            expires = lifeTime.getExpires();
+        }
+        
         FedizResponse fedResponse = new FedizResponse(
                 validatorResponse.getUsername(), validatorResponse.getIssuer(),
                 validatorResponse.getRoles(), validatorResponse.getClaims(),
                 validatorResponse.getAudience(),
-                (lifeTime != null) ? lifeTime.getCreated() : null,
-                        (lifeTime != null) ? lifeTime.getExpires() : null, rst,
-                            validatorResponse.getUniqueTokenId());
+                created,
+                expires, 
+                rst,
+                validatorResponse.getUniqueTokenId());
 
         return fedResponse;
     }
     
+    private TokenValidatorResponse validateToken(
+        Element token,
+        String tokenType,
+        FedizContext config,
+        Certificate[] certs
+    ) throws ProcessingException {
+        TokenValidatorResponse validatorResponse = null;
+        List<TokenValidator> validators = ((FederationProtocol)config.getProtocol()).getTokenValidators();
+        for (TokenValidator validator : validators) {
+            boolean canHandle = false;
+            if (tokenType != null) {
+                canHandle = validator.canHandleTokenType(tokenType);
+            } else {
+                canHandle = validator.canHandleToken(token);
+            }
+            if (canHandle) {
+                try {
+                    TokenValidatorRequest validatorRequest = 
+                        new TokenValidatorRequest(token, certs);
+                    validatorResponse = validator.validateAndProcessToken(validatorRequest, config);
+                } catch (ProcessingException ex) {
+                    throw ex;
+                } catch (Exception ex) {
+                    LOG.warn("Failed to validate token", ex);
+                    throw new ProcessingException(TYPE.TOKEN_INVALID);
+                }
+                break;
+            } else {
+                LOG.warn("No security token validator found for '" + tokenType + "'");
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            }
+        }
+        
+        return validatorResponse;
+    }
+    
     private Element decryptEncryptedRST(
         Element encryptedRST,
         FedizContext config
@@ -596,62 +617,6 @@ public class FederationProcessorImpl implements FedizProcessor {
         return wReq;
     }
 
-    private String resolveIssuer(HttpServletRequest request, FedizContext config) throws IOException,
-        UnsupportedCallbackException {
-        Object issuerObj = ((FederationProtocol)config.getProtocol()).getIssuer();
-        String issuerURL = null;
-        if (issuerObj instanceof String) {
-            issuerURL = (String)issuerObj;
-        } else if (issuerObj instanceof CallbackHandler) {
-            CallbackHandler issuerCB = (CallbackHandler)issuerObj;
-            IDPCallback callback = new IDPCallback(request);
-            issuerCB.handle(new Callback[] {callback});
-            issuerURL = callback.getIssuerUrl().toString();
-        }
-        return issuerURL;
-    }
-
-    private String resolveWTRealm(HttpServletRequest request, FedizContext config) throws IOException,
-        UnsupportedCallbackException {
-        Object wtRealmObj = ((FederationProtocol)config.getProtocol()).getRealm();
-        String wtRealm = null;
-        if (wtRealmObj != null) {
-            if (wtRealmObj instanceof String) {
-                wtRealm = (String)wtRealmObj;
-            } else if (wtRealmObj instanceof CallbackHandler) {
-                CallbackHandler hrCB = (CallbackHandler)wtRealmObj;
-                RealmCallback callback = new RealmCallback(request);
-                hrCB.handle(new Callback[] {callback});
-                wtRealm = callback.getRealm();
-            }
-        } else {
-            wtRealm = extractFullContextPath(request); //default value
-        }
-        return wtRealm;
-    }
-
-
-    private String extractFullContextPath(HttpServletRequest request) throws MalformedURLException {
-        String result = null;
-        String contextPath = request.getContextPath();
-        String requestUrl = request.getRequestURL().toString();
-        String requestPath = new URL(requestUrl).getPath();
-        // Cut request path of request url and add context path if not ROOT
-        if (requestPath != null && requestPath.length() > 0) {
-            int lastIndex = requestUrl.lastIndexOf(requestPath);
-            result = requestUrl.substring(0, lastIndex);
-        } else {
-            result = requestUrl;
-        }
-        if (contextPath != null && contextPath.length() > 0) {
-            // contextPath contains starting slash
-            result = result + contextPath + "/";
-        } else {
-            result = result + "/";
-        }
-        return result;
-    }
-    
     private static class DecryptionCallbackHandler implements CallbackHandler {
         
         private final String password;

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizRequest.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizRequest.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizRequest.java
index 388cf36..e413055 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizRequest.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizRequest.java
@@ -22,6 +22,8 @@ package org.apache.cxf.fediz.core.processor;
 import java.io.Serializable;
 import java.security.cert.Certificate;
 
+import javax.servlet.http.HttpServletRequest;
+
 public class FedizRequest implements Serializable {
 
     private static final long serialVersionUID = 1L;
@@ -31,6 +33,7 @@ public class FedizRequest implements Serializable {
     private String freshness;
     private String state;
     private Certificate[] certs;
+    private HttpServletRequest request;
 
     public Certificate[] getCerts() {
         return certs;
@@ -62,6 +65,12 @@ public class FedizRequest implements Serializable {
     public void setState(String state) {
         this.state = state;
     }
+    public HttpServletRequest getRequest() {
+        return request;
+    }
+    public void setRequest(HttpServletRequest request) {
+        this.request = request;
+    }
 
 
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/SAMLProcessorImpl.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/SAMLProcessorImpl.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/SAMLProcessorImpl.java
index 1fa1a67..94621f7 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/SAMLProcessorImpl.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/SAMLProcessorImpl.java
@@ -21,8 +21,6 @@ package org.apache.cxf.fediz.core.processor;
 
 import java.io.IOException;
 import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
 import java.net.URLEncoder;
 import java.text.SimpleDateFormat;
 import java.util.Date;
@@ -32,14 +30,10 @@ import java.util.TimeZone;
 import java.util.UUID;
 import java.util.zip.DataFormatException;
 
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
 import javax.servlet.http.HttpServletRequest;
 
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-
 import org.apache.cxf.fediz.core.FederationConstants;
 import org.apache.cxf.fediz.core.TokenValidator;
 import org.apache.cxf.fediz.core.TokenValidatorRequest;
@@ -54,7 +48,8 @@ import org.apache.cxf.fediz.core.samlsso.AuthnRequestBuilder;
 import org.apache.cxf.fediz.core.samlsso.CompressionUtils;
 import org.apache.cxf.fediz.core.samlsso.RequestState;
 import org.apache.cxf.fediz.core.samlsso.SAMLProtocolResponseValidator;
-import org.apache.cxf.fediz.core.spi.IDPCallback;
+import org.apache.cxf.fediz.core.samlsso.SAMLSSOResponseValidator;
+import org.apache.cxf.fediz.core.samlsso.SSOValidatorResponse;
 import org.apache.cxf.fediz.core.util.DOMUtils;
 import org.apache.wss4j.common.ext.WSSecurityException;
 import org.apache.wss4j.common.saml.OpenSAMLUtil;
@@ -67,7 +62,7 @@ import org.opensaml.xml.XMLObject;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class SAMLProcessorImpl implements FedizProcessor {
+public class SAMLProcessorImpl extends AbstractFedizProcessor {
 
     private static final Logger LOG = LoggerFactory.getLogger(SAMLProcessorImpl.class);
     
@@ -104,7 +99,7 @@ public class SAMLProcessorImpl implements FedizProcessor {
     public Document getMetaData(FedizContext config) throws ProcessingException {
         return new MetadataWriter().getMetaData(config);
     }
-    /*
+    
     private RequestState processRelayState(String relayState, SAMLProtocol samlProtocol) 
         throws ProcessingException {
         if (relayState.getBytes().length < 0 || relayState.getBytes().length > 80) {
@@ -135,12 +130,12 @@ public class SAMLProcessorImpl implements FedizProcessor {
         
         return false;
     }
-    */
+    
     protected FedizResponse processSignInRequest(
             FedizRequest request, FedizContext config)
         throws ProcessingException {
         SAMLProtocol protocol = (SAMLProtocol)config.getProtocol();
-        // TODO RequestState requestState = processRelayState(request.getState(), protocol);
+        RequestState requestState = processRelayState(request.getState(), protocol);
         
         InputStream tokenStream = null;
         try {
@@ -177,7 +172,7 @@ public class SAMLProcessorImpl implements FedizProcessor {
         }
         
         // Validate the Response
-        validateSamlResponseProtocol((org.opensaml.saml2.core.Response)responseObject);
+        validateSamlResponseProtocol((org.opensaml.saml2.core.Response)responseObject, config);
         
         // Validate the internal assertion(s)
         TokenValidatorResponse validatorResponse = null;
@@ -211,17 +206,15 @@ public class SAMLProcessorImpl implements FedizProcessor {
             }
         }
         
-        /* TODO
-        SSOValidatorResponse validatorResponse = 
-            validateSamlSSOResponse(postBinding, samlResponse, requestState);
-            */
+        validateSamlSSOResponse((org.opensaml.saml2.core.Response)responseObject, 
+                                request.getRequest(), requestState, config);
         
         FedizResponse fedResponse = new FedizResponse(
                 validatorResponse.getUsername(), validatorResponse.getIssuer(),
                 validatorResponse.getRoles(), validatorResponse.getClaims(),
                 validatorResponse.getAudience(),
-                null, // TODO
-                null, // TODO
+                validatorResponse.getCreated(),
+                validatorResponse.getExpires(),
                 token,
                 validatorResponse.getUniqueTokenId());
 
@@ -233,11 +226,12 @@ public class SAMLProcessorImpl implements FedizProcessor {
      * @throws ProcessingException 
      */
     protected void validateSamlResponseProtocol(
-        org.opensaml.saml2.core.Response samlResponse
+        org.opensaml.saml2.core.Response samlResponse,
+        FedizContext config
     ) throws ProcessingException {
         try {
             SAMLProtocolResponseValidator protocolValidator = new SAMLProtocolResponseValidator();
-            protocolValidator.validateSamlResponse(samlResponse);
+            protocolValidator.validateSamlResponse(samlResponse, config);
         } catch (WSSecurityException ex) {
             LOG.debug(ex.getMessage(), ex);
             throw new ProcessingException(TYPE.INVALID_REQUEST);
@@ -246,33 +240,33 @@ public class SAMLProcessorImpl implements FedizProcessor {
     
     /**
      * Validate the received SAML Response as per the Web SSO profile
+     * @throws ProcessingException 
+     */
     protected SSOValidatorResponse validateSamlSSOResponse(
-        boolean postBinding,
         org.opensaml.saml2.core.Response samlResponse,
-        RequestState requestState
-    ) {
+        HttpServletRequest request,
+        RequestState requestState,
+        FedizContext config
+    ) throws ProcessingException {
         try {
             SAMLSSOResponseValidator ssoResponseValidator = new SAMLSSOResponseValidator();
-            ssoResponseValidator.setAssertionConsumerURL(
-                messageContext.getUriInfo().getAbsolutePath().toString());
-
-            ssoResponseValidator.setClientAddress(
-                 messageContext.getHttpServletRequest().getRemoteAddr());
+            String requestURL = request.getRequestURL().toString();
+            ssoResponseValidator.setAssertionConsumerURL(requestURL);
+            ssoResponseValidator.setClientAddress(request.getRemoteAddr());
 
             ssoResponseValidator.setIssuerIDP(requestState.getIdpServiceAddress());
             ssoResponseValidator.setRequestId(requestState.getSamlRequestId());
             ssoResponseValidator.setSpIdentifier(requestState.getIssuerId());
-            ssoResponseValidator.setEnforceAssertionsSigned(enforceAssertionsSigned);
-            ssoResponseValidator.setEnforceKnownIssuer(enforceKnownIssuer);
-            ssoResponseValidator.setReplayCache(getReplayCache());
+            ssoResponseValidator.setEnforceAssertionsSigned(true);
+            ssoResponseValidator.setEnforceKnownIssuer(true);
+            ssoResponseValidator.setReplayCache(config.getTokenReplayCache());
 
-            return ssoResponseValidator.validateSamlResponse(samlResponse, postBinding);
+            return ssoResponseValidator.validateSamlResponse(samlResponse, false);
         } catch (WSSecurityException ex) {
-            reportError("INVALID_SAML_RESPONSE");
-            throw ExceptionUtils.toBadRequestException(ex, null);
+            LOG.debug(ex.getMessage(), ex);
+            throw new ProcessingException(TYPE.INVALID_REQUEST);
         }
     }
-    */
 
     @Override
     public RedirectionResponse createSignInRequest(HttpServletRequest request, FedizContext config)
@@ -299,8 +293,9 @@ public class SAMLProcessorImpl implements FedizProcessor {
      
             // Create the AuthnRequest
             String requestURL = request.getRequestURL().toString();
+            String realm = resolveWTRealm(request, config);
             AuthnRequest authnRequest = 
-                authnRequestBuilder.createAuthnRequest(config.getName(), requestURL);
+                authnRequestBuilder.createAuthnRequest(realm, requestURL);
             
             if (((SAMLProtocol)config.getProtocol()).isSignRequest()) {
                 authnRequest.setDestination(redirectURL);
@@ -314,8 +309,8 @@ public class SAMLProcessorImpl implements FedizProcessor {
             RequestState requestState = new RequestState(requestURL,
                                                          redirectURL,
                                                          authnRequest.getID(),
+                                                         realm,
                                                          config.getName(),
-                                                         requestURL,
                                                          webAppDomain,
                                                          System.currentTimeMillis());
             
@@ -447,156 +442,5 @@ public class SAMLProcessorImpl implements FedizProcessor {
         response.setRedirectionURL(redirectURL);
         return response;
     }
-/*
-    private String resolveSignInQuery(HttpServletRequest request, FedizContext config)
-        throws IOException, UnsupportedCallbackException, UnsupportedEncodingException {
-        Object signInQueryObj = ((FederationProtocol)config.getProtocol()).getSignInQuery();
-        String signInQuery = null;
-        if (signInQueryObj != null) {
-            if (signInQueryObj instanceof String) {
-                signInQuery = (String)signInQueryObj;
-            } else if (signInQueryObj instanceof CallbackHandler) {
-                CallbackHandler frCB = (CallbackHandler)signInQueryObj;
-                SignInQueryCallback callback = new SignInQueryCallback(request);
-                frCB.handle(new Callback[] {callback});
-                Map<String, String> signInQueryMap = callback.getSignInQueryParamMap();
-                StringBuilder sbQuery = new StringBuilder();
-                for (String key : signInQueryMap.keySet()) {
-                    if (sbQuery.length() > 0) {
-                        sbQuery.append("&");
-                    }
-                    sbQuery.append(key).append('=').
-                    append(URLEncoder.encode(signInQueryMap.get(key), "UTF-8"));
-                }
-                signInQuery = sbQuery.toString();
-               
-            }
-        }
-        return signInQuery;
-    }
-
-    private String resolveFreshness(HttpServletRequest request, FedizContext config) throws IOException,
-        UnsupportedCallbackException {
-        Object freshnessObj = ((FederationProtocol)config.getProtocol()).getFreshness();
-        String freshness = null;
-        if (freshnessObj != null) {
-            if (freshnessObj instanceof String) {
-                freshness = (String)freshnessObj;
-            } else if (freshnessObj instanceof CallbackHandler) {
-                CallbackHandler frCB = (CallbackHandler)freshnessObj;
-                FreshnessCallback callback = new FreshnessCallback(request);
-                frCB.handle(new Callback[] {callback});
-                freshness = callback.getFreshness();
-            }
-        }
-        return freshness;
-    }
-
-    private String resolveHomeRealm(HttpServletRequest request, FedizContext config) throws IOException,
-        UnsupportedCallbackException {
-        Object homeRealmObj = ((FederationProtocol)config.getProtocol()).getHomeRealm();
-        String homeRealm = null;
-        if (homeRealmObj != null) {
-            if (homeRealmObj instanceof String) {
-                homeRealm = (String)homeRealmObj;
-            } else if (homeRealmObj instanceof CallbackHandler) {
-                CallbackHandler hrCB = (CallbackHandler)homeRealmObj;
-                HomeRealmCallback callback = new HomeRealmCallback(request);
-                hrCB.handle(new Callback[] {callback});
-                homeRealm = callback.getHomeRealm();
-            }
-        }
-        return homeRealm;
-    }
-
-    private String resolveAuthenticationType(HttpServletRequest request, FedizContext config)
-        throws IOException, UnsupportedCallbackException {
-        Object wAuthObj = ((FederationProtocol)config.getProtocol()).getAuthenticationType();
-        String wAuth = null;
-        if (wAuthObj != null) {
-            if (wAuthObj instanceof String) {
-                wAuth = (String)wAuthObj;
-            } else if (wAuthObj instanceof CallbackHandler) {
-                CallbackHandler wauthCB = (CallbackHandler)wAuthObj;
-                WAuthCallback callback = new WAuthCallback(request);
-                wauthCB.handle(new Callback[] {callback});
-                wAuth = callback.getWauth();
-            }  
-        }
-        return wAuth;
-    }
-    
-    private String resolveRequest(HttpServletRequest request, FedizContext config)
-        throws IOException, UnsupportedCallbackException {
-        Object wReqObj = ((FederationProtocol)config.getProtocol()).getRequest();
-        String wReq = null;
-        if (wReqObj != null) {
-            if (wReqObj instanceof String) {
-                wReq = (String)wReqObj;
-            } else if (wReqObj instanceof CallbackHandler) {
-                CallbackHandler wauthCB = (CallbackHandler)wReqObj;
-                WReqCallback callback = new WReqCallback(request);
-                wauthCB.handle(new Callback[] {callback});
-                wReq = callback.getWreq();
-            }  
-        }
-        return wReq;
-    }
-*/
-    private String resolveIssuer(HttpServletRequest request, FedizContext config) throws IOException,
-        UnsupportedCallbackException {
-        Object issuerObj = config.getProtocol().getIssuer();
-        String issuerURL = null;
-        if (issuerObj instanceof String) {
-            issuerURL = (String)issuerObj;
-        } else if (issuerObj instanceof CallbackHandler) {
-            CallbackHandler issuerCB = (CallbackHandler)issuerObj;
-            IDPCallback callback = new IDPCallback(request);
-            issuerCB.handle(new Callback[] {callback});
-            issuerURL = callback.getIssuerUrl().toString();
-        }
-        return issuerURL;
-    }
-/*
-    private String resolveWTRealm(HttpServletRequest request, FedizContext config) throws IOException,
-        UnsupportedCallbackException {
-        Object wtRealmObj = ((FederationProtocol)config.getProtocol()).getRealm();
-        String wtRealm = null;
-        if (wtRealmObj != null) {
-            if (wtRealmObj instanceof String) {
-                wtRealm = (String)wtRealmObj;
-            } else if (wtRealmObj instanceof CallbackHandler) {
-                CallbackHandler hrCB = (CallbackHandler)wtRealmObj;
-                RealmCallback callback = new RealmCallback(request);
-                hrCB.handle(new Callback[] {callback});
-                wtRealm = callback.getRealm();
-            }
-        } else {
-            wtRealm = extractFullContextPath(request); //default value
-        }
-        return wtRealm;
-    }
-
-*/
-    private String extractFullContextPath(HttpServletRequest request) throws MalformedURLException {
-        String result = null;
-        String contextPath = request.getContextPath();
-        String requestUrl = request.getRequestURL().toString();
-        String requestPath = new URL(requestUrl).getPath();
-        // Cut request path of request url and add context path if not ROOT
-        if (requestPath != null && requestPath.length() > 0) {
-            int lastIndex = requestUrl.lastIndexOf(requestPath);
-            result = requestUrl.substring(0, lastIndex);
-        } else {
-            result = requestUrl;
-        }
-        if (contextPath != null && contextPath.length() > 0) {
-            // contextPath contains starting slash
-            result = result + contextPath + "/";
-        } else {
-            result = result + "/";
-        }
-        return result;
-    }
     
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/FedizSignatureTrustValidator.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/FedizSignatureTrustValidator.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/FedizSignatureTrustValidator.java
new file mode 100644
index 0000000..0a2ff81
--- /dev/null
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/FedizSignatureTrustValidator.java
@@ -0,0 +1,248 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.fediz.core.saml;
+
+
+import java.security.PublicKey;
+import java.security.cert.CertificateExpiredException;
+import java.security.cert.CertificateNotYetValidException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.dom.handler.RequestData;
+import org.apache.wss4j.dom.validate.Credential;
+import org.apache.wss4j.dom.validate.Validator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * This class verifies trust in a signature.. 
+ */
+public class FedizSignatureTrustValidator implements Validator {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(FedizSignatureTrustValidator.class);
+    
+    public enum TRUST_TYPE { CHAIN_TRUST, CHAIN_TRUST_CONSTRAINTS, PEER_TRUST }
+    
+    /**
+     * Defines the kind of trust which is required
+     */
+    private TRUST_TYPE signatureTrustType = TRUST_TYPE.CHAIN_TRUST;
+        
+    /**
+     * a collection of compiled regular expression patterns for the subject DN
+     */
+    private Collection<Pattern> subjectDNPatterns = new ArrayList<Pattern>();
+    
+    
+    /**
+     * Set the kind of trust. The default is CHAIN_TRUST.
+     */
+    public void setSignatureTrustType(TRUST_TYPE trustType) {
+        this.signatureTrustType = trustType;
+    }
+
+    /**
+     * Set a list of Strings corresponding to regular expression constraints on
+     * the subject DN of a certificate
+     */
+    public void setSubjectConstraints(Collection<Pattern> constraints) {
+        if (constraints != null) {
+            subjectDNPatterns.clear();
+            subjectDNPatterns.addAll(constraints);
+        }
+    }
+    
+    /**
+     * Set a list of Strings corresponding to regular expression constraints on
+     * the subject DN of a certificate
+     */
+    public void setSubjectConstraints(List<String> constraints) {
+        if (constraints != null) {
+            subjectDNPatterns = new ArrayList<Pattern>();
+            for (String constraint : constraints) {
+                try {
+                    subjectDNPatterns.add(Pattern.compile(constraint.trim()));
+                } catch (PatternSyntaxException ex) {
+                    // LOG.severe(ex.getMessage());
+                    throw ex;
+                }
+            }
+        }
+    }
+    
+    /**
+     * Validate the credential argument. It must contain either some Certificates or a PublicKey.
+     * 
+     * A Crypto and a CallbackHandler implementation is required to be set.
+     * 
+     * @param credential the Credential to be validated
+     * @param data the RequestData associated with the request
+     * @throws WSSecurityException on a failed validation
+     */
+    public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
+        if (credential == null
+            || ((credential.getCertificates() == null || credential.getCertificates().length == 0)
+                && credential.getPublicKey() == null)) {
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noCredential");
+        }
+        
+        verifyTrust(credential, data);
+        
+        return credential;
+    }
+    
+    /**
+     * Verify trust in the credential.
+     * @param credential the Credential to be validated
+     * @param data The RequestData context
+     * @return A Credential instance
+     * @throws WSSecurityException
+     */
+    protected Credential verifyTrust(
+        Credential credential,
+        RequestData data
+    ) throws WSSecurityException {
+        X509Certificate[] certs = credential.getCertificates();
+        PublicKey publicKey = credential.getPublicKey();
+        Crypto crypto = getCrypto(data);
+        if (crypto == null) {
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noSigCryptoFile");
+        }
+        
+        if (certs != null && certs.length > 0) {
+            validateCertificates(certs);
+            verifyTrustInCerts(certs, crypto, data, data.isRevocationEnabled());
+            if (signatureTrustType.equals(TRUST_TYPE.CHAIN_TRUST_CONSTRAINTS)) {
+                if (matches(certs[0])) {
+                    return credential;
+                } else {
+                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
+                }
+            } else {
+                return credential;
+            }
+        }
+        if (publicKey != null) {
+            validatePublicKey(publicKey, crypto);
+            return credential;
+        }
+        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
+    }
+
+    protected Crypto getCrypto(RequestData data) {
+        return data.getSigVerCrypto();
+    }
+
+
+    /**
+     * Validate the certificates by checking the validity of each cert
+     * @throws WSSecurityException
+     */
+    protected void validateCertificates(X509Certificate[] certificates) 
+        throws WSSecurityException {
+        try {
+            for (int i = 0; i < certificates.length; i++) {
+                certificates[i].checkValidity();
+            }
+        } catch (CertificateExpiredException e) {
+            throw new WSSecurityException(
+                WSSecurityException.ErrorCode.FAILED_CHECK, "invalidCert", e
+            );
+        } catch (CertificateNotYetValidException e) {
+            throw new WSSecurityException(
+                WSSecurityException.ErrorCode.FAILED_CHECK, "invalidCert", e
+            );
+        }
+    }
+    
+    /**
+     * Evaluate whether the given certificate chain should be trusted.
+     * 
+     * @param certificates the certificate chain that should be validated against the keystore
+     * @param crypto A Crypto instance
+     * @param data A RequestData instance
+     * @param enableRevocation Whether revocation is enabled or not
+     * @throws WSSecurityException if the certificate chain is not trusted
+     */
+    protected void verifyTrustInCerts(
+        X509Certificate[] certificates, 
+        Crypto crypto,
+        RequestData data,
+        boolean enableRevocation
+    ) throws WSSecurityException {
+        //
+        // Use the validation method from the crypto to check whether the subjects' 
+        // certificate was really signed by the issuer stated in the certificate
+        //
+        crypto.verifyTrust(certificates, enableRevocation, null);
+        if (LOG.isDebugEnabled()) {
+            String subjectString = certificates[0].getSubjectX500Principal().getName();
+            LOG.debug(
+                "Certificate path has been verified for certificate with subject " + subjectString
+            );
+        }
+    }
+    
+    /**
+     * Validate a public key
+     * @throws WSSecurityException
+     */
+    protected void validatePublicKey(PublicKey publicKey, Crypto crypto) 
+        throws WSSecurityException {
+        crypto.verifyTrust(publicKey);
+    }
+    
+    /**
+     * @return true if the certificate's SubjectDN matches the constraints
+     *         defined in the subject DNConstraints; false, otherwise. The
+     *         certificate subject DN only has to match ONE of the subject cert
+     *         constraints (not all).
+     */
+    public boolean matches(final java.security.cert.X509Certificate cert) {
+        if (!subjectDNPatterns.isEmpty()) {
+            if (cert == null) {
+                return false;
+            }
+            String subjectName = cert.getSubjectX500Principal().getName();
+            boolean subjectMatch = false;
+            for (Pattern subjectDNPattern : subjectDNPatterns) {
+                final Matcher matcher = subjectDNPattern.matcher(subjectName);
+                if (matcher.matches()) {
+                    subjectMatch = true;
+                    break;
+                }
+            }
+            if (!subjectMatch) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SAMLTokenValidator.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SAMLTokenValidator.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SAMLTokenValidator.java
index b468b5c..0b9b68a 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SAMLTokenValidator.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SAMLTokenValidator.java
@@ -42,7 +42,7 @@ import org.apache.cxf.fediz.core.config.TrustManager;
 import org.apache.cxf.fediz.core.config.TrustedIssuer;
 import org.apache.cxf.fediz.core.exception.ProcessingException;
 import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
-import org.apache.cxf.fediz.core.saml.SamlAssertionValidator.TRUST_TYPE;
+import org.apache.cxf.fediz.core.saml.FedizSignatureTrustValidator.TRUST_TYPE;
 import org.apache.wss4j.common.ext.WSSecurityException;
 import org.apache.wss4j.common.principal.SAMLTokenPrincipal;
 import org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl;
@@ -205,6 +205,7 @@ public class SAMLTokenValidator implements TokenValidator {
                     assertion.getId(), p.getName(), assertionIssuer, roles,
                     new ClaimCollection(claims), audience);
             response.setExpires(getExpires(assertion));
+            response.setCreated(getCreated(assertion));
             
             return response;
 
@@ -441,6 +442,20 @@ public class SAMLTokenValidator implements TokenValidator {
         return validTill.toDate();
     }
     
+    private Date getCreated(SamlAssertionWrapper assertion) {
+        DateTime validFrom = null;
+        if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)) {
+            validFrom = assertion.getSaml2().getConditions().getNotBefore();
+        } else {
+            validFrom = assertion.getSaml1().getConditions().getNotBefore();
+        }
+        
+        if (validFrom == null) {
+            return null;
+        }
+        return validFrom.toDate();
+    }
+    
     /**
      * Check the Conditions of the Assertion.
      */

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SamlAssertionValidator.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SamlAssertionValidator.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SamlAssertionValidator.java
index 24a6784..e72f021 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SamlAssertionValidator.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/saml/SamlAssertionValidator.java
@@ -19,19 +19,14 @@
 
 package org.apache.cxf.fediz.core.saml;
 
-
-import java.security.PublicKey;
-import java.security.cert.CertificateExpiredException;
-import java.security.cert.CertificateNotYetValidException;
-import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Date;
 import java.util.List;
-import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.regex.PatternSyntaxException;
 
+import org.apache.cxf.fediz.core.saml.FedizSignatureTrustValidator.TRUST_TYPE;
 import org.apache.wss4j.common.cache.ReplayCache;
 import org.apache.wss4j.common.crypto.Crypto;
 import org.apache.wss4j.common.ext.WSSecurityException;
@@ -57,8 +52,6 @@ public class SamlAssertionValidator implements Validator {
     
     private static final Logger LOG = LoggerFactory.getLogger(SamlAssertionValidator.class);
     
-    public enum TRUST_TYPE { CHAIN_TRUST, CHAIN_TRUST_CONSTRAINTS, PEER_TRUST }
-    
     /**
      * The time in seconds in the future within which the NotBefore time of an incoming 
      * Assertion is valid. The default is 60 seconds.
@@ -71,9 +64,6 @@ public class SamlAssertionValidator implements Validator {
      */
     private boolean validateSignatureAgainstProfile = true;
 
-    /**
-     * Defines the kind of trust which is required thus assertion signature validation is successful.
-     */
     private TRUST_TYPE signatureTrustType = TRUST_TYPE.CHAIN_TRUST;
         
     /**
@@ -180,97 +170,17 @@ public class SamlAssertionValidator implements Validator {
         credential.setPublicKey(samlKeyInfo.getPublicKey());
         credential.setCertificates(samlKeyInfo.getCerts());
         
-        X509Certificate[] certs = credential.getCertificates();
-        PublicKey publicKey = credential.getPublicKey();
-        Crypto crypto = getCrypto(data);
-        if (crypto == null) {
-            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "noSigCryptoFile");
-        }
+        FedizSignatureTrustValidator trustValidator = new FedizSignatureTrustValidator();
+        trustValidator.setSignatureTrustType(signatureTrustType);
+        trustValidator.setSubjectConstraints(subjectDNPatterns);
         
-        if (certs != null && certs.length > 0) {
-            validateCertificates(certs);
-            verifyTrustInCerts(certs, crypto, data, data.isRevocationEnabled());
-            if (signatureTrustType.equals(TRUST_TYPE.CHAIN_TRUST_CONSTRAINTS)) {
-                if (matches(certs[0])) {
-                    return credential;
-                } else {
-                    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
-                }
-            } else {
-                return credential;
-            }
-        }
-        if (publicKey != null) {
-            validatePublicKey(publicKey, crypto);
-            return credential;
-        }
-        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
+        return trustValidator.validate(credential, data);
     }
 
     protected Crypto getCrypto(RequestData data) {
         return data.getSigVerCrypto();
     }
 
-
-    /**
-     * Validate the certificates by checking the validity of each cert
-     * @throws WSSecurityException
-     */
-    protected void validateCertificates(X509Certificate[] certificates) 
-        throws WSSecurityException {
-        try {
-            for (int i = 0; i < certificates.length; i++) {
-                certificates[i].checkValidity();
-            }
-        } catch (CertificateExpiredException e) {
-            throw new WSSecurityException(
-                WSSecurityException.ErrorCode.FAILED_CHECK, "invalidCert", e
-            );
-        } catch (CertificateNotYetValidException e) {
-            throw new WSSecurityException(
-                WSSecurityException.ErrorCode.FAILED_CHECK, "invalidCert", e
-            );
-        }
-    }
-    
-    /**
-     * Evaluate whether the given certificate chain should be trusted.
-     * 
-     * @param certificates the certificate chain that should be validated against the keystore
-     * @param crypto A Crypto instance
-     * @param data A RequestData instance
-     * @param enableRevocation Whether revocation is enabled or not
-     * @throws WSSecurityException if the certificate chain is not trusted
-     */
-    protected void verifyTrustInCerts(
-        X509Certificate[] certificates, 
-        Crypto crypto,
-        RequestData data,
-        boolean enableRevocation
-    ) throws WSSecurityException {
-        //
-        // Use the validation method from the crypto to check whether the subjects' 
-        // certificate was really signed by the issuer stated in the certificate
-        //
-        crypto.verifyTrust(certificates, enableRevocation, null);
-        if (LOG.isDebugEnabled()) {
-            String subjectString = certificates[0].getSubjectX500Principal().getName();
-            LOG.debug(
-                "Certificate path has been verified for certificate with subject " + subjectString
-            );
-        }
-    }
-    
-    /**
-     * Validate a public key
-     * @throws WSSecurityException
-     */
-    protected void validatePublicKey(PublicKey publicKey, Crypto crypto) 
-        throws WSSecurityException {
-        crypto.verifyTrust(publicKey);
-    }
-    
-    
     /**
      * Check the Conditions of the Assertion.
      */
@@ -336,32 +246,4 @@ public class SamlAssertionValidator implements Validator {
         this.validateSignatureAgainstProfile = validateSignatureAgainstProfile;
     }
     
-    /**
-     * @return true if the certificate's SubjectDN matches the constraints
-     *         defined in the subject DNConstraints; false, otherwise. The
-     *         certificate subject DN only has to match ONE of the subject cert
-     *         constraints (not all).
-     */
-    public boolean matches(final java.security.cert.X509Certificate cert) {
-        if (!subjectDNPatterns.isEmpty()) {
-            if (cert == null) {
-                return false;
-            }
-            String subjectName = cert.getSubjectX500Principal().getName();
-            boolean subjectMatch = false;
-            for (Pattern subjectDNPattern : subjectDNPatterns) {
-                final Matcher matcher = subjectDNPattern.matcher(subjectName);
-                if (matcher.matches()) {
-                    subjectMatch = true;
-                    break;
-                }
-            }
-            if (!subjectMatch) {
-                return false;
-            }
-        }
-
-        return true;
-    }
-    
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/EHCacheSPStateManager.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/EHCacheSPStateManager.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/EHCacheSPStateManager.java
index 0daeb2a..4ec8f8e 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/EHCacheSPStateManager.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/EHCacheSPStateManager.java
@@ -41,7 +41,6 @@ public class EHCacheSPStateManager implements SPStateManager {
     public static final String RESPONSE_CACHE_KEY = "cxf.fediz.samlp.response.state.cache";
     
     private Ehcache requestCache;
-    private Ehcache responseCache;
     private CacheManager cacheManager;
     private long ttl = DEFAULT_TTL;
     
@@ -60,11 +59,6 @@ public class EHCacheSPStateManager implements SPStateManager {
 
         Ehcache newCache = new Cache(requestCC);
         requestCache = cacheManager.addCacheIfAbsent(newCache);
-        
-        CacheConfiguration responseCC = EHCacheManagerHolder.getCacheConfiguration(RESPONSE_CACHE_KEY, cacheManager);
-        
-        newCache = new Cache(responseCC);
-        responseCache = cacheManager.addCacheIfAbsent(newCache);
     }
     
     private static URL getConfigFileURL(Object o) {
@@ -100,44 +94,6 @@ public class EHCacheSPStateManager implements SPStateManager {
         return ttl;
     }
     
-    public ResponseState getResponseState(String securityContextKey) {
-        Element element = responseCache.get(securityContextKey);
-        if (element != null) {
-            if (responseCache.isExpired(element)) {
-                responseCache.remove(securityContextKey);
-                return null;
-            }
-            return (ResponseState)element.getObjectValue();
-        }
-        return null;
-    }
-
-    public ResponseState removeResponseState(String securityContextKey) {
-        Element element = responseCache.get(securityContextKey);
-        if (element != null) {
-            responseCache.remove(securityContextKey);
-            return (ResponseState)element.getObjectValue();
-        }
-        return null;
-    }
-
-    public void setResponseState(String securityContextKey, ResponseState state) {
-        if (securityContextKey == null || "".equals(securityContextKey)) {
-            return;
-        }
-        
-        int parsedTTL = (int)ttl;
-        if (ttl != (long)parsedTTL) {
-            // Fall back to 5 minutes if the default TTL is set incorrectly
-            parsedTTL = 60 * 5;
-        }
-        Element element = new Element(securityContextKey, state);
-        element.setTimeToLive(parsedTTL);
-        element.setTimeToIdle(parsedTTL);
-        
-        responseCache.put(element);
-    }
-    
     public void setRequestState(String relayState, RequestState state) {
         if (relayState == null || "".equals(relayState)) {
             return;
@@ -169,7 +125,6 @@ public class EHCacheSPStateManager implements SPStateManager {
             cacheManager.shutdown();
             cacheManager = null;
             requestCache = null;
-            responseCache = null;
         }
     }
 

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/ResponseState.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/ResponseState.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/ResponseState.java
deleted file mode 100644
index dfbf9ff..0000000
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/ResponseState.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.apache.cxf.fediz.core.samlsso;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement
-@XmlAccessorType(XmlAccessType.FIELD)
-public class ResponseState implements Serializable {
-
-    private static final long serialVersionUID = -3247188797004342462L;
-    
-    private String assertion;
-    private String relayState;
-    private String webAppContext;
-    private String webAppDomain;
-    private long createdAt;
-    private long expiresAt;
-    
-    public ResponseState() {
-        
-    }
-    
-    public ResponseState(String assertion,
-                         String relayState,
-                         String webAppContext,
-                         String webAppDomain,
-                         long createdAt, 
-                         long expiresAt) {
-        this.assertion = assertion;
-        this.relayState = relayState;
-        this.webAppContext = webAppContext;
-        this.webAppDomain = webAppDomain;
-        this.createdAt = createdAt;
-        this.expiresAt = expiresAt;
-    }
-
-    public long getCreatedAt() {
-        return createdAt;
-    }
-    
-    public long getExpiresAt() {
-        return expiresAt;
-    }
-
-    public String getRelayState() {
-        return relayState;
-    }
-    
-    public String getWebAppContext() {
-        return webAppContext;
-    }
-
-    public String getWebAppDomain() {
-        return webAppDomain;
-    }
-    
-    public String getAssertion() {
-        return assertion;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SAMLProtocolResponseValidator.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SAMLProtocolResponseValidator.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SAMLProtocolResponseValidator.java
index 2269aa4..d086aee 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SAMLProtocolResponseValidator.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SAMLProtocolResponseValidator.java
@@ -18,8 +18,16 @@
  */
 package org.apache.cxf.fediz.core.samlsso;
 
-import org.w3c.dom.Document;
+import java.util.Collections;
+import java.util.List;
 
+import org.w3c.dom.Document;
+import org.apache.cxf.fediz.core.config.CertificateValidationMethod;
+import org.apache.cxf.fediz.core.config.FedizContext;
+import org.apache.cxf.fediz.core.config.TrustManager;
+import org.apache.cxf.fediz.core.config.TrustedIssuer;
+import org.apache.cxf.fediz.core.saml.FedizSignatureTrustValidator;
+import org.apache.cxf.fediz.core.saml.FedizSignatureTrustValidator.TRUST_TYPE;
 import org.apache.wss4j.common.ext.WSSecurityException;
 import org.apache.wss4j.common.saml.SAMLKeyInfo;
 import org.apache.wss4j.common.saml.SAMLUtil;
@@ -27,6 +35,7 @@ import org.apache.wss4j.dom.WSDocInfo;
 import org.apache.wss4j.dom.WSSConfig;
 import org.apache.wss4j.dom.handler.RequestData;
 import org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor;
+import org.apache.wss4j.dom.validate.Credential;
 import org.opensaml.security.SAMLSignatureProfileValidator;
 import org.opensaml.xml.security.x509.BasicX509Credential;
 import org.opensaml.xml.signature.KeyInfo;
@@ -58,7 +67,8 @@ public class SAMLProtocolResponseValidator {
      * @throws WSSecurityException
      */
     public void validateSamlResponse(
-        org.opensaml.saml2.core.Response samlResponse
+        org.opensaml.saml2.core.Response samlResponse,
+        FedizContext config
     ) throws WSSecurityException {
         // Check the Status Code
         if (samlResponse.getStatus() == null
@@ -75,7 +85,7 @@ public class SAMLProtocolResponseValidator {
         }
         
         validateResponseAgainstSchemas(samlResponse);
-        validateResponseSignature(samlResponse);
+        validateResponseSignature(samlResponse, config);
     }
     
     /**
@@ -84,7 +94,8 @@ public class SAMLProtocolResponseValidator {
      * @throws WSSecurityException
      */
     public void validateSamlResponse(
-        org.opensaml.saml1.core.Response samlResponse
+        org.opensaml.saml1.core.Response samlResponse,
+        FedizContext config
     ) throws WSSecurityException {
         // Check the Status Code
         if (samlResponse.getStatus() == null
@@ -103,7 +114,7 @@ public class SAMLProtocolResponseValidator {
         }
 
         validateResponseAgainstSchemas(samlResponse);
-        validateResponseSignature(samlResponse);
+        validateResponseSignature(samlResponse, config);
     }
     
     /**
@@ -144,14 +155,15 @@ public class SAMLProtocolResponseValidator {
      * Validate the Response signature (if it exists)
      */
     private void validateResponseSignature(
-        org.opensaml.saml2.core.Response samlResponse
+        org.opensaml.saml2.core.Response samlResponse,
+        FedizContext config
     ) throws WSSecurityException {
         if (!samlResponse.isSigned()) {
             return;
         }
         
         validateResponseSignature(
-            samlResponse.getSignature(), samlResponse.getDOM().getOwnerDocument()
+            samlResponse.getSignature(), samlResponse.getDOM().getOwnerDocument(), config
         );
     }
     
@@ -159,14 +171,15 @@ public class SAMLProtocolResponseValidator {
      * Validate the Response signature (if it exists)
      */
     private void validateResponseSignature(
-        org.opensaml.saml1.core.Response samlResponse
+        org.opensaml.saml1.core.Response samlResponse,
+        FedizContext config
     ) throws WSSecurityException {
         if (!samlResponse.isSigned()) {
             return;
         }
         
         validateResponseSignature(
-            samlResponse.getSignature(), samlResponse.getDOM().getOwnerDocument()
+            samlResponse.getSignature(), samlResponse.getDOM().getOwnerDocument(), config
         );
     }
     
@@ -175,7 +188,8 @@ public class SAMLProtocolResponseValidator {
      */
     private void validateResponseSignature(
         Signature signature, 
-        Document doc
+        Document doc,
+        FedizContext config
     ) throws WSSecurityException {
         RequestData requestData = new RequestData();
         WSSConfig wssConfig = WSSConfig.getNewInstance();
@@ -205,17 +219,52 @@ public class SAMLProtocolResponseValidator {
         validateSignatureAgainstProfiles(signature, samlKeyInfo);
 
         // Now verify trust on the signature
-        /* TODO Credential trustCredential = new Credential();
+        Credential trustCredential = new Credential();
         trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
         trustCredential.setCertificates(samlKeyInfo.getCerts());
 
-        try {
-            signatureValidator.validate(trustCredential, requestData);
-        } catch (WSSecurityException e) {
-            LOG.debug("Error in validating signature on SAML Response: " + e.getMessage(), e);
-            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        FedizSignatureTrustValidator trustValidator = new FedizSignatureTrustValidator();
+        
+        boolean trusted = false;
+        
+        List<TrustedIssuer> trustedIssuers = config.getTrustedIssuers();
+        for (TrustedIssuer ti : trustedIssuers) {
+            List<String> subjectConstraints = Collections.singletonList(ti.getSubject());
+            if (ti.getCertificateValidationMethod().equals(CertificateValidationMethod.CHAIN_TRUST)) {
+                trustValidator.setSubjectConstraints(subjectConstraints);
+                trustValidator.setSignatureTrustType(TRUST_TYPE.CHAIN_TRUST_CONSTRAINTS);
+            } else if (ti.getCertificateValidationMethod().equals(CertificateValidationMethod.PEER_TRUST)) {
+                trustValidator.setSignatureTrustType(TRUST_TYPE.PEER_TRUST);
+            } else {
+                throw new IllegalStateException("Unsupported certificate validation method: " 
+                                                + ti.getCertificateValidationMethod());
+            }
+            try {
+                for (TrustManager tm: config.getCertificateStores()) {
+                    try {
+                        requestData.setSigVerCrypto(tm.getCrypto());
+                        trustValidator.validate(trustCredential, requestData);
+                        trusted = true;
+                        break;
+                    } catch (Exception ex) {
+                        LOG.debug("Issuer '{}' not validated in keystore '{}'",
+                                  ti.getName(), tm.getName());
+                    }
+                }
+                if (trusted) {
+                    break;
+                }
+                
+            } catch (Exception ex) {
+                LOG.info("Error in validating signature on SAML Response: " + ex.getMessage(), ex);
+                throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+            }
+        }
+        
+        if (!trusted) {
+            LOG.warn("SAML Response is not trusted");
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILED_AUTHENTICATION);
         }
-        */
     }
     
     /**

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SPStateManager.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SPStateManager.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SPStateManager.java
index d55dce0..d55c5d4 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SPStateManager.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/samlsso/SPStateManager.java
@@ -36,9 +36,5 @@ public interface SPStateManager extends Closeable {
     void setRequestState(String relayState, RequestState state);
     RequestState removeRequestState(String relayState);
     
-    void setResponseState(String contextKey, ResponseState state);
-    ResponseState getResponseState(String contextKey);
-    ResponseState removeResponseState(String contextKey);
-    
     void close() throws IOException;
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/core/src/main/resources/schemas/FedizConfig.xsd
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/resources/schemas/FedizConfig.xsd b/plugins/core/src/main/resources/schemas/FedizConfig.xsd
index 748b8a7..750ec31 100644
--- a/plugins/core/src/main/resources/schemas/FedizConfig.xsd
+++ b/plugins/core/src/main/resources/schemas/FedizConfig.xsd
@@ -93,7 +93,6 @@
 		<xs:complexContent>
 			<xs:extension base="protocolType">
 				<xs:sequence>
-					<xs:element ref="realm" />
 					<xs:element ref="authenticationType" />
 					<xs:element ref="homeRealm" />
 					<xs:element ref="freshness" />
@@ -101,7 +100,6 @@
 					<xs:element ref="request" />
 					<xs:element ref="signInQuery" />
 					<xs:element ref="claimTypesRequested" />
-					<xs:element ref="tokenValidators" />
 					<xs:element ref="applicationServiceURL" />
 				</xs:sequence>
 				<xs:attribute name="version" use="required" type="xs:string" />
@@ -118,7 +116,6 @@
 					<xs:element ref="webAppDomain" />
 					<xs:element ref="authnRequestBuilder"/>
 					<xs:element ref="stateManager"/>
-					<xs:element ref="tokenValidators" />
 				</xs:sequence>
 				<xs:attribute name="version" use="required" type="xs:string" />
 			</xs:extension>
@@ -141,6 +138,8 @@
 	        <xs:element ref="roleDelimiter" />
 	        <xs:element ref="roleURI" />
 	        <xs:element ref="issuer" />
+	        <xs:element ref="realm" />
+	        <xs:element ref="tokenValidators" />
 		</xs:sequence>
 	</xs:complexType>
  

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/jetty/src/main/java/org/apache/cxf/fediz/jetty/FederationAuthenticator.java
----------------------------------------------------------------------
diff --git a/plugins/jetty/src/main/java/org/apache/cxf/fediz/jetty/FederationAuthenticator.java b/plugins/jetty/src/main/java/org/apache/cxf/fediz/jetty/FederationAuthenticator.java
index ce23c0c..ebb40e3 100644
--- a/plugins/jetty/src/main/java/org/apache/cxf/fediz/jetty/FederationAuthenticator.java
+++ b/plugins/jetty/src/main/java/org/apache/cxf/fediz/jetty/FederationAuthenticator.java
@@ -196,6 +196,7 @@ public class FederationAuthenticator extends LoginAuthenticator {
                     wfReq.setAction(action);
                     wfReq.setResponseToken(responseToken);
                     wfReq.setState(request.getParameter("RelayState"));
+                    wfReq.setRequest(request);
 
                     X509Certificate certs[] = 
                         (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/spring/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/plugins/spring/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java b/plugins/spring/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java
index 3e20030..2c6d85b 100644
--- a/plugins/spring/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java
+++ b/plugins/spring/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java
@@ -52,6 +52,7 @@ public class FederationAuthenticationFilter extends AbstractAuthenticationProces
         wfReq.setAction(wa);
         wfReq.setResponseToken(responseToken);
         wfReq.setState(request.getParameter("RelayState"));
+        wfReq.setRequest(request);
         
         X509Certificate certs[] = 
             (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/spring2/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/plugins/spring2/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java b/plugins/spring2/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java
index 466f7c3..eeb7190 100644
--- a/plugins/spring2/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java
+++ b/plugins/spring2/src/main/java/org/apache/cxf/fediz/spring/web/FederationAuthenticationFilter.java
@@ -65,6 +65,7 @@ public class FederationAuthenticationFilter extends AbstractProcessingFilter {
         wfReq.setAction(wa);
         wfReq.setResponseToken(responseToken);
         wfReq.setState(request.getParameter("RelayState"));
+        wfReq.setRequest(request);
         
         X509Certificate certs[] = 
             (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e7c14fea/plugins/tomcat/src/main/java/org/apache/cxf/fediz/tomcat/FederationAuthenticator.java
----------------------------------------------------------------------
diff --git a/plugins/tomcat/src/main/java/org/apache/cxf/fediz/tomcat/FederationAuthenticator.java b/plugins/tomcat/src/main/java/org/apache/cxf/fediz/tomcat/FederationAuthenticator.java
index ce49565..719efc9 100644
--- a/plugins/tomcat/src/main/java/org/apache/cxf/fediz/tomcat/FederationAuthenticator.java
+++ b/plugins/tomcat/src/main/java/org/apache/cxf/fediz/tomcat/FederationAuthenticator.java
@@ -422,6 +422,7 @@ public class FederationAuthenticator extends FormAuthenticator {
                 wfReq.setAction(action);
                 wfReq.setResponseToken(responseToken);
                 wfReq.setState(request.getParameter("RelayState"));
+                wfReq.setRequest(request);
                 
                 X509Certificate certs[] = 
                     (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");