You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by jb...@apache.org on 2015/03/20 13:11:26 UTC

[01/12] cxf-fediz git commit: Plugin refactoring: Moving common code to core RequestHandler.

Repository: cxf-fediz
Updated Branches:
  refs/heads/master 76f00d5e3 -> fe8f240fd


Plugin refactoring: Moving common code to core RequestHandler.


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

Branch: refs/heads/master
Commit: 0f6a65debd2143339bdbea572b35ba94b2d8c368
Parents: 76f00d5
Author: Jan Bernhardt <jb...@talend.com>
Authored: Mon Mar 2 17:27:06 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:07 2015 +0100

----------------------------------------------------------------------
 .../cxf/fediz/core/handler/LogoutHandler.java   | 168 +++++++++++++++++++
 .../cxf/fediz/core/handler/RequestHandler.java  |  40 +++++
 .../cxf/fediz/core/handler/SigninHandler.java   | 103 ++++++++++++
 .../core/metadata/MetadataDocumentHandler.java  |  91 ++++++++++
 .../core/processor/FederationProcessorImpl.java |   6 +-
 .../core/federation/FederationRequestTest.java  |   1 +
 .../fediz/tomcat/FederationAuthenticator.java   | 158 +++--------------
 systests/tomcat7/pom.xml                        |   4 +-
 8 files changed, 430 insertions(+), 141 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0f6a65de/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java
new file mode 100644
index 0000000..d58de21
--- /dev/null
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java
@@ -0,0 +1,168 @@
+/**
+ * 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.handler;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+
+import javax.servlet.ServletOutputStream;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.w3c.dom.Element;
+
+import org.apache.cxf.fediz.core.FederationConstants;
+import org.apache.cxf.fediz.core.config.FedizContext;
+import org.apache.cxf.fediz.core.processor.FedizProcessor;
+import org.apache.cxf.fediz.core.processor.FedizProcessorFactory;
+import org.apache.cxf.fediz.core.processor.RedirectionResponse;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class LogoutHandler implements RequestHandler {
+
+    private static final Logger LOG = LoggerFactory.getLogger(LogoutHandler.class);
+    protected final FedizContext fedizConfig;
+    private final String servletContextPath;
+    private Element token;
+
+    public LogoutHandler(FedizContext fedConfig) {
+        this(fedConfig, "/");
+    }
+
+    public LogoutHandler(FedizContext fedConfig, String servletContextPath) {
+        this.fedizConfig = fedConfig;
+        this.servletContextPath = servletContextPath;
+    }
+
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        String wa = request.getParameter(FederationConstants.PARAM_ACTION);
+        if (FederationConstants.ACTION_SIGNOUT.equals(wa) || FederationConstants.ACTION_SIGNOUT_CLEANUP.equals(wa)) {
+            // Default WS-Federation logout action
+            return true;
+        }
+        //Check for custom logout URL
+        String logoutUrl = fedizConfig.getLogoutURL();
+        return logoutUrl != null && !logoutUrl.isEmpty() 
+            && servletContextPath != null && request.getRequestURI().equals(servletContextPath + logoutUrl);
+    }
+
+    @Override
+    public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
+        String wa = request.getParameter(FederationConstants.PARAM_ACTION);
+        if (FederationConstants.ACTION_SIGNOUT.equals(wa)) {
+            return signout(request, response);
+        } else if (FederationConstants.ACTION_SIGNOUT_CLEANUP.equals(wa)) {
+            return signoutCleanup(request, response);
+        } else {
+            return customLogout(request, response);
+        }
+    }
+    
+    protected boolean customLogout(HttpServletRequest request, HttpServletResponse response) {
+        LOG.info("Custom Logout URL was invoked.");
+        return signout(request, response);
+    }
+
+    protected boolean signoutCleanup(HttpServletRequest request, HttpServletResponse response) {
+        LOG.info("SignOutCleanup request found. Terminating user session.");
+        request.getSession().invalidate();
+        String wreply = request.getParameter(FederationConstants.PARAM_REPLY);
+        if (wreply != null && !wreply.isEmpty()) {
+            try {
+                LOG.debug("Redirecting user after logout to: {}", wreply);
+                response.sendRedirect(wreply);
+            } catch (IOException e) {
+                LOG.error("Error redirecting user after logout: {}", e.getMessage());
+            }
+        } else {
+            LOG.debug("No wreply parameter was set in logout action. Returning logout image");
+            writeLogoutImage(response);
+        }
+        return true;
+    }
+
+    public void setToken(Element token) {
+        this.token = token;
+    }
+
+    protected boolean signout(HttpServletRequest request, HttpServletResponse response) {
+        LOG.debug("SignOut request found. Redirecting to IDP...");
+        //TODO make direct cleanup (session termination) optional via configuration
+        try {
+            SamlAssertionWrapper assertionToken = null;
+            if (token != null) {
+                assertionToken = new SamlAssertionWrapper(token);
+            }
+            FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedizConfig.getProtocol());
+            RedirectionResponse redirectionResponse = wfProc.createSignOutRequest(request, assertionToken, fedizConfig);
+            String redirectURL = redirectionResponse.getRedirectionURL();
+            if (redirectURL != null) {
+                Map<String, String> headers = redirectionResponse.getHeaders();
+                if (!headers.isEmpty()) {
+                    for (String headerName : headers.keySet()) {
+                        response.addHeader(headerName, headers.get(headerName));
+                    }
+                }
+                response.sendRedirect(redirectURL);
+                return true;
+            } else {
+                LOG.warn("Failed to create SignOutRequest.");
+            }
+        } catch (Exception ex) {
+            LOG.warn("Failed to create SignOutRequest: " + ex.getMessage());
+            try {
+                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignOutRequest.");
+            } catch (IOException e) {
+                LOG.error("Failed to send error response: {}", e.getMessage());
+            }
+        }
+        return false;
+    }
+
+    protected void writeLogoutImage(HttpServletResponse response) {
+        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("logout.jpg");
+        if (inputStream == null) {
+            LOG.warn("Could not write logout.jpg");
+            return;
+        }
+        int read = 0;
+        byte[] buf = new byte[1024];
+        try {
+            response.setContentType("image/jpeg");
+            ServletOutputStream responseOutputStream = response.getOutputStream();
+            while ((read = inputStream.read(buf)) != -1) {
+                responseOutputStream.write(buf, 0, read);
+            }
+            responseOutputStream.flush();
+        } catch (IOException e) {
+            LOG.error("Could  not send logout image: {}", e.getMessage());
+        } finally {
+            try {
+                inputStream.close();
+            } catch (IOException e) {
+                // ignore
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0f6a65de/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java
new file mode 100644
index 0000000..cc15e59
--- /dev/null
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java
@@ -0,0 +1,40 @@
+/**
+ * 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.handler;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public interface RequestHandler {
+
+    /**
+     * @param request Check if handler can handle this given request
+     * @return Returns true if handler can handle provided request, otherwise handler returns false.
+     */
+    boolean canHandleRequest(HttpServletRequest request);
+
+    /**
+     * After ensuring that this Handler can handle the given request this method will do the actual handling.
+     *
+     * @param request Request to be handled.
+     * @param response Response to be populated.
+     * @return Returns true if request handling was successful.
+     */
+    boolean handleRequest(HttpServletRequest request, HttpServletResponse response);
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0f6a65de/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
new file mode 100644
index 0000000..e4cd349
--- /dev/null
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
@@ -0,0 +1,103 @@
+/**
+ * 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.handler;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.cxf.fediz.core.FederationConstants;
+import org.apache.cxf.fediz.core.SAMLSSOConstants;
+import org.apache.cxf.fediz.core.config.FederationProtocol;
+import org.apache.cxf.fediz.core.config.FedizContext;
+import org.apache.cxf.fediz.core.config.SAMLProtocol;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.processor.FederationProcessorImpl;
+import org.apache.cxf.fediz.core.processor.FedizProcessor;
+import org.apache.cxf.fediz.core.processor.FedizRequest;
+import org.apache.cxf.fediz.core.processor.FedizResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class SigninHandler implements RequestHandler {
+
+    private static final Logger LOG = LoggerFactory.getLogger(SigninHandler.class);
+    protected final FedizContext fedizConfig;
+
+    public SigninHandler(FedizContext fedConfig) {
+        this.fedizConfig = fedConfig;
+    }
+
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        return FederationConstants.ACTION_SIGNIN.equals(request.getParameter(FederationConstants.PARAM_ACTION));
+    }
+
+    @Override
+    public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
+        if (request.getMethod().equals("POST")) {
+            LOG.debug("Sign-In-Response received");
+            String wresult = request.getParameter(FederationConstants.PARAM_RESULT);
+            String wctx = request.getParameter(FederationConstants.PARAM_CONTEXT);
+            if (wresult != null && wctx != null) {
+                LOG.debug("Validating RSTR...");
+                // process and validate the token
+                try {
+                    processSigninRequest(request, response);
+                    LOG.info("RSTR validated successfully");
+                    resumeRequest();
+                    return true;
+                } catch (ProcessingException e) {
+                    LOG.error("RSTR validated failed.");
+                }
+            } else {
+                throw new RuntimeException("Missing required parameter [wctx or wresult]");
+            }
+        } else {
+            throw new RuntimeException("Incorrect method GET for Sign-In-Response");
+        }
+        return false;
+    }
+
+    public abstract void resumeRequest();
+    
+    public FedizResponse processSigninRequest(HttpServletRequest req, HttpServletResponse resp)
+        throws ProcessingException {
+        FedizRequest federationRequest = new FedizRequest();
+
+        String wa = req.getParameter(FederationConstants.PARAM_ACTION);
+        String responseToken = getResponseToken(req, fedizConfig);
+
+        federationRequest.setAction(wa);
+        federationRequest.setResponseToken(responseToken);
+        federationRequest.setState(req.getParameter("RelayState"));
+        federationRequest.setRequest(req);
+
+        FedizProcessor processor = new FederationProcessorImpl();
+        return processor.processRequest(federationRequest, fedizConfig);
+    }
+
+    public String getResponseToken(HttpServletRequest request, FedizContext fedConfig) {
+        if (fedConfig.getProtocol() instanceof FederationProtocol) {
+            return request.getParameter(FederationConstants.PARAM_RESULT);
+        } else if (fedConfig.getProtocol() instanceof SAMLProtocol) {
+            return request.getParameter(SAMLSSOConstants.SAML_RESPONSE);
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0f6a65de/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java
new file mode 100644
index 0000000..364bb22
--- /dev/null
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java
@@ -0,0 +1,91 @@
+/**
+ * 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.metadata;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.w3c.dom.Document;
+
+import org.apache.cxf.fediz.core.FederationConstants;
+import org.apache.cxf.fediz.core.SAMLSSOConstants;
+import org.apache.cxf.fediz.core.config.FederationProtocol;
+import org.apache.cxf.fediz.core.config.FedizContext;
+import org.apache.cxf.fediz.core.config.SAMLProtocol;
+import org.apache.cxf.fediz.core.handler.RequestHandler;
+import org.apache.cxf.fediz.core.processor.FedizProcessor;
+import org.apache.cxf.fediz.core.processor.FedizProcessorFactory;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class MetadataDocumentHandler implements RequestHandler {
+
+    private static final Logger LOG = LoggerFactory.getLogger(MetadataDocumentHandler.class);
+    protected final FedizContext fedizConfig;
+
+    public MetadataDocumentHandler(FedizContext fedConfig) {
+        this.fedizConfig = fedConfig;
+    }
+
+    public static String getMetadataURI(FedizContext fedConfig) {
+        if (fedConfig.getProtocol().getMetadataURI() != null) {
+            return fedConfig.getProtocol().getMetadataURI();
+        } else if (fedConfig.getProtocol() instanceof FederationProtocol) {
+            return FederationConstants.METADATA_PATH_URI;
+        } else if (fedConfig.getProtocol() instanceof SAMLProtocol) {
+            return SAMLSSOConstants.FEDIZ_SAML_METADATA_PATH_URI;
+        }
+        return FederationConstants.METADATA_PATH_URI;
+    }
+
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        return request.getRequestURL().indexOf(MetadataDocumentHandler.getMetadataURI(fedizConfig)) != -1;
+    }
+
+    @Override
+    public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
+        LOG.debug("Metadata document requested");
+        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedizConfig.getProtocol());
+        PrintWriter out = null;
+        try {
+            out = response.getWriter();
+            Document metadata = wfProc.getMetaData(request, fedizConfig);
+            out.write(DOM2Writer.nodeToString(metadata));
+            response.setContentType("text/xml");
+            return true;
+        } catch (Exception ex) {
+            LOG.error("Failed to get metadata document: {}", ex.getMessage());
+            try {
+                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            } catch (IOException e) {
+                LOG.error("Failed to send error response: {}", e.getMessage());
+            }
+            return false;
+        } finally {
+            if (out != null) {
+                out.close();
+            }
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0f6a65de/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 40c3a93..c98486c 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
@@ -495,7 +495,10 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             StringBuilder sb = new StringBuilder();
             sb.append(FederationConstants.PARAM_ACTION).append('=').append(FederationConstants.ACTION_SIGNOUT);
 
-            String logoutRedirectTo = config.getLogoutRedirectTo();
+            String logoutRedirectTo = request.getParameter(FederationConstants.PARAM_REPLY);
+            if (logoutRedirectTo != null && !logoutRedirectTo.isEmpty()) {
+                logoutRedirectTo = config.getLogoutRedirectTo();
+            }
             if (logoutRedirectTo != null && !logoutRedirectTo.isEmpty()) {
 
                 if (logoutRedirectTo.startsWith("/")) {
@@ -505,7 +508,6 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
                 }
 
                 LOG.debug("wreply=" + logoutRedirectTo);
-
                 sb.append('&').append(FederationConstants.PARAM_REPLY).append('=');
                 sb.append(URLEncoder.encode(logoutRedirectTo, "UTF-8"));
             }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0f6a65de/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java b/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
index 51596a7..ebcd3a6 100644
--- a/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
+++ b/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
@@ -145,6 +145,7 @@ public class FederationRequestTest {
         FedizContext config = getFederationConfigurator().getFedizContext("ROOT");
         
         HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
+        EasyMock.expect(req.getParameter(FederationConstants.PARAM_REPLY)).andReturn(null);
         EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL)).times(1, 2);
         EasyMock.expect(req.getContextPath()).andReturn(TEST_REQUEST_URI);
         EasyMock.replay(req);

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0f6a65de/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 4e7bae9..a365235 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
@@ -21,8 +21,6 @@ package org.apache.cxf.fediz.tomcat;
 
 import java.io.File;
 import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
 import java.security.Principal;
 import java.security.cert.X509Certificate;
 import java.util.Collections;
@@ -31,14 +29,12 @@ import java.util.List;
 import java.util.Map;
 
 import javax.servlet.ServletException;
-import javax.servlet.ServletOutputStream;
 import javax.servlet.ServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
 import javax.xml.bind.JAXBException;
 
-import org.w3c.dom.Document;
 import org.w3c.dom.Element;
+
 import org.apache.catalina.LifecycleException;
 import org.apache.catalina.Session;
 import org.apache.catalina.authenticator.Constants;
@@ -55,6 +51,9 @@ import org.apache.cxf.fediz.core.config.FedizConfigurator;
 import org.apache.cxf.fediz.core.config.FedizContext;
 import org.apache.cxf.fediz.core.config.SAMLProtocol;
 import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.handler.LogoutHandler;
+import org.apache.cxf.fediz.core.handler.RequestHandler;
+import org.apache.cxf.fediz.core.metadata.MetadataDocumentHandler;
 import org.apache.cxf.fediz.core.processor.FedizProcessor;
 import org.apache.cxf.fediz.core.processor.FedizProcessorFactory;
 import org.apache.cxf.fediz.core.processor.FedizRequest;
@@ -62,9 +61,6 @@ import org.apache.cxf.fediz.core.processor.FedizResponse;
 import org.apache.cxf.fediz.core.processor.RedirectionResponse;
 import org.apache.juli.logging.Log;
 import org.apache.juli.logging.LogFactory;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.wss4j.common.util.DOM2Writer;
 
 
 public class FederationAuthenticator extends FormAuthenticator {
@@ -192,72 +188,34 @@ public class FederationAuthenticator extends FormAuthenticator {
             contextName = "/";
         }
         FedizContext fedConfig = getContextConfiguration(contextName);
-        
-        if (request.getRequestURL().indexOf(FederationConstants.METADATA_PATH_URI) != -1
-            || request.getRequestURL().indexOf(getMetadataURI(fedConfig)) != -1) {
-            if (LOG.isInfoEnabled()) {
-                LOG.info("Metadata document requested");
-            }
-            response.setContentType("text/xml");
-            PrintWriter out = response.getWriter();
-            
-            FedizProcessor wfProc = 
-                FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
-            try {
-                Document metadata = wfProc.getMetaData(request, fedConfig);
-                out.write(DOM2Writer.nodeToString(metadata));
-                return;
-            } catch (Exception ex) {
-                LOG.error("Failed to get metadata document: " + ex.getMessage());
-                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-                return;
-            }            
+        RequestHandler mdHandler = new MetadataDocumentHandler(fedConfig);
+        if (mdHandler.canHandleRequest(request)) {
+            mdHandler.handleRequest(request, response);
+            return;
         }
 
-        String wa = request.getParameter(FederationConstants.PARAM_ACTION);
-        if (FederationConstants.ACTION_SIGNOUT_CLEANUP.equals(wa)) {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("SignOutCleanup request found");
-                LOG.debug("SignOutCleanup action...");
+        LogoutHandler logoutHandler = new LogoutHandler(fedConfig, contextName);
+        if (logoutHandler.canHandleRequest(request)) {
+            Element token = (Element)request.getSession().getAttribute(SECURITY_TOKEN);
+            logoutHandler.setToken(token);
+
+            //TODO: Check if this internal session cleanup is really needed
+            Session session = request.getSessionInternal();
+            // Cleanup session
+            if (session != null) {
+                session.removeNote(FEDERATION_NOTE);
+                session.setPrincipal(null);
             }
 
-            request.getSession().invalidate();
-            handleLogout(response.getOutputStream());
+            logoutHandler.handleRequest(request, response);
 
             return;
         }
         
         super.invoke(request, response);
-
-    }
-    
-    private void handleLogout(final ServletOutputStream responseOutputStream) throws IOException {
-        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("logout.jpg");
-        if (inputStream == null) {
-            LOG.warn("Could not write logout.jpg");
-            return;
-        }
-        int read = 0;
-        byte[] buf = new byte[1024];
-        while ((read = inputStream.read(buf)) != -1) {
-            responseOutputStream.write(buf, 0, read);
-        }
-        inputStream.close();
-        responseOutputStream.flush();
-    }
-    
-    private String getMetadataURI(FedizContext fedConfig) {
-        if (fedConfig.getProtocol().getMetadataURI() != null) {
-            return fedConfig.getProtocol().getMetadataURI();
-        } else if (fedConfig.getProtocol() instanceof FederationProtocol) {
-            return FederationConstants.METADATA_PATH_URI;
-        } else if (fedConfig.getProtocol() instanceof SAMLProtocol) {
-            return SAMLSSOConstants.FEDIZ_SAML_METADATA_PATH_URI;
-        }
-        
-        return FederationConstants.METADATA_PATH_URI;
     }
 
+
     //CHECKSTYLE:OFF
     @Override
     public boolean authenticate(Request request, HttpServletResponse response,
@@ -273,40 +231,6 @@ public class FederationAuthenticator extends FormAuthenticator {
         }
         FedizContext fedConfig = getContextConfiguration(contextName);
         
-        //logout
-        String logoutUrl = fedConfig.getLogoutURL();
-        if (logoutUrl != null && !logoutUrl.isEmpty()
-            && request.getRequestURI().equals(contextName + logoutUrl)) {
-            HttpSession httpSession = request.getSession(false);
-            if (httpSession != null) {
-                // Here the user is already logged in
-                session = request.getSessionInternal();
-                
-                Element token = 
-                    (Element)request.getSession().getAttribute(SECURITY_TOKEN);
-                
-                // Cleanup session
-                if (session != null) {
-                    session.removeNote(FEDERATION_NOTE);
-                    session.setPrincipal(null);
-                    request.getSession().removeAttribute(SECURITY_TOKEN);
-                }
-                httpSession.invalidate();
-
-                FedizProcessor wfProc = 
-                    FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
-                signOutRedirectToIssuer(request, response, token, wfProc);
-
-                return false;
-            } else {
-                // The user is already logged out
-                handleLogout(response.getOutputStream());
-
-                return false;
-            }
-        }
-
-
         // Have we already authenticated someone?
         Principal principal = request.getUserPrincipal();
         // String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
@@ -692,45 +616,5 @@ public class FederationAuthenticator extends FormAuthenticator {
         }
     }
 
-    protected void signOutRedirectToIssuer(Request request, HttpServletResponse response, 
-                                           Element token, FedizProcessor processor)
-            throws IOException {
 
-        String contextName = request.getServletContext().getContextPath();
-        if (contextName == null || contextName.isEmpty()) {
-            contextName = "/";
-        }
-        FedizContext fedCtx = this.configurator.getFedizContext(contextName);
-        try {
-            SamlAssertionWrapper assertionToken = null;
-            if (token != null) {
-                assertionToken = new SamlAssertionWrapper(token);
-            }
-            RedirectionResponse redirectionResponse = 
-                processor.createSignOutRequest(request, assertionToken, fedCtx);
-            String redirectURL = redirectionResponse.getRedirectionURL();
-            if (redirectURL != null) {
-                Map<String, String> headers = redirectionResponse.getHeaders();
-                if (!headers.isEmpty()) {
-                    for (String headerName : headers.keySet()) {
-                        response.addHeader(headerName, headers.get(headerName));
-                    }
-                }
-                
-                response.sendRedirect(redirectURL);
-            } else {
-                LOG.warn("Failed to create SignOutRequest.");
-                response.sendError(
-                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignOutRequest.");
-            }
-        } catch (ProcessingException ex) {
-            LOG.warn("Failed to create SignOutRequest: " + ex.getMessage());
-            response.sendError(
-                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignOutRequest.");
-        } catch (WSSecurityException ex) {
-            LOG.warn("Failed to create SignOutRequest: " + ex.getMessage());
-            response.sendError(
-                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignOutRequest.");
-        }
-    }
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0f6a65de/systests/tomcat7/pom.xml
----------------------------------------------------------------------
diff --git a/systests/tomcat7/pom.xml b/systests/tomcat7/pom.xml
index b96a516..c7b696b 100644
--- a/systests/tomcat7/pom.xml
+++ b/systests/tomcat7/pom.xml
@@ -215,8 +215,8 @@
                             <includes>
                                 <include>**/integrationtests/**</include>
                             </includes>
-                            <argLine>-Xms512m -Xmx1024m
-                                -XX:MaxPermSize=256m</argLine>
+                            <argLine>-Xms512m -Xmx1024m -XX:MaxPermSize=256m </argLine>
+                            <!--argLine>-Xms512m -Xmx1024m -XX:MaxPermSize=256m -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=y</argLine-->
                         </configuration>
                     </execution>
                     <execution>


[07/12] cxf-fediz git commit: Renamed Websphere Demo App

Posted by jb...@apache.org.
Renamed Websphere Demo App


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

Branch: refs/heads/master
Commit: aeacfac0f6c04197b90ccc23c53f2c3ee5891c7a
Parents: 5c2dfa6
Author: Jan Bernhardt <jb...@talend.com>
Authored: Mon Mar 9 16:31:16 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:45 2015 +0100

----------------------------------------------------------------------
 examples/websphereWebapp/pom.xml | 16 ++--------------
 plugins/websphere/pom.xml        |  1 +
 2 files changed, 3 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/aeacfac0/examples/websphereWebapp/pom.xml
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/pom.xml b/examples/websphereWebapp/pom.xml
index fc87cb0..9c71f01 100644
--- a/examples/websphereWebapp/pom.xml
+++ b/examples/websphereWebapp/pom.xml
@@ -27,8 +27,8 @@
     </parent>
 
     <groupId>org.apache.cxf.fediz.examples</groupId>
-    <artifactId>simpleWebapp</artifactId>
-    <name>Fediz Example: SimpleWebapp</name>
+    <artifactId>websphereWebapp</artifactId>
+    <name>Fediz Example: WebsphereWebapp</name>
     <packaging>war</packaging>
 
     <properties>
@@ -57,18 +57,6 @@
     </dependencies>
 
     <build>
-        <plugins>
-            <plugin><!--for mvn tomcat:deploy/:undeploy/:redeploy -->
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>tomcat-maven-plugin</artifactId>
-                <version>1.1</version>
-                <configuration>
-                    <server>myTomcat</server>
-                    <url>http://localhost:8080/manager/text</url>
-                    <path>/${project.build.finalName}</path>
-                </configuration>
-            </plugin>
-        </plugins>
         <!-- Name of the generated WAR file -->
         <finalName>fedizhelloworld</finalName>
     </build>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/aeacfac0/plugins/websphere/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/websphere/pom.xml b/plugins/websphere/pom.xml
index cbc36d4..5f88527 100644
--- a/plugins/websphere/pom.xml
+++ b/plugins/websphere/pom.xml
@@ -93,6 +93,7 @@
 			<groupId>org.slf4j</groupId>
 			<artifactId>slf4j-log4j12</artifactId>
 			<version>${slf4j.version}</version>
+            <scope>test</scope>
 		</dependency>
 
         <dependency>


[05/12] cxf-fediz git commit: Improved Servlet Filter for Websphere

Posted by jb...@apache.org.
Improved Servlet Filter for Websphere


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

Branch: refs/heads/master
Commit: ab0d1b0bcca914f1a24594118e93896880f61241
Parents: 29c9253
Author: Jan Bernhardt <jb...@talend.com>
Authored: Mon Mar 9 11:30:56 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:33 2015 +0100

----------------------------------------------------------------------
 .../src/main/webapp/WEB-INF/web.xml             |  7 --
 .../was/servlet/filter/FederationFilter.java    | 98 ++++++++++++++++++++
 .../filter/SecurityContextTTLChecker.java       |  8 +-
 3 files changed, 104 insertions(+), 9 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ab0d1b0b/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml b/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml
index 28d2a3a..a60f3a4 100644
--- a/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml
+++ b/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml
@@ -6,13 +6,6 @@
     <display-name>WS Federation Simple Web Application Example</display-name>
 
     <!-- Optional: Cache the security token in Thread Local Storage -->
-	<!-- 
-    <filter>
-        <filter-name>FederationFilter</filter-name>
-        <filter-class>org.apache.cxf.fediz.core.servlet.FederationFilter</filter-class>
-    </filter>
-	-->
-	
 	<filter>
         <filter-name>FederationFilter</filter-name>
         <filter-class>org.apache.cxf.fediz.was.servlet.filter.SecurityContextTTLChecker</filter-class>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ab0d1b0b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/FederationFilter.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/FederationFilter.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/FederationFilter.java
new file mode 100644
index 0000000..991fd91
--- /dev/null
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/FederationFilter.java
@@ -0,0 +1,98 @@
+/**
+ * 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.was.servlet.filter;
+
+import java.io.IOException;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.security.auth.Subject;
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServlet;
+
+import org.w3c.dom.Element;
+import com.ibm.websphere.security.WSSecurityException;
+import com.ibm.websphere.security.auth.WSSubject;
+
+import org.apache.cxf.fediz.core.SecurityTokenThreadLocal;
+import org.apache.cxf.fediz.core.processor.FedizResponse;
+import org.apache.cxf.fediz.was.Constants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Add security token to thread local
+ */
+public class FederationFilter extends HttpServlet implements Filter {
+    private static final Logger LOG = LoggerFactory.getLogger(FederationFilter.class);
+    private static final long serialVersionUID = 5732969318462358728L;
+
+    public FederationFilter() {
+        super();
+    }
+
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+    }
+
+    /*
+     * (non-Java-doc)
+     * @see javax.servlet.Filter#doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+     */
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
+        ServletException {
+        try {
+            Subject subject = WSSubject.getCallerSubject();
+            if (subject != null) {
+                FedizResponse fedResponse = getCachedFederationResponse(subject);
+                LOG.info("Security token found for user: {}", fedResponse.getUsername());
+                Element el = fedResponse.getToken();
+                if (el != null) {
+                    SecurityTokenThreadLocal.setToken(el);
+                    LOG.debug("Setting Security Token to SecurityTokenThreadLocal");
+                }
+            }
+            chain.doFilter(request, response);
+        } catch (WSSecurityException e) {
+            LOG.warn("No caller Subject/Principal found in request.");
+            chain.doFilter(request, response);
+        } finally {
+            SecurityTokenThreadLocal.setToken(null);
+        }
+    }
+
+    private FedizResponse getCachedFederationResponse(Subject subject) {
+        Iterator<?> i = subject.getPublicCredentials().iterator();
+        while (i.hasNext()) {
+            Object o = i.next();
+            if (o instanceof Hashtable) {
+                Map<?, ?> table = (Hashtable<?, ?>)o;
+                return (FedizResponse)table.get(Constants.SUBJECT_TOKEN_KEY);
+            }
+        }
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ab0d1b0b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
index 43efc6b..8ad301b 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
@@ -52,9 +52,9 @@ import org.slf4j.LoggerFactory;
  * A Servlet Filter that MUST be configured to match the '/*' request scheme on each Web Application
  * to enforce SAML assertion TimeToLive checking
  *
- * @deprecated  Not needed any longer since version 1.2.0
+ * Only needed if TAI Interceptor is not registered with option "beforeSSO=true". Otherwise use FederationFilter
+ * instead.
  */
-@Deprecated
 public class SecurityContextTTLChecker extends HttpServlet implements Filter {
     private static final Logger LOG = LoggerFactory.getLogger(SecurityContextTTLChecker.class);
     private static final long serialVersionUID = 5732969339258858728L;
@@ -69,6 +69,7 @@ public class SecurityContextTTLChecker extends HttpServlet implements Filter {
         super();
     }
 
+    @SuppressWarnings("deprecation")
     @Override
     public void init(ServletConfig config) throws ServletException {
         super.init(config);
@@ -80,6 +81,7 @@ public class SecurityContextTTLChecker extends HttpServlet implements Filter {
      * (non-Java-doc)
      * @see javax.servlet.Filter#doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      */
+    @Override
     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
         throws IOException, ServletException {
 
@@ -145,10 +147,12 @@ public class SecurityContextTTLChecker extends HttpServlet implements Filter {
      * (non-Java-doc)
      * @see javax.servlet.Filter#destroy()
      */
+    @SuppressWarnings("deprecation")
     public void destroy() {
         FedizInterceptor.deRegisterContext(contextPath);
     }
 
+    @SuppressWarnings("deprecation")
     @Override
     public void init(FilterConfig filterConfig) throws ServletException {
         contextPath = filterConfig.getServletContext().getContextPath();


[12/12] cxf-fediz git commit: [FEDIZ-109] SAML TTL validation for Tomcat

Posted by jb...@apache.org.
[FEDIZ-109] SAML TTL validation for Tomcat


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

Branch: refs/heads/master
Commit: fe8f240fd15a0237e16a4759a5fb8776de0420a2
Parents: 0e954ed
Author: Jan Bernhardt <jb...@talend.com>
Authored: Fri Mar 20 10:14:20 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Fri Mar 20 10:49:34 2015 +0100

----------------------------------------------------------------------
 .../fediz/tomcat/FederationAuthenticator.java   | 165 ++++++++-----------
 1 file changed, 70 insertions(+), 95 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/fe8f240f/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 a365235..daa7b84 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
@@ -52,15 +52,14 @@ import org.apache.cxf.fediz.core.config.FedizContext;
 import org.apache.cxf.fediz.core.config.SAMLProtocol;
 import org.apache.cxf.fediz.core.exception.ProcessingException;
 import org.apache.cxf.fediz.core.handler.LogoutHandler;
-import org.apache.cxf.fediz.core.handler.RequestHandler;
 import org.apache.cxf.fediz.core.metadata.MetadataDocumentHandler;
 import org.apache.cxf.fediz.core.processor.FedizProcessor;
 import org.apache.cxf.fediz.core.processor.FedizProcessorFactory;
 import org.apache.cxf.fediz.core.processor.FedizRequest;
 import org.apache.cxf.fediz.core.processor.FedizResponse;
 import org.apache.cxf.fediz.core.processor.RedirectionResponse;
-import org.apache.juli.logging.Log;
-import org.apache.juli.logging.LogFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 
 public class FederationAuthenticator extends FormAuthenticator {
@@ -75,13 +74,12 @@ public class FederationAuthenticator extends FormAuthenticator {
     protected static final String INFO = "org.apache.cxf.fediz.tomcat.WsFedAuthenticator/1.0";
     protected static final String TRUSTED_ISSUER = "org.apache.cxf.fediz.tomcat.TRUSTED_ISSUER";
 
-    private static final Log LOG = LogFactory.getLog(FormAuthenticator.class);
+    private static final Logger LOG = LoggerFactory.getLogger(FormAuthenticator.class);
 
     /**
      * Fediz Configuration file
      */
     protected String configFile;
-    protected boolean tokenExpirationValidation = true;
     protected String encoding = "UTF-8";
 
     private FedizConfigurator configurator;
@@ -114,14 +112,6 @@ public class FederationAuthenticator extends FormAuthenticator {
         this.encoding = encoding;
     }
     
-    public boolean isTokenExpirationValidation() {
-        return tokenExpirationValidation;
-    }
-
-    public void setTokenExpirationValidation(boolean tokenExpirationValidation) {
-        this.tokenExpirationValidation = tokenExpirationValidation;
-    }
-
     @Override
     protected synchronized void startInternal() throws LifecycleException {
 
@@ -188,7 +178,7 @@ public class FederationAuthenticator extends FormAuthenticator {
             contextName = "/";
         }
         FedizContext fedConfig = getContextConfiguration(contextName);
-        RequestHandler mdHandler = new MetadataDocumentHandler(fedConfig);
+        MetadataDocumentHandler mdHandler = new MetadataDocumentHandler(fedConfig);
         if (mdHandler.canHandleRequest(request)) {
             mdHandler.handleRequest(request, response);
             return;
@@ -216,6 +206,7 @@ public class FederationAuthenticator extends FormAuthenticator {
     }
 
 
+    //TODO Fix checkstyle errors
     //CHECKSTYLE:OFF
     @Override
     public boolean authenticate(Request request, HttpServletResponse response,
@@ -235,72 +226,28 @@ public class FederationAuthenticator extends FormAuthenticator {
         Principal principal = request.getUserPrincipal();
         // String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
         if (principal != null) {
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Already authenticated '" + principal.getName() + "'");
-            }
+            LOG.debug("Already authenticated '{}'", principal.getName());
+            
             // Associate the session with any existing SSO session
             /*
              * if (ssoId != null) associate(ssoId,
              * request.getSessionInternal(true));
              */
 
-            // Check whether security token still valid
-            session = request.getSessionInternal();
-            if (session == null) {
-                LOG.debug("Session should not be null after authentication");
+            if (fedConfig.isDetectExpiredTokens()) {
+                // Check whether security token still valid
+                return validateToken(request, response, fedConfig);
             } else {
-                FedizResponse wfRes = (FedizResponse)session.getNote(FEDERATION_NOTE);
-
-                Date tokenExpires = wfRes.getTokenExpires();
-                if (tokenExpires == null) {
-                    LOG.debug("Token doesn't expire");
-                    return true;
-                }
-                if (!this.tokenExpirationValidation) {
-                    LOG.debug("Token expiration not validated.");
-                    return true;
-                }
-
-                Date currentTime = new Date();
-                if (currentTime.after(wfRes.getTokenExpires())) {
-                    LOG.debug("Token already expired. Clean up and redirect");
-
-                    session.removeNote(FEDERATION_NOTE);
-                    session.setPrincipal(null);
-                    request.getSession().removeAttribute(SECURITY_TOKEN);
-
-                    if (LOG.isDebugEnabled()) {
-                        LOG.debug("Save request in session '"
-                                + session.getIdInternal() + "'");
-                    }
-                    try {
-                        saveRequest(request, session);
-                    } catch (IOException ioe) {
-                        LOG.debug("Request body too big to save during authentication");
-                        response.sendError(HttpServletResponse.SC_FORBIDDEN,
-                                sm.getString("authenticator.requestBodyTooBig"));
-                        return false;
-                    }
-                    
-                    FedizProcessor wfProc = 
-                        FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
-                    signInRedirectToIssuer(request, response, wfProc);
-
-                    return false;
-                }
+                LOG.debug("Token expiration not validated.");
+                return true;
             }
-
-            return true;
         }
 
         // Is this the re-submit of the original request URI after successful
         // authentication? If so, forward the *original* request instead.
         if (matchRequest(request)) {
             session = request.getSessionInternal(true);
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Restore request from session '"
-                        + session.getIdInternal() + "'");
-            }
+            LOG.debug("Restore request from session '{}'", session.getIdInternal());
             
             // Get principal from session, register, and then remove it
             principal = (Principal)session.getNote(Constants.FORM_PRINCIPAL_NOTE);
@@ -309,14 +256,11 @@ public class FederationAuthenticator extends FormAuthenticator {
             request.removeNote(Constants.FORM_PRINCIPAL_NOTE);
             
             if (restoreRequest(request, session)) {
-                if (LOG.isDebugEnabled()) {
-                    LOG.debug("Proceed to restored request");
-                }
+                LOG.debug("Proceed to restored request");
                 return true;
             } else {
-                if (LOG.isDebugEnabled()) {
-                    LOG.debug("Restore of original request failed");
-                }
+                // TODO Is a authentication failed result realy needed if no initial request can be restored? 
+                LOG.warn("Restore of original request failed");
                 response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                 return false;
             }
@@ -327,7 +271,6 @@ public class FederationAuthenticator extends FormAuthenticator {
          * MessageBytes uriMB = MessageBytes.newInstance(); CharChunk uriCC =
          * uriMB.getCharChunk(); uriCC.setLimit(-1);
          */
-        // String contextPath = request.getContextPath();
         String requestURI = request.getDecodedRequestURI();
 
         if (isSignInRequired(request, fedConfig)) {
@@ -365,18 +308,14 @@ public class FederationAuthenticator extends FormAuthenticator {
             }
 
             if (responseToken == null) {
-                if (LOG.isDebugEnabled()) {
-                    LOG.debug("SignIn request must contain a response token from the IdP");
-                }
+                LOG.debug("SignIn request must contain a response token from the IdP");
                 response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                 return false;
             } else {
                 request.getResponse().sendAcknowledgement();
                 // processSignInRequest
-                if (LOG.isDebugEnabled()) {
-                    LOG.debug("Process SignIn request");
-                    LOG.debug("token=\n" + responseToken);
-                }
+                LOG.debug("Process SignIn request");
+                LOG.debug("token=\n{}", responseToken);
                 
                 session = request.getSessionInternal();
                 RequestState requestState = (RequestState)session.getNote(REQUEST_STATE);
@@ -388,12 +327,12 @@ public class FederationAuthenticator extends FormAuthenticator {
                 wfReq.setRequest(request);
                 wfReq.setRequestState(requestState);
                 
-                X509Certificate certs[] = 
-                    (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");
+                X509Certificate certs[] = (X509Certificate[])request
+                    .getAttribute("javax.servlet.request.X509Certificate");
                 wfReq.setCerts(certs);
 
-                FedizProcessor wfProc = 
-                    FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
+                FedizProcessor wfProc = FedizProcessorFactory
+                    .newFedizProcessor(fedConfig.getProtocol());
                 try {
                     wfRes = wfProc.processRequest(wfReq, fedConfig);
                 } catch (ProcessingException ex) {
@@ -460,9 +399,7 @@ public class FederationAuthenticator extends FormAuthenticator {
         // HttpSessionAttributeListener
 
         if (session == null) {
-            if (containerLog.isDebugEnabled()) {
-                containerLog.debug("User took so long to log on the session expired");
-            }
+            containerLog.debug("User took so long to log on the session expired");
             if (landingPage == null) {
                 response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT,
                         sm.getString("authenticator.sessionExpired"));
@@ -499,9 +436,7 @@ public class FederationAuthenticator extends FormAuthenticator {
         // Redirect the user to the original request URI (which will cause
         // the original request to be restored)
         requestURI = savedRequestURL(session);
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Redirecting to original '" + requestURI + "'");
-        }
+        LOG.debug("Redirecting to original '{}", requestURI);
         if (requestURI == null) {
             if (landingPage == null) {
                 response.sendError(HttpServletResponse.SC_BAD_REQUEST,
@@ -522,6 +457,48 @@ public class FederationAuthenticator extends FormAuthenticator {
         }
         return false;
     }
+
+    protected boolean validateToken(Request request, HttpServletResponse response, FedizContext fedConfig)
+        throws IOException {
+        Session session;
+        session = request.getSessionInternal();
+        if (session != null) {
+
+            FedizResponse wfRes = (FedizResponse)session.getNote(FEDERATION_NOTE);
+            Date tokenExpires = wfRes.getTokenExpires();
+            if (tokenExpires == null) {
+                LOG.debug("Token doesn't expire");
+                return true;
+            }
+
+            Date currentTime = new Date();
+            if (!currentTime.after(wfRes.getTokenExpires())){ 
+                return true;
+            } else {
+                LOG.warn("Token already expired. Clean up and redirect");
+
+                session.removeNote(FEDERATION_NOTE);
+                session.setPrincipal(null);
+                request.getSession().removeAttribute(SECURITY_TOKEN);
+
+                LOG.debug("Save request in session '{}'", session.getIdInternal());
+                try {
+                    saveRequest(request, session);
+                } catch (IOException ioe) {
+                    LOG.debug("Request body too big to save during authentication");
+                    response.sendError(HttpServletResponse.SC_FORBIDDEN, 
+                                       sm.getString("authenticator.requestBodyTooBig"));
+                    return false;
+                }
+
+                FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());
+                signInRedirectToIssuer(request, response, wfProc);
+            } 
+        } else {
+            LOG.debug("Session should not be null after authentication");
+        }
+        return false;
+    }
     
     private boolean isSignInRequired(Request request, FedizContext fedConfig) {
         if (fedConfig.getProtocol() instanceof FederationProtocol
@@ -606,13 +583,11 @@ public class FederationAuthenticator extends FormAuthenticator {
                 response.sendRedirect(redirectURL);
             } else {
                 LOG.warn("Failed to create SignInRequest.");
-                response.sendError(
-                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest.");
+                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest.");
             }
         } catch (ProcessingException ex) {
-            LOG.warn("Failed to create SignInRequest: " + ex.getMessage());
-            response.sendError(
-                               HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest.");
+            LOG.warn("Failed to create SignInRequest: {}", ex.getMessage());
+            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest.");
         }
     }
 


[11/12] cxf-fediz git commit: [FEDIZ-105] SAML TTL validation for Websphere

Posted by jb...@apache.org.
[FEDIZ-105] SAML TTL validation for Websphere


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

Branch: refs/heads/master
Commit: 0e954ede17c54b88e6cafdfde155d74a6b37bec8
Parents: 545c90a
Author: Jan Bernhardt <jb...@talend.com>
Authored: Fri Mar 20 08:39:01 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Fri Mar 20 10:13:52 2015 +0100

----------------------------------------------------------------------
 .../cxf/fediz/core/config/FedizContext.java     |  8 ++++---
 .../core/processor/FederationProcessorImpl.java | 22 +++++++++---------
 .../cxf/fediz/core/processor/FedizResponse.java |  3 ++-
 .../core/federation/FederationRequestTest.java  |  1 +
 .../cxf/fediz/was/tai/FedizInterceptor.java     | 24 ++++++++++++++------
 5 files changed, 36 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0e954ede/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java
index 9e9d2ed..1084b96 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/config/FedizContext.java
@@ -62,7 +62,6 @@ public class FedizContext implements Closeable {
     
     private ContextConfig config;
 
-    private boolean detectExpiredTokens = true;
     private boolean detectReplayedTokens = true;
     private String relativePath;
     private ReplayCache replayCache;
@@ -74,6 +73,9 @@ public class FedizContext implements Closeable {
     
 
     public FedizContext(ContextConfig config) {
+        if (config == null) {
+            throw new IllegalArgumentException("ContextConfig cannot be null!");
+        }
         this.config = config;
         
     }
@@ -249,11 +251,11 @@ public class FedizContext implements Closeable {
 
 
     public boolean isDetectExpiredTokens() {
-        return detectExpiredTokens;
+        return config.isTokenExpirationValidation();
     }
     
     public void setDetectExpiredTokens(boolean detectExpiredTokens) {
-        this.detectExpiredTokens = detectExpiredTokens;
+        config.setTokenExpirationValidation(detectExpiredTokens);
     }
 
     

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0e954ede/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 faa7e6e..0fc6a15 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
@@ -562,17 +562,17 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
         
         if (homeRealm == null || homeRealm.isEmpty()) {
             // Check if home realm is set in configuration
-	        Object homeRealmObj = ((FederationProtocol)config.getProtocol()).getHomeRealm();
-	        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();
-	            }
-	        }
+            Object homeRealmObj = ((FederationProtocol)config.getProtocol()).getHomeRealm();
+            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;
     }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0e954ede/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizResponse.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizResponse.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizResponse.java
index b392ad2..e1a1e01 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizResponse.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/processor/FedizResponse.java
@@ -51,7 +51,8 @@ public class FedizResponse implements Serializable {
     private Date tokenExpires;
 
     //CHECKSTYLE:OFF
-    public FedizResponse(String username, String issuer, List<String> roles, List<Claim> claims, String audience, Date created, Date expires, Element token, String uniqueTokenId) {
+    public FedizResponse(String username, String issuer, List<String> roles, List<Claim> claims, String audience, 
+        Date created, Date expires, Element token, String uniqueTokenId) {
         this.username = username;
         this.issuer = issuer;
         this.roles = roles;

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0e954ede/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java b/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
index c9561dd..c5489d0 100644
--- a/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
+++ b/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
@@ -121,6 +121,7 @@ public class FederationRequestTest {
         HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
         EasyMock.expect(req.getParameter(FederationConstants.PARAM_HOME_REALM))
             .andReturn("urn:org:apache:cxf:fediz:idp:realm-A");
+        EasyMock.expect(req.getQueryString()).andReturn(null);
         EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL)).times(1, 2);
         EasyMock.expect(req.getContextPath()).andReturn(TEST_REQUEST_URI);
         EasyMock.replay(req);

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/0e954ede/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
index b58125e..6d8976c 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
@@ -211,6 +211,12 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         FedizContext fedCtx = getFederationContext(req);
 
         if (fedCtx != null) {
+
+            // Validate SAML token lifetime on each request?
+            if (fedCtx.isDetectExpiredTokens()) {
+                return true;
+            }
+
             // Handle Metadata Document requests
             MetadataDocumentHandler mddHandler = new MetadataDocumentHandler(fedCtx);
             if (mddHandler.canHandleRequest(req)) {
@@ -329,7 +335,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
                     HttpSession session = request.getSession(true);
                     RequestState requestState = (RequestState)session.getAttribute(wctx);
                     if (requestState != null && requestState.getTargetAddress() != null) {
-                        LOG.info("Redirecting request to {}", requestState.getTargetAddress());
+                        LOG.debug("Restore request to {}", requestState.getTargetAddress());
                         try {
                             response.sendRedirect(requestState.getTargetAddress());
                         } catch (IOException e) {
@@ -344,8 +350,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             }
 
             // Check if user was authenticated previously and token is still valid
-            // TODO validate SAML TTL
-            TAIResult taiResult = checkUserAuthentication(req);
+            TAIResult taiResult = checkUserAuthentication(req, fedCtx);
             if (taiResult != null) {
                 return taiResult;
             }
@@ -360,7 +365,8 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         }
     }
 
-    private TAIResult checkUserAuthentication(HttpServletRequest req) throws WebTrustAssociationFailedException {
+    private TAIResult checkUserAuthentication(HttpServletRequest req, FedizContext fedCtx)
+        throws WebTrustAssociationFailedException {
         TAIResult result = null;
         HttpSession session = req.getSession(false);
         if (session != null) {
@@ -368,10 +374,11 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             FedizResponse federationResponse = (FedizResponse)session
                 .getAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
             if (federationResponse != null) {
-                LOG.info("Security Token found in session for user: {}", federationResponse.getUsername());
+                LOG.debug("Security Token found in session for user: {}", federationResponse.getUsername());
 
                 // validate Security Token and create User Principal
                 if (checkSecurityToken(federationResponse)) {
+                    // TODO check if there is a better way to avoid recreation of subject each validated call
                     // proceed creating the JAAS Subject
                     List<String> groupsIds = groupIdsFromTokenRoles(federationResponse);
                     LOG.debug("Mapped group IDs: {}", groupsIds);
@@ -379,8 +386,11 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
 
                     result = TAIResult.create(HttpServletResponse.SC_OK, federationResponse.getUsername(), subject);
                 }
-                // Cleanup session
-                session.removeAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
+                if (!fedCtx.isDetectExpiredTokens()) {
+                    // token is not required for TTL validation
+                    // Cleanup session
+                    session.removeAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
+                }
             }
         }
         return result;


[10/12] cxf-fediz git commit: Fix loosing query parameters in requested URL

Posted by jb...@apache.org.
Fix loosing query parameters in requested URL


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

Branch: refs/heads/master
Commit: 545c90ac975c22baba41f63472e26b5fdb03100a
Parents: 06720e6
Author: Jan Bernhardt <jb...@talend.com>
Authored: Fri Mar 13 14:05:33 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:27:03 2015 +0100

----------------------------------------------------------------------
 .../core/processor/FederationProcessorImpl.java | 260 +++++++++----------
 .../core/federation/FederationRequestTest.java  |   1 +
 .../cxf/fediz/was/tai/FedizInterceptor.java     |   2 +-
 3 files changed, 127 insertions(+), 136 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/545c90ac/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 35a66ce..faa7e6e 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
@@ -91,10 +91,8 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
     }
 
     @Override
-    public FedizResponse processRequest(FedizRequest request,
-                                             FedizContext config)
-        throws ProcessingException {
-        
+    public FedizResponse processRequest(FedizRequest request, FedizContext config) throws ProcessingException {
+
         if (!(config.getProtocol() instanceof FederationProtocol)) {
             LOG.error("Unsupported protocol");
             throw new IllegalStateException("Unsupported protocol");
@@ -108,16 +106,13 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
         }
         return response;
     }
-    
 
     public Document getMetaData(HttpServletRequest request, FedizContext config) throws ProcessingException {
         return new MetadataWriter().getMetaData(request, config);
     }
-    
-    protected FedizResponse processSignInRequest(
-            FedizRequest request, FedizContext config)
-        throws ProcessingException {
-        
+
+    protected FedizResponse processSignInRequest(FedizRequest request, FedizContext config) throws ProcessingException {
+
         Document doc = null;
         Element el = null;
         try {
@@ -143,7 +138,7 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
 
         while (el != null) {
             String ln = el.getLocalName();
-            if (FederationConstants.WS_TRUST_13_NS.equals(el.getNamespaceURI()) 
+            if (FederationConstants.WS_TRUST_13_NS.equals(el.getNamespaceURI())
                 || FederationConstants.WS_TRUST_2005_02_NS.equals(el.getNamespaceURI())) {
                 if ("Lifetime".equals(ln)) {
                     lifetimeElem = el;
@@ -156,11 +151,15 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             el = DOMUtils.getNextElement(el);
         }
         if (LOG.isDebugEnabled()) {
-            LOG.debug("RST: " + ((rst != null) ? rst.toString() : "null"));
-            LOG.debug("Lifetime: "
-                    + ((lifetimeElem != null) ? lifetimeElem.toString()
-                            : "null"));
-            LOG.debug("Tokentype: " + ((tt != null) ? tt.toString() : "null"));
+            LOG.debug("RST: " + ((rst != null)
+                ? rst.toString()
+                : "null"));
+            LOG.debug("Lifetime: " + ((lifetimeElem != null)
+                ? lifetimeElem.toString()
+                : "null"));
+            LOG.debug("Tokentype: " + ((tt != null)
+                ? tt.toString()
+                : "null"));
         }
         if (rst == null) {
             LOG.warn("RequestedSecurityToken element not found in wresult");
@@ -185,18 +184,16 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
                 throw new ProcessingException(TYPE.TOKEN_INVALID);
             }
         }
-        
+
         // Check to see if RST is encrypted
-        if ("EncryptedData".equals(rst.getLocalName())
-            && WSConstants.ENC_NS.equals(rst.getNamespaceURI())) {
+        if ("EncryptedData".equals(rst.getLocalName()) && WSConstants.ENC_NS.equals(rst.getNamespaceURI())) {
             Element decryptedRST = decryptEncryptedRST(rst, config);
             if (decryptedRST != null) {
                 rst = decryptedRST;
             }
         }
-        
-        TokenValidatorResponse validatorResponse = 
-            validateToken(rst, tt, config, request.getCerts());
+
+        TokenValidatorResponse validatorResponse = validateToken(rst, tt, config, request.getCerts());
 
         // Check whether token already used for signin
         Date expires = null;
@@ -211,25 +208,17 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
         if (lifeTime != null && lifeTime.getCreated() != null) {
             created = lifeTime.getCreated();
         }
-        
-        FedizResponse fedResponse = new FedizResponse(
-                validatorResponse.getUsername(), validatorResponse.getIssuer(),
-                validatorResponse.getRoles(), validatorResponse.getClaims(),
-                validatorResponse.getAudience(),
-                created,
-                expires, 
-                rst,
-                validatorResponse.getUniqueTokenId());
+
+        FedizResponse fedResponse = new FedizResponse(validatorResponse.getUsername(), validatorResponse.getIssuer(),
+                                                      validatorResponse.getRoles(), validatorResponse.getClaims(),
+                                                      validatorResponse.getAudience(), created, expires, rst,
+                                                      validatorResponse.getUniqueTokenId());
 
         return fedResponse;
     }
-    
-    private TokenValidatorResponse validateToken(
-        Element token,
-        String tokenType,
-        FedizContext config,
-        Certificate[] certs
-    ) throws ProcessingException {
+
+    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) {
@@ -241,8 +230,7 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             }
             if (canHandle) {
                 try {
-                    TokenValidatorRequest validatorRequest = 
-                        new TokenValidatorRequest(token, certs);
+                    TokenValidatorRequest validatorRequest = new TokenValidatorRequest(token, certs);
                     validatorResponse = validator.validateAndProcessToken(validatorRequest, config);
                 } catch (ProcessingException ex) {
                     throw ex;
@@ -256,49 +244,41 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
                 throw new ProcessingException(TYPE.BAD_REQUEST);
             }
         }
-        
+
         return validatorResponse;
     }
-    
-    private Element decryptEncryptedRST(
-        Element encryptedRST,
-        FedizContext config
-    ) throws ProcessingException {
+
+    private Element decryptEncryptedRST(Element encryptedRST, FedizContext config) throws ProcessingException {
 
         KeyManager decryptionKeyManager = config.getDecryptionKey();
         if (decryptionKeyManager == null || decryptionKeyManager.getCrypto() == null) {
-            LOG.debug(
-                "We must have a decryption Crypto instance configured to decrypt encrypted tokens"
-            );
+            LOG.debug("We must have a decryption Crypto instance configured to decrypt encrypted tokens");
             throw new ProcessingException(TYPE.BAD_REQUEST);
         }
         String keyPassword = decryptionKeyManager.getKeyPassword();
         if (keyPassword == null) {
-            LOG.debug(
-                "We must have a decryption key password to decrypt encrypted tokens"
-            );
+            LOG.debug("We must have a decryption key password to decrypt encrypted tokens");
             throw new ProcessingException(TYPE.BAD_REQUEST);
         }
-        
+
         EncryptedDataProcessor proc = new EncryptedDataProcessor();
         WSDocInfo docInfo = new WSDocInfo(encryptedRST.getOwnerDocument());
         RequestData data = new RequestData();
-        
+
         // Disable WSS4J processing of the (decrypted) SAML Token
         WSSConfig wssConfig = WSSConfig.getNewInstance();
         wssConfig.setProcessor(WSSecurityEngine.SAML_TOKEN, new NOOpProcessor());
         wssConfig.setProcessor(WSSecurityEngine.SAML2_TOKEN, new NOOpProcessor());
         data.setWssConfig(wssConfig);
-        
+
         data.setDecCrypto(decryptionKeyManager.getCrypto());
         data.setCallbackHandler(new DecryptionCallbackHandler(keyPassword));
         try {
-            List<WSSecurityEngineResult> result =
-                proc.handleToken(encryptedRST, data, docInfo);
+            List<WSSecurityEngineResult> result = proc.handleToken(encryptedRST, data, docInfo);
             if (result.size() > 0) {
                 @SuppressWarnings("unchecked")
-                List<WSDataRef> dataRefs = 
-                    (List<WSDataRef>)result.get(result.size() - 1).get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
+                List<WSDataRef> dataRefs = (List<WSDataRef>)result.get(result.size() - 1)
+                    .get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
                 if (dataRefs != null && dataRefs.size() > 0) {
                     return dataRefs.get(0).getProtectedElement();
                 }
@@ -312,14 +292,14 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
 
     private LifeTime processLifeTime(Element lifetimeElem) throws ProcessingException {
         try {
-            Element createdElem = DOMUtils.getFirstChildWithName(lifetimeElem,
-                    WSConstants.WSU_NS, WSConstants.CREATED_LN);
+            Element createdElem = DOMUtils.getFirstChildWithName(lifetimeElem, WSConstants.WSU_NS,
+                                                                 WSConstants.CREATED_LN);
             DateFormat zulu = new XmlSchemaDateFormat();
 
             Date created = zulu.parse(DOMUtils.getContent(createdElem));
 
-            Element expiresElem = DOMUtils.getFirstChildWithName(lifetimeElem,
-                    WSConstants.WSU_NS, WSConstants.EXPIRES_LN);
+            Element expiresElem = DOMUtils.getFirstChildWithName(lifetimeElem, WSConstants.WSU_NS,
+                                                                 WSConstants.EXPIRES_LN);
             Date expires = zulu.parse(DOMUtils.getContent(expiresElem));
 
             return new LifeTime(created, expires);
@@ -361,40 +341,44 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
                 LOG.error("Unsupported protocol");
                 throw new IllegalStateException("Unsupported protocol");
             }
-            
+
             String issuerURL = resolveIssuer(request, config);
             LOG.debug("Issuer url: " + issuerURL);
             if (issuerURL != null && issuerURL.length() > 0) {
                 redirectURL = issuerURL;
             }
-            
+
             String wAuth = resolveAuthenticationType(request, config);
             LOG.debug("WAuth: " + wAuth);
-            
+
             String wReq = resolveRequest(request, config);
             LOG.debug("WReq: " + wReq);
-            
+
             String homeRealm = resolveHomeRealm(request, config);
             LOG.debug("HomeRealm: " + homeRealm);
-            
+
             String freshness = resolveFreshness(request, config);
             LOG.debug("Freshness: " + freshness);
-            
+
             String signInQuery = resolveSignInQuery(request, config);
             LOG.debug("SignIn Query: " + signInQuery);
-            
+
             String wctx = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
-            String requestURL = request.getRequestURL().toString();
-           
+            StringBuffer requestURL = request.getRequestURL();
+            String params = request.getQueryString();
+            if (params != null && !params.isEmpty()) {
+                requestURL.append("?").append(params);
+            }
+
             requestState = new RequestState();
-            requestState.setTargetAddress(requestURL);
+            requestState.setTargetAddress(requestURL.toString());
             requestState.setIdpServiceAddress(redirectURL);
             requestState.setState(wctx);
             requestState.setCreatedAt(System.currentTimeMillis());
 
             StringBuilder sb = new StringBuilder();
             sb.append(FederationConstants.PARAM_ACTION).append('=').append(FederationConstants.ACTION_SIGNIN);
-            
+
             String reply = ((FederationProtocol)config.getProtocol()).getReply();
             if (reply == null || reply.length() == 0) {
                 reply = request.getRequestURL().toString();
@@ -409,7 +393,7 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
                     }
                 }
             }
-            
+
             LOG.debug("wreply=" + reply);
             sb.append('&').append(FederationConstants.PARAM_REPLY).append('=');
             sb.append(URLEncoder.encode(reply, "UTF-8"));
@@ -417,56 +401,59 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             String realm = resolveWTRealm(request, config);
             LOG.debug("wtrealm=" + realm);
 
-            //add wtrealm parameter
-            sb.append('&').append(FederationConstants.PARAM_TREALM).append('=')
-                .append(URLEncoder.encode(realm, "UTF-8"));
-            
+            // add wtrealm parameter
+            sb.append('&').append(FederationConstants.PARAM_TREALM).append('=').append(URLEncoder
+                                                                                           .encode(realm, "UTF-8"));
+
             // add authentication type parameter wauth if set
             if (wAuth != null && wAuth.length() > 0) {
-                sb.append('&').append(FederationConstants.PARAM_AUTH_TYPE).append('=')
-                    .append(URLEncoder.encode(wAuth, "UTF-8"));
+                sb.append('&').append(FederationConstants.PARAM_AUTH_TYPE).append('=').append(URLEncoder
+                                                                                                  .encode(wAuth,
+                                                                                                          "UTF-8"));
             }
-            
+
             // add tokenRequest parameter wreq if set
             if (wReq != null && wReq.length() > 0) {
-                sb.append('&').append(FederationConstants.PARAM_REQUEST).append('=')
-                    .append(URLEncoder.encode(wReq, "UTF-8"));
+                sb.append('&').append(FederationConstants.PARAM_REQUEST).append('=').append(URLEncoder.encode(wReq,
+                                                                                                              "UTF-8"));
             }
-            
+
             // add home realm parameter whr if set
             if (homeRealm != null && homeRealm.length() > 0) {
-                sb.append('&').append(FederationConstants.PARAM_HOME_REALM).append('=')
-                    .append(URLEncoder.encode(homeRealm, "UTF-8"));
+                sb.append('&').append(FederationConstants.PARAM_HOME_REALM).append('=').append(URLEncoder
+                                                                                                   .encode(homeRealm,
+                                                                                                           "UTF-8"));
             }
-            
+
             // add freshness parameter wfresh if set
             if (freshness != null && freshness.length() > 0) {
-                sb.append('&').append(FederationConstants.PARAM_FRESHNESS).append('=')
-                    .append(URLEncoder.encode(freshness, "UTF-8"));
+                sb.append('&').append(FederationConstants.PARAM_FRESHNESS).append('=').append(URLEncoder
+                                                                                                  .encode(freshness,
+                                                                                                          "UTF-8"));
             }
-            
+
             // add current time parameter wct
             Date creationTime = new Date();
             XmlSchemaDateFormat fmt = new XmlSchemaDateFormat();
             String wct = fmt.format(creationTime);
             sb.append('&').append(FederationConstants.PARAM_CURRENT_TIME).append('=')
-            .append(URLEncoder.encode(wct, "UTF-8"));
-            
+                .append(URLEncoder.encode(wct, "UTF-8"));
+
             LOG.debug("wctx=" + wctx);
             sb.append('&').append(FederationConstants.PARAM_CONTEXT).append('=');
             sb.append(URLEncoder.encode(wctx, "UTF-8"));
-            
+
             // add signin query extensions
             if (signInQuery != null && signInQuery.length() > 0) {
                 sb.append('&').append(signInQuery);
             }
-            
+
             redirectURL = redirectURL + "?" + sb.toString();
         } catch (Exception ex) {
             LOG.error("Failed to create SignInRequest", ex);
             throw new ProcessingException("Failed to create SignInRequest");
         }
-        
+
         RedirectionResponse response = new RedirectionResponse();
         response.setRedirectionURL(redirectURL);
         response.setRequestState(requestState);
@@ -474,10 +461,8 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
     }
 
     @Override
-    public RedirectionResponse createSignOutRequest(HttpServletRequest request, 
-                                                    SamlAssertionWrapper token,
-                                                    FedizContext config)
-        throws ProcessingException {
+    public RedirectionResponse createSignOutRequest(HttpServletRequest request, SamlAssertionWrapper token,
+        FedizContext config) throws ProcessingException {
 
         String redirectURL = null;
         try {
@@ -517,14 +502,14 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             LOG.error("Failed to create SignInRequest", ex);
             throw new ProcessingException("Failed to create SignInRequest");
         }
-        
+
         RedirectionResponse response = new RedirectionResponse();
         response.setRedirectionURL(redirectURL);
         return response;
     }
 
-    private String resolveSignInQuery(HttpServletRequest request, FedizContext config)
-        throws IOException, UnsupportedCallbackException, UnsupportedEncodingException {
+    private String resolveSignInQuery(HttpServletRequest request, FedizContext config) throws IOException,
+        UnsupportedCallbackException, UnsupportedEncodingException {
         Object signInQueryObj = ((FederationProtocol)config.getProtocol()).getSignInQuery();
         String signInQuery = null;
         if (signInQueryObj != null) {
@@ -533,18 +518,19 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             } else if (signInQueryObj instanceof CallbackHandler) {
                 CallbackHandler frCB = (CallbackHandler)signInQueryObj;
                 SignInQueryCallback callback = new SignInQueryCallback(request);
-                frCB.handle(new Callback[] {callback});
+                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"));
+                    sbQuery.append(key).append('=').append(URLEncoder.encode(signInQueryMap.get(key), "UTF-8"));
                 }
                 signInQuery = sbQuery.toString();
-               
+
             }
         }
         return signInQuery;
@@ -560,7 +546,9 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             } else if (freshnessObj instanceof CallbackHandler) {
                 CallbackHandler frCB = (CallbackHandler)freshnessObj;
                 FreshnessCallback callback = new FreshnessCallback(request);
-                frCB.handle(new Callback[] {callback});
+                frCB.handle(new Callback[] {
+                    callback
+                });
                 freshness = callback.getFreshness();
             }
         }
@@ -574,25 +562,23 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
         
         if (homeRealm == null || homeRealm.isEmpty()) {
             // Check if home realm is set in configuration
-            Object homeRealmObj = ((FederationProtocol)config.getProtocol()).getHomeRealm();
-            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();
-                }
-            }
+	        Object homeRealmObj = ((FederationProtocol)config.getProtocol()).getHomeRealm();
+	        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 {
+    private String resolveAuthenticationType(HttpServletRequest request, FedizContext config) throws IOException,
+        UnsupportedCallbackException {
         Object wAuthObj = ((FederationProtocol)config.getProtocol()).getAuthenticationType();
         String wAuth = null;
         if (wAuthObj != null) {
@@ -601,15 +587,17 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             } else if (wAuthObj instanceof CallbackHandler) {
                 CallbackHandler wauthCB = (CallbackHandler)wAuthObj;
                 WAuthCallback callback = new WAuthCallback(request);
-                wauthCB.handle(new Callback[] {callback});
+                wauthCB.handle(new Callback[] {
+                    callback
+                });
                 wAuth = callback.getWauth();
-            }  
+            }
         }
         return wAuth;
     }
-    
-    private String resolveRequest(HttpServletRequest request, FedizContext config)
-        throws IOException, UnsupportedCallbackException {
+
+    private String resolveRequest(HttpServletRequest request, FedizContext config) throws IOException,
+        UnsupportedCallbackException {
         Object wReqObj = ((FederationProtocol)config.getProtocol()).getRequest();
         String wReq = null;
         if (wReqObj != null) {
@@ -618,17 +606,19 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             } else if (wReqObj instanceof CallbackHandler) {
                 CallbackHandler wauthCB = (CallbackHandler)wReqObj;
                 WReqCallback callback = new WReqCallback(request);
-                wauthCB.handle(new Callback[] {callback});
+                wauthCB.handle(new Callback[] {
+                    callback
+                });
                 wReq = callback.getWreq();
-            }  
+            }
         }
         return wReq;
     }
 
     private static class DecryptionCallbackHandler implements CallbackHandler {
-        
+
         private final String password;
-        
+
         public DecryptionCallbackHandler(String password) {
             this.password = password;
         }
@@ -637,14 +627,14 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
         public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
             for (int i = 0; i < callbacks.length; i++) {
                 if (callbacks[i] instanceof WSPasswordCallback) {
-                    WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
+                    WSPasswordCallback pc = (WSPasswordCallback)callbacks[i];
                     pc.setPassword(password);
                 } else {
                     throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
                 }
             }
         }
-        
+
     }
 
     private static class NOOpProcessor implements Processor {
@@ -654,7 +644,7 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             throws WSSecurityException {
             return new ArrayList<WSSecurityEngineResult>();
         }
-        
+
     }
 
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/545c90ac/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java b/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
index ebcd3a6..c9561dd 100644
--- a/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
+++ b/plugins/core/src/test/java/org/apache/cxf/fediz/core/federation/FederationRequestTest.java
@@ -97,6 +97,7 @@ public class FederationRequestTest {
         EasyMock.expect(req.getParameter(FederationConstants.PARAM_HOME_REALM)).andReturn(null);
         EasyMock.expect(req.getRequestURL()).andReturn(new StringBuffer(TEST_REQUEST_URL)).times(1, 2);
         EasyMock.expect(req.getContextPath()).andReturn(TEST_REQUEST_URI);
+        EasyMock.expect(req.getQueryString()).andReturn(null);
         EasyMock.replay(req);
         
         FedizProcessor wfProc = new FederationProcessorImpl();

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/545c90ac/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
index 1fb30a8..b58125e 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
@@ -226,7 +226,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             }
 
             // Handle Signin requests
-            SigninHandler signinHandler = new SigninHandler(fedCtx);
+            SigninHandler<TAIResult> signinHandler = new SigninHandler<TAIResult>(fedCtx);
             if (signinHandler.canHandleRequest(req)) {
                 LOG.debug("SignIn request detected");
                 return true;


[08/12] cxf-fediz git commit: Improve Logging

Posted by jb...@apache.org.
Improve Logging


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

Branch: refs/heads/master
Commit: d95850ec5dc779cbb66a6912b00d8c9eb89e82e6
Parents: aeacfac
Author: Jan Bernhardt <jb...@talend.com>
Authored: Mon Mar 9 17:39:23 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:51 2015 +0100

----------------------------------------------------------------------
 .../core/processor/FederationProcessorImpl.java | 14 +++----
 .../cxf/fediz/was/tai/FedizInterceptor.java     | 40 +++-----------------
 2 files changed, 12 insertions(+), 42 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d95850ec/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 c98486c..35a66ce 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
@@ -363,25 +363,25 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             }
             
             String issuerURL = resolveIssuer(request, config);
-            LOG.info("Issuer url: " + issuerURL);
+            LOG.debug("Issuer url: " + issuerURL);
             if (issuerURL != null && issuerURL.length() > 0) {
                 redirectURL = issuerURL;
             }
             
             String wAuth = resolveAuthenticationType(request, config);
-            LOG.info("WAuth: " + wAuth);
+            LOG.debug("WAuth: " + wAuth);
             
             String wReq = resolveRequest(request, config);
-            LOG.info("WReq: " + wReq);
+            LOG.debug("WReq: " + wReq);
             
             String homeRealm = resolveHomeRealm(request, config);
-            LOG.info("HomeRealm: " + homeRealm);
+            LOG.debug("HomeRealm: " + homeRealm);
             
             String freshness = resolveFreshness(request, config);
-            LOG.info("Freshness: " + freshness);
+            LOG.debug("Freshness: " + freshness);
             
             String signInQuery = resolveSignInQuery(request, config);
-            LOG.info("SignIn Query: " + signInQuery);
+            LOG.debug("SignIn Query: " + signInQuery);
             
             String wctx = URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
             String requestURL = request.getRequestURL().toString();
@@ -487,7 +487,7 @@ public class FederationProcessorImpl extends AbstractFedizProcessor {
             }
 
             String issuerURL = resolveIssuer(request, config);
-            LOG.info("Issuer url: " + issuerURL);
+            LOG.debug("Issuer url: " + issuerURL);
             if (issuerURL != null && issuerURL.length() > 0) {
                 redirectURL = issuerURL;
             }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/d95850ec/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
index 530c0bb..4707df3 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
@@ -23,7 +23,6 @@ import java.io.IOException;
 import java.rmi.RemoteException;
 import java.util.ArrayList;
 import java.util.Hashtable;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
@@ -38,10 +37,8 @@ import javax.servlet.http.HttpSession;
 import com.ibm.websphere.security.CustomRegistryException;
 import com.ibm.websphere.security.EntryNotFoundException;
 import com.ibm.websphere.security.UserRegistry;
-import com.ibm.websphere.security.WSSecurityException;
 import com.ibm.websphere.security.WebTrustAssociationException;
 import com.ibm.websphere.security.WebTrustAssociationFailedException;
-import com.ibm.websphere.security.auth.WSSubject;
 import com.ibm.wsspi.security.tai.TAIResult;
 import com.ibm.wsspi.security.tai.TrustAssociationInterceptor;
 import com.ibm.wsspi.security.token.AttributeNameConstants;
@@ -283,22 +280,9 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             }
 
             // Check if user was authenticated previously and token is still valid
-            String user = req.getRemoteUser();
-            String principal = WSSubject.getCallerPrincipal();
-            Subject subject = null;
-            try {
-                subject = WSSubject.getCallerSubject();
-            } catch (WSSecurityException e) {
-                LOG.error("Could not read subject");
-            }
-            LOG.info("Remote User: {}, Principal: {}, Subject {}", user, principal, subject);
-            if (principal != null && subject != null) {
-                // return TAIResult.create(HttpServletResponse.SC_OK, principal, subject);
-            } else {
-                TAIResult taiResult = checkUserAuthentication(req);
-                if (taiResult != null) {
-                    return taiResult;
-                }
+            TAIResult taiResult = checkUserAuthentication(req);
+            if (taiResult != null) {
+                return taiResult;
             }
 
             LOG.info("No Subject found in existing session. Redirecting to IDP");
@@ -321,17 +305,15 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             if (federationResponse != null) {
                 LOG.info("Security Token found in session: {}", federationResponse.getUsername());
 
-                // check that the target WebApp is properly configured for Token TTL enforcement
+                // validate Security Token and create User Principal
                 if (checkSecurityToken(federationResponse)) {
                     // proceed creating the JAAS Subject
-                    LOG.info("Security Filter properly configured - forwarding subject");
                     List<String> groupsIds = groupIdsFromTokenRoles(federationResponse);
+                    LOG.debug("Mapped group IDs: {}", groupsIds);
                     Subject subject = createSubject(federationResponse, groupsIds, session.getId());
 
                     result = TAIResult.create(HttpServletResponse.SC_OK, federationResponse.getUsername(), subject);
                 }
-                // leave the Session untouched
-                // session.removeAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
             }
         }
         return result;
@@ -368,18 +350,6 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         }
     }
 
-    protected FedizResponse getCachedFederationResponse(Subject subject) {
-        Iterator<?> i = subject.getPublicCredentials().iterator();
-        while (i.hasNext()) {
-            Object o = i.next();
-            if (o instanceof Hashtable) {
-                Map<?, ?> table = (Hashtable<?, ?>)o;
-                return (FedizResponse)table.get(Constants.SUBJECT_TOKEN_KEY);
-            }
-        }
-        return null;
-    }
-
     private boolean checkSecurityToken(FedizResponse response) {
         if (response == null) {
             return false;


[06/12] cxf-fediz git commit: Removing provided libs from assembled zip

Posted by jb...@apache.org.
Removing provided libs from assembled zip


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

Branch: refs/heads/master
Commit: 5c2dfa610d7dc07311bd1ca90cafc45d116754c4
Parents: ab0d1b0
Author: Jan Bernhardt <jb...@talend.com>
Authored: Mon Mar 9 14:14:44 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:39 2015 +0100

----------------------------------------------------------------------
 .../java/org/apache/cxf/fediz/example/FederationServlet.java   | 2 +-
 plugins/websphere/pom.xml                                      | 6 +++---
 2 files changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/5c2dfa61/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java b/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java
index a20910d..13029d9 100644
--- a/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java
+++ b/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java
@@ -86,7 +86,7 @@ public class FederationServlet extends HttpServlet {
                 out.println(c.getClaimType().toString() + ": " + c.getValue() + "<p>");
             }
         } else {
-            out.println("<p>Principal is not instance of FedizPrincipal");
+            out.println("<br>Principal is not instance of FedizPrincipal<p>");
         }
 
         Element el = SecurityTokenThreadLocal.getToken();

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/5c2dfa61/plugins/websphere/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/websphere/pom.xml b/plugins/websphere/pom.xml
index 7fbc88c..cbc36d4 100644
--- a/plugins/websphere/pom.xml
+++ b/plugins/websphere/pom.xml
@@ -67,21 +67,21 @@
 			<artifactId>com.ibm.websphere.security</artifactId>
 			<version>1.0.3</version>
 			<type>jar</type>
-			<scope>compile</scope>
+			<scope>provided</scope>
  		</dependency>
 		<dependency>
 			<groupId>com.ibm.ws.security</groupId>
 			<artifactId>com.ibm.ws.security.authentication.tai</artifactId>
 			<version>1.0.3</version>
 			<type>jar</type>
-			<scope>compile</scope>
+			<scope>provided</scope>
 		</dependency>
 		<dependency>
 			<groupId>com.ibm.ws.security</groupId>
 			<artifactId>com.ibm.ws.security.token</artifactId>
 			<version>1.0.2</version>
 			<type>jar</type>
-			<scope>compile</scope>
+			<scope>provided</scope>
 		</dependency>        
 
 		<dependency>


[03/12] cxf-fediz git commit: Improve SigninHandler

Posted by jb...@apache.org.
Improve SigninHandler


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

Branch: refs/heads/master
Commit: e615cf8fd3547175b6dab3147e3214f1ec56140d
Parents: ce7b4f1
Author: Jan Bernhardt <jb...@talend.com>
Authored: Thu Mar 5 08:59:20 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:20 2015 +0100

----------------------------------------------------------------------
 .../apache/cxf/fediz/core/handler/SigninHandler.java    | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/e615cf8f/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
index 54a6ab7..a8d214d 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
@@ -34,7 +34,11 @@ import org.apache.cxf.fediz.core.processor.FedizResponse;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public abstract class SigninHandler implements RequestHandler {
+/**
+ * It is recommended to extend this class and implement the resumeRequest method to continue invoking the originally
+ * requested website.
+ */
+public class SigninHandler implements RequestHandler {
 
     private static final Logger LOG = LoggerFactory.getLogger(SigninHandler.class);
     protected final FedizContext fedizConfig;
@@ -74,8 +78,10 @@ public abstract class SigninHandler implements RequestHandler {
         return false;
     }
 
-    public abstract void resumeRequest(HttpServletRequest request, HttpServletResponse response,
-        FedizResponse federationResponse);
+    public void resumeRequest(HttpServletRequest request, HttpServletResponse response,
+        FedizResponse federationResponse) {
+
+    }
 
     public FedizResponse processSigninRequest(HttpServletRequest req, HttpServletResponse resp)
         throws ProcessingException {


[04/12] cxf-fediz git commit: Improved Group Mapping, Renamed unreleased Constants

Posted by jb...@apache.org.
Improved Group Mapping, Renamed unreleased Constants


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

Branch: refs/heads/master
Commit: 29c9253617be481a439dc0b03a0ad489c1aad96e
Parents: e615cf8
Author: Jan Bernhardt <jb...@talend.com>
Authored: Fri Mar 6 19:31:32 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:26 2015 +0100

----------------------------------------------------------------------
 plugins/websphere/pom.xml                       |  7 ++
 .../org/apache/cxf/fediz/was/Constants.java     | 17 ++++-
 .../was/mapper/DefaultRoleToGroupMapper.java    | 36 ++++++++-
 .../was/mapper/FileBasedRoleToGroupMapper.java  | 24 +++---
 .../filter/SecurityContextTTLChecker.java       |  3 +
 .../cxf/fediz/was/tai/FedizInterceptor.java     | 66 ++++++++++------
 .../mapper/DefaultRoleToGroupMapperTest.java    | 79 ++++++++++++++++++++
 7 files changed, 191 insertions(+), 41 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/29c92536/plugins/websphere/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/websphere/pom.xml b/plugins/websphere/pom.xml
index 415c1ca..7fbc88c 100644
--- a/plugins/websphere/pom.xml
+++ b/plugins/websphere/pom.xml
@@ -94,6 +94,13 @@
 			<artifactId>slf4j-log4j12</artifactId>
 			<version>${slf4j.version}</version>
 		</dependency>
+
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>${junit.version}</version>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
     <build>
         <plugins>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/29c92536/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/Constants.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/Constants.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/Constants.java
index 00a1d33..4d3bd1f 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/Constants.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/Constants.java
@@ -37,7 +37,7 @@ public interface Constants {
     String SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY = "fediz.security.token";
 
     /**
-     * @deprecated Use FEDIZ_CONFIG_LOCATION instead.
+     * @deprecated Use PROPERTY_KEY_CONFIG_LOCATION instead.
      *
      * Using this property causes problems on Websphere 8.5. See https://issues.apache.org/jira/browse/FEDIZ-97 for more
      * details.
@@ -47,10 +47,10 @@ public interface Constants {
     /**
      * This constant contains the name for the property to discover the location of the fediz configuration file.
      */
-    String FEDIZ_CONFIG_LOCATION = "fedizConfigLocation";
+    String PROPERTY_KEY_CONFIG_LOCATION = "fedizConfigFileLocation";
 
     /**
-     * @deprecated Use FEDIZ_ROLE_MAPPER instead.
+     * @deprecated Use PROPERTY_KEY_ROLE_MAPPER instead.
      */
     @Deprecated
     String ROLE_GROUP_MAPPER = "role.group.mapper";
@@ -59,5 +59,14 @@ public interface Constants {
      * This constant contains the name for the property to discover the class-name which should be used for role to
      * group mappings.
      */
-    String FEDIZ_ROLE_MAPPER = "fedizRoleMapper";
+    String PROPERTY_KEY_ROLE_MAPPER = "roleMapper";
+
+    /**
+     * Usually the group name is mapped to the GroupUID by using the User Registry. In the WAS liberty profile there
+     * is no User Registry available via JNDI, thus the GroupUID mapping needs to take place directly in the
+     * Claim2Group Mapper. By using this interceptor property and setting the value to 'true' the UserRegistry will
+     * not be used to get the GroupUID but instead the GroupUID needs to be provided by the Claim2Group Mapper. The
+     * default value is set to 'false', thus the UserRegistry will be invoked.
+     */
+    String PROPERTY_KEY_DIRECT_GROUP_MAPPING = "directGroupMapping";
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/29c92536/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapper.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapper.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapper.java
index 3bd9c9b..5bbaac4 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapper.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapper.java
@@ -19,28 +19,56 @@
 
 package org.apache.cxf.fediz.was.mapper;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
 
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 /**
  *
  */
 public class DefaultRoleToGroupMapper implements RoleToGroupMapper {
 
-    
+    public static final String PROPERTY_KEY_ROLE_MAPPING_TEMPLATE = "roleMappingTemplate";
+
+    public static final String ROLE_MAPPING_PLACEHOLDER = "%roleName%";
+
+    public static final String DEFAULT_MAPPING_TEMPLATE = "group:defaultWIMFileBasedRealm/"
+                                                          + DefaultRoleToGroupMapper.ROLE_MAPPING_PLACEHOLDER;
+
+    private static final Logger LOG = LoggerFactory.getLogger(DefaultRoleToGroupMapper.class);
+
+    private String template;
+
     @Override
     public void cleanup() {
     }
 
-   
     @Override
     public List<String> groupsFromRoles(List<String> roles) {
-        return roles;
+        if (template == null || roles == null) {
+            return roles;
+        } else {
+            List<String> renamedRoles = new ArrayList<String>();
+            for (String role : roles) {
+                String renamedRole = template.replace(ROLE_MAPPING_PLACEHOLDER, role);
+                renamedRoles.add(renamedRole);
+                LOG.debug("Mapped role {} to {}", role, renamedRole);
+            }
+            return renamedRoles;
+        }
     }
 
-    
     @Override
     public void initialize(Properties properties) {
+        if (properties != null && properties.containsKey(PROPERTY_KEY_ROLE_MAPPING_TEMPLATE)) {
+            template = properties.getProperty(PROPERTY_KEY_ROLE_MAPPING_TEMPLATE);
+            LOG.info("Set RoleToGroup regex pattern: {}", template);
+        } else {
+            template = null;
+        }
     }
 
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/29c92536/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java
index 2ab406c..1bbd21a 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java
@@ -22,7 +22,12 @@ package org.apache.cxf.fediz.was.mapper;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
 
 import javax.xml.bind.JAXBContext;
 import javax.xml.bind.JAXBException;
@@ -44,22 +49,23 @@ public class FileBasedRoleToGroupMapper implements RoleToGroupMapper {
      * This constant contains the name for the property to discover the role mapping file refresh rate. The value of
      * this property contains the number of seconds to wait, before changes in the file are detected and applied.
      */
-    public static final String FEDIZ_ROLE_MAPPING_REFRESH_TIMEOUT = "fedizRoleMappingRefreshTimeout";
+    public static final String PROPERTY_KEY_ROLE_MAPPING_REFRESH_TIMEOUT = "roleMappingRefreshTimeout";
     /**
      * This constant contains the name for the property to discover the location of the role to group mapping file.
      */
-    public static final String FEDIZ_ROLE_MAPPING_LOCATION = "fedizRoleMappingLocation";
+    public static final String PROPERTY_KEY_ROLE_MAPPING_LOCATION = "roleMappingLocation";
 
     /**
-     * @deprecated Use FEDIZ_ROLE_MAPPING_REFRESH_TIMEOUT instead.
+     * @deprecated Use PROPERTY_KEY_ROLE_MAPPING_REFRESH_TIMEOUT instead.
      */
     @Deprecated
     private static final String REFRESH_TIMEOUT_PARAMETER = "groups.mapping.refresh.timeout";
     /**
-     * @deprecated Use FEDIZ_ROLE_MAPPING_LOCATION instead.
+     * @deprecated Use PROPERTY_KEY_ROLE_MAPPING_LOCATION instead.
      */
     @Deprecated
     private static final String MAPPING_FILE_PARAMETER = "groups.mapping.file";
+
     private static final String INITIALIZATION_THREAD_NAME = "ClaimGroupMapper";
 
     private static final Logger LOG = LoggerFactory.getLogger(FileBasedRoleToGroupMapper.class);
@@ -87,15 +93,15 @@ public class FileBasedRoleToGroupMapper implements RoleToGroupMapper {
     @Override
     public void initialize(Properties props) {
         if (props != null) {
-            String fileLocation = props.containsKey(FEDIZ_ROLE_MAPPING_LOCATION)
-                    ? props.getProperty(FEDIZ_ROLE_MAPPING_LOCATION)
+            String fileLocation = props.containsKey(PROPERTY_KEY_ROLE_MAPPING_LOCATION)
+                    ? props.getProperty(PROPERTY_KEY_ROLE_MAPPING_LOCATION)
                     : props.getProperty(MAPPING_FILE_PARAMETER);
             if (fileLocation != null) {
                 groupMappingFilename = fileLocation;
                 LOG.info("Mapping file set to {}", fileLocation);
             }
-            String timeout = props.containsKey(FEDIZ_ROLE_MAPPING_REFRESH_TIMEOUT)
-                    ? props.getProperty(FEDIZ_ROLE_MAPPING_REFRESH_TIMEOUT)
+            String timeout = props.containsKey(PROPERTY_KEY_ROLE_MAPPING_REFRESH_TIMEOUT)
+                    ? props.getProperty(PROPERTY_KEY_ROLE_MAPPING_REFRESH_TIMEOUT)
                     : props.getProperty(REFRESH_TIMEOUT_PARAMETER);
             if (timeout != null) {
                 refreshRateMillisec = Integer.parseInt(timeout) * 1000;

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/29c92536/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
index aa17e61..43efc6b 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
@@ -119,6 +119,9 @@ public class SecurityContextTTLChecker extends HttpServlet implements Filter {
     }
 
     private boolean checkSecurityToken(FedizResponse response) {
+        if (response == null) {
+            return false;
+        }
         long currentTime = System.currentTimeMillis();
         return response.getTokenExpires().getTime() > currentTime;
     }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/29c92536/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
index 3a30b2e..530c0bb 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
@@ -77,6 +77,11 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
     private FedizConfigurator configurator;
     private RoleToGroupMapper mapper;
 
+    /**
+     * @see org.apache.cxf.fediz.was.Constants#PROPERTY_KEY_DIRECT_GROUP_MAPPING
+     */
+    private boolean directGrouMapping;
+
     public String getConfigFile() {
         return configFile;
     }
@@ -144,8 +149,8 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         if (props != null) {
             try {
                 @SuppressWarnings("deprecation")
-                String roleGroupMapper = props.containsKey(Constants.FEDIZ_ROLE_MAPPER)
-                    ? props.getProperty(Constants.FEDIZ_ROLE_MAPPER)
+                String roleGroupMapper = props.containsKey(Constants.PROPERTY_KEY_ROLE_MAPPER)
+                    ? props.getProperty(Constants.PROPERTY_KEY_ROLE_MAPPER)
                     : props.getProperty(Constants.ROLE_GROUP_MAPPER);
                 if (roleGroupMapper != null && !roleGroupMapper.isEmpty()) {
                     try {
@@ -162,8 +167,8 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
                 }
 
                 @SuppressWarnings("deprecation")
-                String configFileLocation = props.containsKey(Constants.FEDIZ_CONFIG_LOCATION)
-                    ? props.getProperty(Constants.FEDIZ_CONFIG_LOCATION)
+                String configFileLocation = props.containsKey(Constants.PROPERTY_KEY_CONFIG_LOCATION)
+                    ? props.getProperty(Constants.PROPERTY_KEY_CONFIG_LOCATION)
                     : props.getProperty(Constants.CONFIGURATION_FILE_PARAMETER);
                 if (configFileLocation != null) {
                     LOG.debug("Configuration file location set to {}", configFileLocation);
@@ -175,8 +180,10 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
                     LOG.debug("Federation config loaded from path: {}", configFileLocation);
                 } else {
                     throw new WebTrustAssociationFailedException("Missing required initialization parameter "
-                                                                 + Constants.FEDIZ_CONFIG_LOCATION);
+                                                                 + Constants.PROPERTY_KEY_CONFIG_LOCATION);
                 }
+
+                directGrouMapping = Boolean.valueOf(props.getProperty(Constants.PROPERTY_KEY_DIRECT_GROUP_MAPPING));
             } catch (Throwable t) {
                 LOG.warn("Failed initializing TAI", t);
                 return 1;
@@ -374,6 +381,9 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
     }
 
     private boolean checkSecurityToken(FedizResponse response) {
+        if (response == null) {
+            return false;
+        }
         long currentTime = System.currentTimeMillis();
         return response.getTokenExpires().getTime() > currentTime;
     }
@@ -383,29 +393,37 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         List<String> localGroups = mapper.groupsFromRoles(federationResponse.getRoles());
         List<String> groupIds = new ArrayList<String>(localGroups.size());
 
-        InitialContext ctx = new InitialContext();
-        try {
-            UserRegistry reg = (UserRegistry)ctx.lookup(Constants.USER_REGISTRY_JNDI_NAME);
+        if (directGrouMapping) {
+            LOG.debug("Direct Group Mapping was set in interceptor. Thus UserRegistry will not be invoked to get "
+                      + "GrouUID");
+            groupIds.addAll(localGroups);
+        } else {
+            InitialContext ctx = new InitialContext();
+            try {
+                UserRegistry reg = (UserRegistry)ctx.lookup(Constants.USER_REGISTRY_JNDI_NAME);
 
-            if (localGroups != null) {
-                LOG.debug("Converting {} group names to uids", localGroups.size());
-                for (String localGroup : localGroups) {
-                    try {
-                        String guid = convertGroupNameToUniqueId(reg, localGroup);
-                        LOG.debug("Group '{}' maps to guid: {}", localGroup, guid);
-                        groupIds.add(guid);
-                    } catch (EntryNotFoundException e) {
-                        LOG.warn("Group entry could not be found in UserRegistry: {}", localGroup);
+                if (localGroups != null) {
+                    LOG.debug("Converting {} group names to uids", localGroups.size());
+                    for (String localGroup : localGroups) {
+                        try {
+                            String guid = convertGroupNameToUniqueId(reg, localGroup);
+                            LOG.debug("Group '{}' maps to guid: {}", localGroup, guid);
+                            groupIds.add(guid);
+                        } catch (EntryNotFoundException e) {
+                            LOG.warn("Group entry '{}' could not be found in UserRegistry for user '{}'", localGroup,
+                                     federationResponse.getUsername());
+                        }
                     }
                 }
+            } catch (NamingException ex) {
+                LOG.error("User Registry could not be loaded via JNDI context.");
+                LOG.warn("Since Group mapping failed no groups will be set for user '{}'", federationResponse
+                    .getUsername());
+                LOG.info("To switch to direct GroupUID Mapping without UserRegistry being involved set "
+                         + "fedizDirectGroupMapping=\"true\"  in TAI Interceptor properties.");
+            } finally {
+                ctx.close();
             }
-        } catch (NamingException ex) {
-            LOG.error("User Registry could not be loaded via JNDI context.");
-            LOG.warn("GroupIDs from mapping will be used instead of UserRegistry mapping for user: {}",
-                     federationResponse.getUsername());
-            groupIds.addAll(localGroups);
-        } finally {
-            ctx.close();
         }
         LOG.debug("Group list: {}", groupIds);
         return groupIds;

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/29c92536/plugins/websphere/src/test/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapperTest.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/test/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapperTest.java b/plugins/websphere/src/test/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapperTest.java
new file mode 100644
index 0000000..b16ac20
--- /dev/null
+++ b/plugins/websphere/src/test/java/org/apache/cxf/fediz/was/mapper/DefaultRoleToGroupMapperTest.java
@@ -0,0 +1,79 @@
+/**
+ * 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.was.mapper;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+/**
+ *
+ */
+public class DefaultRoleToGroupMapperTest {
+
+    @Test
+    public void testSimpleMapping() {
+        DefaultRoleToGroupMapper mapper = new DefaultRoleToGroupMapper();
+
+        List<String> result = mapper.groupsFromRoles(Arrays.asList("Role1", "Role2", "Role3"));
+        assertNotNull(result);
+        assertEquals(3, result.size());
+        assertEquals("Role1", result.get(0));
+        assertEquals("Role3", result.get(2));
+    }
+
+    @Test
+    public void testNullMapping() {
+        DefaultRoleToGroupMapper mapper = new DefaultRoleToGroupMapper();
+
+        List<String> result = mapper.groupsFromRoles(null);
+        assertNull(result);
+    }
+
+    @Test
+    public void testEmptyMapping() {
+        DefaultRoleToGroupMapper mapper = new DefaultRoleToGroupMapper();
+
+        List<String> result = mapper.groupsFromRoles(new ArrayList<String>());
+        assertNotNull(result);
+        assertEquals(0, result.size());
+    }
+
+    @Test
+    public void testTemplateMapping() {
+        DefaultRoleToGroupMapper mapper = new DefaultRoleToGroupMapper();
+        Properties props = new Properties();
+        props.put(DefaultRoleToGroupMapper.PROPERTY_KEY_ROLE_MAPPING_TEMPLATE,
+                  DefaultRoleToGroupMapper.DEFAULT_MAPPING_TEMPLATE);
+        mapper.initialize(props);
+
+        List<String> result = mapper.groupsFromRoles(Arrays.asList("Role1", "Role2", "Role3"));
+        assertNotNull(result);
+        assertEquals(3, result.size());
+        assertEquals("group:defaultWIMFileBasedRealm/Role1", result.get(0));
+    }
+}


[02/12] cxf-fediz git commit: Improving Websphere Plugin: * Using core handler * Improve ExceptionHandling for Group Mappings * Added WAS 8.5 Liberty Support * Added WAS HelloWorld Example

Posted by jb...@apache.org.
Improving Websphere Plugin:
 * Using core handler
 * Improve ExceptionHandling for Group Mappings
 * Added WAS 8.5 Liberty Support
 * Added WAS HelloWorld Example


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

Branch: refs/heads/master
Commit: ce7b4f1ae15e688486dcfaca1683e4d63cb47970
Parents: 0f6a65d
Author: Jan Bernhardt <jb...@talend.com>
Authored: Mon Mar 2 19:45:48 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:13 2015 +0100

----------------------------------------------------------------------
 examples/websphereWebapp/README.txt             | 104 ++++++++
 examples/websphereWebapp/pom.xml                |  76 ++++++
 .../src/main/config/fediz_config.xml            |  36 +++
 .../cxf/fediz/example/FederationServlet.java    | 115 +++++++++
 .../src/main/resources/log4j.properties         |  17 ++
 .../src/main/resources/logging.properties       |  53 ++++
 .../src/main/webapp/META-INF/context.xml        |   3 +
 .../src/main/webapp/WEB-INF/web.xml             | 105 ++++++++
 .../websphereWebapp/src/main/webapp/index.html  |  25 ++
 .../src/main/webapp/secure/test.html            |  25 ++
 .../cxf/fediz/core/handler/SigninHandler.java   |   9 +-
 .../filter/SecurityContextTTLChecker.java       |   5 +-
 .../cxf/fediz/was/tai/FedizInterceptor.java     | 247 +++++++++----------
 13 files changed, 687 insertions(+), 133 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/README.txt
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/README.txt b/examples/websphereWebapp/README.txt
new file mode 100644
index 0000000..12ac9d9
--- /dev/null
+++ b/examples/websphereWebapp/README.txt
@@ -0,0 +1,104 @@
+Simple Web Application Demo
+===========================
+
+This demo shows how to build and deploy an SSO protected using Apache CXF Fediz
+web application.
+
+Running this sample consists of four steps:
+
+- Configure the Tomcat-IDP and Tomcat or Jetty-RP instances
+- Building the demo using Maven
+- Deploying the demo to the RP instance
+- Testing the demo
+
+Please review the README in the samples main directory before continuing.
+
+Configure the Tomcat-IDP
+------------------------
+Make sure the separate Tomcat instance hosting the Fediz IDP and IDP
+STS has been configured and is running as described here:  
+http://cxf.apache.org/fediz-idp.html.  Confirm the STS is active by
+checking that the WSDL is viewable from the browser using the URL given
+on that page--don't proceed further unless it is.
+
+
+a) Configure the Tomcat-RP instance
+-----------------------------------
+Tomcat installation holding the relying parties (the demo Web application
+for this sample) must be configured properly before applications can be
+deployed to it.  See this wiki page for instructions:
+http://cxf.apache.org/fediz-tomcat.html -- the "Installation" and "HTTPS
+Configuration" sections are the only parts that need configuration for this
+sample. 
+
+b) Configure the Jetty-RP instance
+----------------------------------
+Jetty installation holding the relying parties (the demo Web application
+for this sample) must be configured properly before applications can be
+deployed to it.  See this wiki page for instructions:
+http://cxf.apache.org/fediz-jetty.html -- the "Installation" and "HTTPS
+Configuration" sections are the only parts that need configuration for this
+sample. 
+
+Demo Web Application
+---------------------
+The main code lives in the class FederationServlet. This Servlet is protected
+and can be accessed only if the browser user is authenticated. The purpose of
+the FederationServlet is to illustrate the usage of the Java Servlet Security
+API to get the authenticated user and to check the roles he has. Further, 
+the FederationServlet shows how to access claims data (user data) which were 
+stored in the SAML token by using the Fediz interface FederationPrincipal.
+Beyond that, the FederationServlet illustrates how to access the SAML token
+if required. The classes SecurityTokenThreadLocal.java and FederationFilter.java
+can be used to achieve that. You could get this information directly from the
+HTTP session.
+
+
+Building the demo using Maven
+-----------------------------
+From the base directory of this sample (i.e., where this README file is
+located), the pom.xml file is used to build and run the demo. From a 
+command prompt, enter:
+
+  mvn clean install   (builds the demo and creates a WAR file for Servlet deployment)
+
+
+a) Deploying the demo to Tomcat
+-------------------------------
+First copy this sample's Fediz Configuration file (src/main/config/fediz_config.xml)
+into the Tomcat-RP's conf folder.  This configuration references the 
+Java keystore 'rp-ssl-server.jks' available in Fediz' examples/samplekeys folder 
+but should already be in the Tomcat RP's root folder when you configured this
+instance as stated in the prerequisites.
+
+Then, either manually copy this sample's generated WAR file to the Tomcat-RP's 
+webapps folder, or use the Tomcat Maven Plugin as described in the README file 
+in the example folder root.
+
+b) Deploying the demo to Jetty
+------------------------------
+First copy this sample's Fediz Configuration file (src/main/config/fediz_config.xml)
+into the Jetty-RP's etc folder.  This configuration references the 
+Java keystore 'rp-ssl-server.jks' available in Fediz' examples/samplekeys folder 
+but should already be in the Jetty RP's root folder when you configured this
+instance as stated in the prerequisites.
+
+Then, either manually copy this sample's generated WAR file to the Jetty-RP's 
+webapps folder, or use the Jetty Maven Plugin as described in the README file 
+in the example folder root.
+
+
+Test the demo
+-------------
+Enter the following URL into the browser (TCP port depends on your HTTP settings):
+
+https://localhost:8443/fedizhelloworld/secure/fedservlet
+
+The browser is redirected to the IDP and prompts for username and password. As described
+in the IDP installation, the following users are already set up:
+
+User: alice   Password: ecila
+User: bob     Password: bob
+User: ted     Password: det
+
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/pom.xml
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/pom.xml b/examples/websphereWebapp/pom.xml
new file mode 100644
index 0000000..fc87cb0
--- /dev/null
+++ b/examples/websphereWebapp/pom.xml
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.apache.cxf.fediz</groupId>
+        <artifactId>examples</artifactId>
+        <version>1.2.0-SNAPSHOT</version>
+    </parent>
+
+    <groupId>org.apache.cxf.fediz.examples</groupId>
+    <artifactId>simpleWebapp</artifactId>
+    <name>Fediz Example: SimpleWebapp</name>
+    <packaging>war</packaging>
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>servlet-api</artifactId>
+            <version>${servlet.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <!-- Required to cast Principal to FederationPrincipal -->
+        <dependency>
+            <groupId>org.apache.cxf.fediz</groupId>
+            <artifactId>fediz-core</artifactId>
+            <version>${project.version}</version>
+            <scope>provided</scope>             
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+            <version>${commons.lang.version}</version>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin><!--for mvn tomcat:deploy/:undeploy/:redeploy -->
+                <groupId>org.codehaus.mojo</groupId>
+                <artifactId>tomcat-maven-plugin</artifactId>
+                <version>1.1</version>
+                <configuration>
+                    <server>myTomcat</server>
+                    <url>http://localhost:8080/manager/text</url>
+                    <path>/${project.build.finalName}</path>
+                </configuration>
+            </plugin>
+        </plugins>
+        <!-- Name of the generated WAR file -->
+        <finalName>fedizhelloworld</finalName>
+    </build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/src/main/config/fediz_config.xml
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/config/fediz_config.xml b/examples/websphereWebapp/src/main/config/fediz_config.xml
new file mode 100644
index 0000000..b52f302
--- /dev/null
+++ b/examples/websphereWebapp/src/main/config/fediz_config.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Place in Tomcat conf folder or other location as designated in this sample's file. 
+     Keystore referenced below must have IDP STS' public cert included in it.  This example uses the
+     ststrust Truststore (ststrust.jks) for this task.
+     In Fediz 1.0, one keystore was used for SSL and the STS public certificate.
+-->
+<FedizConfig>
+	<contextConfig name="/fedizhelloworld">
+		<audienceUris>
+			<audienceItem>urn:org:apache:cxf:fediz:fedizhelloworld</audienceItem>
+		</audienceUris>
+		<certificateStores>
+			<trustManager>
+				<keyStore file="ststrust.jks" password="storepass" type="JKS" />
+			</trustManager>
+		</certificateStores>
+		<trustedIssuers>
+			<issuer certificateValidation="PeerTrust" />
+		</trustedIssuers>
+		<maximumClockSkew>1000</maximumClockSkew>
+		<protocol xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+			xsi:type="federationProtocolType" version="1.0.0">
+			<realm>urn:org:apache:cxf:fediz:fedizhelloworld</realm>
+			<issuer>https://localhost:9443/fediz-idp/federation</issuer>
+			<roleDelimiter>,</roleDelimiter>
+			<roleURI>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role</roleURI>
+			<claimTypesRequested>
+				<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role" optional="false" />
+				<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" optional="true" />
+				<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" optional="true" />
+				<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" optional="true" />
+			</claimTypesRequested>
+		</protocol>
+	</contextConfig>
+</FedizConfig>
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java b/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java
new file mode 100644
index 0000000..a20910d
--- /dev/null
+++ b/examples/websphereWebapp/src/main/java/org/apache/cxf/fediz/example/FederationServlet.java
@@ -0,0 +1,115 @@
+/**
+ * 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.example;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.security.Principal;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.Element;
+
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.apache.cxf.fediz.core.Claim;
+import org.apache.cxf.fediz.core.ClaimCollection;
+import org.apache.cxf.fediz.core.FedizPrincipal;
+import org.apache.cxf.fediz.core.SecurityTokenThreadLocal;
+
+
+public class FederationServlet extends HttpServlet {
+
+    /**
+     * 
+     */
+    private static final long serialVersionUID = -9019993850246851112L;
+
+    public void doGet(HttpServletRequest request, HttpServletResponse response)
+        throws ServletException, IOException {
+
+        response.setContentType("text/html");
+        PrintWriter out = response.getWriter();
+
+        out.println("<html>");
+        out.println("<head><title>WS Federation Example</title></head>");
+        out.println("<body>");
+        out.println("<h1>Hello World</h1>");
+        out.println("Request url: " + request.getRequestURL().toString() + "<p>");
+
+
+        out.println("<br><b>User</b><p>");
+        Principal p = request.getUserPrincipal();
+        if (p != null) {
+            out.println("Principal: " + p.getName() + "<p>");
+        }
+
+        out.println("<br><b>Roles</b><p>");
+        List<String> roleListToCheck = Arrays.asList("Admin", "Manager", "User", "Authenticated");
+        for (String item: roleListToCheck) {
+            out.println("Has role '" + item + "': " + ((request.isUserInRole(item)) ? "<b>yes</b>" : "no") + "<p>");
+        }
+
+        if (p instanceof FedizPrincipal) {
+            FedizPrincipal fp = (FedizPrincipal)p;
+
+            out.println("<br><b>Claims</b><p>");
+            ClaimCollection claims = fp.getClaims();
+            for (Claim c: claims) {
+                out.println(c.getClaimType().toString() + ": " + c.getValue() + "<p>");
+            }
+        } else {
+            out.println("<p>Principal is not instance of FedizPrincipal");
+        }
+
+        Element el = SecurityTokenThreadLocal.getToken();
+        if (el != null) {
+            out.println("<br><b>Bootstrap token</b><p>");
+            String token = null;
+            try {
+                TransformerFactory transFactory = TransformerFactory.newInstance();
+                Transformer transformer = transFactory.newTransformer();
+                StringWriter buffer = new StringWriter();
+                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+                transformer.transform(new DOMSource(el),
+                                      new StreamResult(buffer));
+                token = buffer.toString();
+                out.println("<p>" + StringEscapeUtils.escapeXml11(token));
+            } catch (Exception ex) {
+                out.println("<p>Failed to transform cached element to string: " + ex.toString());
+            }
+        } else {
+            out.println("<p>Bootstrap token not cached in thread local storage");
+        }
+
+        out.println("</body>");
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/resources/log4j.properties b/examples/websphereWebapp/src/main/resources/log4j.properties
new file mode 100644
index 0000000..aaea9b4
--- /dev/null
+++ b/examples/websphereWebapp/src/main/resources/log4j.properties
@@ -0,0 +1,17 @@
+# Set root category priority to INFO and its only appender to CONSOLE.
+#log4j.rootCategory=FATAL, CONSOLE
+log4j.rootCategory=DEBUG, CONSOLE
+
+# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
+log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
+log4j.appender.CONSOLE.Threshold=DEBUG
+log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
+log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n
+
+# LOGFILE is set to be a File appender using a PatternLayout.
+log4j.appender.LOGFILE=org.apache.log4j.FileAppender
+log4j.appender.LOGFILE.File=target/wss4j.log
+log4j.appender.LOGFILE.Append=false
+log4j.appender.LOGFILE.Threshold=DEBUG
+log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
+log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/src/main/resources/logging.properties
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/resources/logging.properties b/examples/websphereWebapp/src/main/resources/logging.properties
new file mode 100644
index 0000000..51cfbec
--- /dev/null
+++ b/examples/websphereWebapp/src/main/resources/logging.properties
@@ -0,0 +1,53 @@
+############################################################
+#  	Default Logging Configuration File
+#
+# You can use a different file by specifying a filename
+# with the java.util.logging.config.file system property.  
+# For example java -Djava.util.logging.config.file=myfile
+############################################################
+
+############################################################
+#  	Global properties
+############################################################
+
+# "handlers" specifies a comma separated list of log Handler 
+# classes.  These handlers will be installed during VM startup.
+# Note that these classes must be on the system classpath.
+# By default we only configure a ConsoleHandler, which will only
+# show messages at the WARNING and above levels.
+handlers= java.util.logging.ConsoleHandler
+#handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandler
+
+# Default global logging level.
+# This specifies which kinds of events are logged across
+# all loggers.  For any given facility this global level
+# can be overridden by a facility specific level
+# Note that the ConsoleHandler also has a separate level
+# setting to limit messages printed to the console.
+.level= INFO
+
+############################################################
+# Handler specific properties.
+# Describes specific configuration info for Handlers.
+############################################################
+
+# default file output is in user's home directory.
+java.util.logging.FileHandler.pattern = %h/java%u.log
+java.util.logging.FileHandler.limit = 50000
+java.util.logging.FileHandler.count = 1
+java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
+
+# Limit the message that are printed on the console to WARNING and above.
+java.util.logging.ConsoleHandler.level = FINEST
+java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
+java.util.logging.SimpleFormatter.format="HEL %1$tc %2$s%n%4$s: %5$s%6$s%n"
+
+############################################################
+# Facility specific properties.
+# Provides extra control for each logger.
+############################################################
+
+# For example, set the com.xyz.foo logger to only log SEVERE
+# messages:
+#com.xyz.foo.level = SEVERE
+org.apache.cxf.fediz.level = FINE
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/src/main/webapp/META-INF/context.xml
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/webapp/META-INF/context.xml b/examples/websphereWebapp/src/main/webapp/META-INF/context.xml
new file mode 100644
index 0000000..7fc734a
--- /dev/null
+++ b/examples/websphereWebapp/src/main/webapp/META-INF/context.xml
@@ -0,0 +1,3 @@
+<Context>
+        <Valve className="org.apache.cxf.fediz.tomcat.FederationAuthenticator" configFile="conf/fediz_config.xml" />        
+</Context>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml b/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..28d2a3a
--- /dev/null
+++ b/examples/websphereWebapp/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,105 @@
+<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+    version="3.0" metadata-complete="true">
+
+    <description>WS Federation Simple Web Application Example</description>
+    <display-name>WS Federation Simple Web Application Example</display-name>
+
+    <!-- Optional: Cache the security token in Thread Local Storage -->
+	<!-- 
+    <filter>
+        <filter-name>FederationFilter</filter-name>
+        <filter-class>org.apache.cxf.fediz.core.servlet.FederationFilter</filter-class>
+    </filter>
+	-->
+	
+	<filter>
+        <filter-name>FederationFilter</filter-name>
+        <filter-class>org.apache.cxf.fediz.was.servlet.filter.SecurityContextTTLChecker</filter-class>
+    </filter>
+
+    <filter-mapping>
+        <filter-name>FederationFilter</filter-name>
+        <url-pattern>/secure/*</url-pattern>
+    </filter-mapping>
+
+    <servlet>
+        <servlet-name>FederationServlet</servlet-name>
+        <servlet-class>org.apache.cxf.fediz.example.FederationServlet</servlet-class>
+    </servlet>
+
+    <servlet-mapping>
+        <servlet-name>FederationServlet</servlet-name>
+        <url-pattern>/secure/fedservlet</url-pattern>
+    </servlet-mapping>
+
+    <servlet-mapping>
+        <servlet-name>FederationServlet</servlet-name>
+        <url-pattern>/secure/admin/fedservlet</url-pattern>
+    </servlet-mapping>
+
+    <servlet-mapping>
+        <servlet-name>FederationServlet</servlet-name>
+        <url-pattern>/secure/user/fedservlet</url-pattern>
+    </servlet-mapping>
+
+    <servlet-mapping>
+        <servlet-name>FederationServlet</servlet-name>
+        <url-pattern>/secure/manager/fedservlet</url-pattern>
+    </servlet-mapping>
+
+    <security-role>
+        <role-name>Manager</role-name>
+    </security-role>
+    <security-role>
+        <role-name>User</role-name>
+    </security-role>
+    <security-role>
+        <role-name>Admin</role-name>
+    </security-role>
+    <security-role>
+        <role-name>Authenticated</role-name>
+    </security-role>
+
+    <security-constraint>
+        <web-resource-collection>
+            <web-resource-name>Protected Area</web-resource-name>
+            <url-pattern>/secure/*</url-pattern>
+        </web-resource-collection>
+        <auth-constraint>
+            <role-name>*</role-name>
+        </auth-constraint>
+    </security-constraint>
+
+    <security-constraint>
+        <web-resource-collection>
+            <web-resource-name>Protected Admin Area</web-resource-name>
+            <url-pattern>/secure/admin/*</url-pattern>
+        </web-resource-collection>
+        <auth-constraint>
+            <role-name>Admin</role-name>
+        </auth-constraint>
+    </security-constraint>
+
+    <security-constraint>
+        <web-resource-collection>
+            <web-resource-name>Protected Manager Area</web-resource-name>
+            <url-pattern>/secure/manager/*</url-pattern>
+        </web-resource-collection>
+        <auth-constraint>
+            <role-name>Manager</role-name>
+        </auth-constraint>
+    </security-constraint>
+
+    <security-constraint>
+        <web-resource-collection>
+            <web-resource-name>Protected User Area</web-resource-name>
+            <url-pattern>/secure/user/*</url-pattern>
+        </web-resource-collection>
+        <auth-constraint>
+            <role-name>User</role-name>
+            <role-name>Admin</role-name>
+            <role-name>Manager</role-name>
+        </auth-constraint>
+    </security-constraint>
+</web-app>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/src/main/webapp/index.html
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/webapp/index.html b/examples/websphereWebapp/src/main/webapp/index.html
new file mode 100644
index 0000000..1a1ef1d
--- /dev/null
+++ b/examples/websphereWebapp/src/main/webapp/index.html
@@ -0,0 +1,25 @@
+<!--
+  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.
+-->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML><HEAD><TITLE>WS Federation Tomcat Examples</TITLE>
+<META http-equiv=Content-Type content="text/html">
+</HEAD>
+<BODY>
+<P>
+<H3>Hello World</H3>
+<P></P>
+</BODY></HTML>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/examples/websphereWebapp/src/main/webapp/secure/test.html
----------------------------------------------------------------------
diff --git a/examples/websphereWebapp/src/main/webapp/secure/test.html b/examples/websphereWebapp/src/main/webapp/secure/test.html
new file mode 100644
index 0000000..042ed67
--- /dev/null
+++ b/examples/websphereWebapp/src/main/webapp/secure/test.html
@@ -0,0 +1,25 @@
+<!--
+  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.
+-->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML><HEAD><TITLE>WS Federation Tomcat Examples</TITLE>
+<META http-equiv=Content-Type content="text/html">
+</HEAD>
+<BODY>
+<P>
+<H3>Secure Test</H3>
+<P></P>
+</BODY></HTML>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
index e4cd349..54a6ab7 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
@@ -58,9 +58,9 @@ public abstract class SigninHandler implements RequestHandler {
                 LOG.debug("Validating RSTR...");
                 // process and validate the token
                 try {
-                    processSigninRequest(request, response);
+                    FedizResponse federationResponse = processSigninRequest(request, response);
                     LOG.info("RSTR validated successfully");
-                    resumeRequest();
+                    resumeRequest(request, response, federationResponse);
                     return true;
                 } catch (ProcessingException e) {
                     LOG.error("RSTR validated failed.");
@@ -74,8 +74,9 @@ public abstract class SigninHandler implements RequestHandler {
         return false;
     }
 
-    public abstract void resumeRequest();
-    
+    public abstract void resumeRequest(HttpServletRequest request, HttpServletResponse response,
+        FedizResponse federationResponse);
+
     public FedizResponse processSigninRequest(HttpServletRequest req, HttpServletResponse resp)
         throws ProcessingException {
         FedizRequest federationRequest = new FedizRequest();

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
index 7bc2abd..aa17e61 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/servlet/filter/SecurityContextTTLChecker.java
@@ -50,8 +50,11 @@ import org.slf4j.LoggerFactory;
 
 /*
  * A Servlet Filter that MUST be configured to match the '/*' request scheme on each Web Application
- * to enforce SAML assertion TimeToLive checking 
+ * to enforce SAML assertion TimeToLive checking
+ *
+ * @deprecated  Not needed any longer since version 1.2.0
  */
+@Deprecated
 public class SecurityContextTTLChecker extends HttpServlet implements Filter {
     private static final Logger LOG = LoggerFactory.getLogger(SecurityContextTTLChecker.class);
     private static final long serialVersionUID = 5732969339258858728L;

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/ce7b4f1a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
index d33f45d..3a30b2e 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
@@ -22,12 +22,11 @@ import java.io.File;
 import java.io.IOException;
 import java.rmi.RemoteException;
 import java.util.ArrayList;
-import java.util.HashSet;
 import java.util.Hashtable;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Properties;
-import java.util.Set;
 
 import javax.naming.InitialContext;
 import javax.naming.NamingException;
@@ -39,23 +38,25 @@ import javax.servlet.http.HttpSession;
 import com.ibm.websphere.security.CustomRegistryException;
 import com.ibm.websphere.security.EntryNotFoundException;
 import com.ibm.websphere.security.UserRegistry;
+import com.ibm.websphere.security.WSSecurityException;
 import com.ibm.websphere.security.WebTrustAssociationException;
 import com.ibm.websphere.security.WebTrustAssociationFailedException;
+import com.ibm.websphere.security.auth.WSSubject;
 import com.ibm.wsspi.security.tai.TAIResult;
 import com.ibm.wsspi.security.tai.TrustAssociationInterceptor;
 import com.ibm.wsspi.security.token.AttributeNameConstants;
 
 import org.apache.cxf.fediz.core.FederationConstants;
 import org.apache.cxf.fediz.core.RequestState;
-import org.apache.cxf.fediz.core.SAMLSSOConstants;
-import org.apache.cxf.fediz.core.config.FederationProtocol;
 import org.apache.cxf.fediz.core.config.FedizConfigurator;
 import org.apache.cxf.fediz.core.config.FedizContext;
-import org.apache.cxf.fediz.core.config.SAMLProtocol;
 import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.handler.LogoutHandler;
+import org.apache.cxf.fediz.core.handler.RequestHandler;
+import org.apache.cxf.fediz.core.handler.SigninHandler;
+import org.apache.cxf.fediz.core.metadata.MetadataDocumentHandler;
 import org.apache.cxf.fediz.core.processor.FederationProcessorImpl;
 import org.apache.cxf.fediz.core.processor.FedizProcessor;
-import org.apache.cxf.fediz.core.processor.FedizRequest;
 import org.apache.cxf.fediz.core.processor.FedizResponse;
 import org.apache.cxf.fediz.core.processor.RedirectionResponse;
 import org.apache.cxf.fediz.was.Constants;
@@ -71,7 +72,6 @@ import org.slf4j.LoggerFactory;
  */
 public class FedizInterceptor implements TrustAssociationInterceptor {
     private static final Logger LOG = LoggerFactory.getLogger(FedizInterceptor.class);
-    private static Set<String> authorizedWebApps = new HashSet<String>(15);
 
     private String configFile;
     private FedizConfigurator configurator;
@@ -117,26 +117,22 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
      * Registers a WebApplication using its contextPath as a key. This method must be called by the associated
      * security ServletFilter instance of a secured application at initialization time
      * 
+     * @deprecated Not used/needed any longer since version 1.2.0
      * @param contextPath
      */
+    @Deprecated
     public static void registerContext(String contextPath) {
-        LOG.debug("Registering secured context-path: {}", contextPath);
-        authorizedWebApps.add(contextPath);
     }
 
     /**
      * Deregister a WebApplication using its contextPath as a key. This method must be called by the
      * associated security ServletFilter instance of a secured application in the #destroy() method
      * 
+     * @deprecated Not used/needed any longer since version 1.2.0
      * @param contextPath
      */
+    @Deprecated
     public static void deRegisterContext(String contextPath) {
-        if (authorizedWebApps.contains(contextPath)) {
-            LOG.debug("De-registering secured context-path {}", contextPath);
-            synchronized (authorizedWebApps) {
-                authorizedWebApps.remove(contextPath);
-            }
-        }
     }
 
     /*
@@ -147,6 +143,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
     public int initialize(Properties props) throws WebTrustAssociationFailedException {
         if (props != null) {
             try {
+                @SuppressWarnings("deprecation")
                 String roleGroupMapper = props.containsKey(Constants.FEDIZ_ROLE_MAPPER)
                     ? props.getProperty(Constants.FEDIZ_ROLE_MAPPER)
                     : props.getProperty(Constants.ROLE_GROUP_MAPPER);
@@ -156,16 +153,15 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
                         LOG.debug("Using the {} mapper class", roleGroupMapper);
                         mapper.initialize(props);
                     } catch (Exception e) {
-                        throw new TAIConfigurationException(
-                                                            "Invalid TAI configuration for idpRoleToGroupMapper: "
-                                                                + e.getClass().getName() + " "
-                                                                + e.getMessage());
+                        throw new TAIConfigurationException("Invalid TAI configuration for idpRoleToGroupMapper: "
+                                                            + e.getClass().getName() + " " + e.getMessage());
                     }
                 } else {
                     mapper = new DefaultRoleToGroupMapper();
                     LOG.debug("Using the DefaultRoleToGroupMapper mapper class");
                 }
 
+                @SuppressWarnings("deprecation")
                 String configFileLocation = props.containsKey(Constants.FEDIZ_CONFIG_LOCATION)
                     ? props.getProperty(Constants.FEDIZ_CONFIG_LOCATION)
                     : props.getProperty(Constants.CONFIGURATION_FILE_PARAMETER);
@@ -235,106 +231,109 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         }
 
         try {
-            // looks for the wa parameter as a way to determine the current step
-            String wa = req.getParameter(FederationConstants.PARAM_ACTION);
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("WS-Federation action: " + (wa == null ? "<not set>" : wa));
+
+            // Handle Metadata Document requests
+            RequestHandler mddHandler = new MetadataDocumentHandler(fedCtx);
+            if (mddHandler.canHandleRequest(req)) {
+                boolean success = mddHandler.handleRequest(req, resp);
+                return TAIResult.create(success
+                    ? HttpServletResponse.SC_OK
+                    : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
             }
-            if (wa == null) {
-                return handleNoWA(req, resp);
-            } else {
-                if (FederationConstants.ACTION_SIGNIN.equals(wa)) {
-                    return handleSignIn(req, resp);
-                } else {
-                    throw new Exception("Unsupported WS-Federation action [" + wa + "]");
-                }
+
+            // Handle Logout requests
+            LogoutHandler logoutHandler = new LogoutHandler(fedCtx);
+            if (logoutHandler.canHandleRequest(req)) {
+                boolean success = logoutHandler.handleRequest(req, resp);
+                return TAIResult.create(success
+                    ? HttpServletResponse.SC_OK
+                    : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
             }
-        } catch (Exception e) {
-            LOG.error("Exception occured validating request", e);
-            throw new WebTrustAssociationFailedException(e.getMessage());
-        }
-    }
 
-    private TAIResult handleSignIn(HttpServletRequest req, HttpServletResponse resp)
-        throws ProcessingException, IOException, WebTrustAssociationFailedException, Exception {
-        if (req.getMethod().equals(Constants.HTTP_POST_METHOD)) {
-            LOG.debug("Sign-In-Response received");
-            String wresult = req.getParameter(FederationConstants.PARAM_RESULT);
-            String wctx = req.getParameter(FederationConstants.PARAM_CONTEXT);
-            if (wresult != null && wctx != null) {
-                LOG.debug("Validating RSTR...");
-                // process and validate the token
-                FedizResponse federationResponse = processSigninRequest(req, resp);
-                LOG.info("RSTR validated successfully");
-
-                HttpSession session = req.getSession(true);
-                session.setAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY, federationResponse);
-                RequestState requestState = (RequestState) session.getAttribute(wctx);
-                if (requestState != null && requestState.getTargetAddress() != null) {
-                    LOG.info("Redirecting request to {}", requestState.getTargetAddress());
-                    resp.sendRedirect(requestState.getTargetAddress());
-                    session.removeAttribute(wctx);
+            // Handle Signin requests
+            SigninHandler signinHandler = new SigninHandler(fedCtx) {
+                @Override
+                public void resumeRequest(HttpServletRequest request, HttpServletResponse response,
+                    FedizResponse federationResponse) {
+                    String wctx = request.getParameter(FederationConstants.PARAM_CONTEXT);
+                    HttpSession session = request.getSession(true);
+                    session.setAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY, federationResponse);
+                    RequestState requestState = (RequestState)session.getAttribute(wctx);
+                    if (requestState != null && requestState.getTargetAddress() != null) {
+                        LOG.info("Redirecting request to {}", requestState.getTargetAddress());
+                        try {
+                            response.sendRedirect(requestState.getTargetAddress());
+                        } catch (IOException e) {
+                            LOG.error("Cannot resume with original request.", e);
+                        }
+                        session.removeAttribute(wctx);
+                    }
                 }
+            };
+            if (signinHandler.canHandleRequest(req)) {
+                signinHandler.handleRequest(req, resp);
                 return TAIResult.create(HttpServletResponse.SC_FOUND);
+            }
+
+            // Check if user was authenticated previously and token is still valid
+            String user = req.getRemoteUser();
+            String principal = WSSubject.getCallerPrincipal();
+            Subject subject = null;
+            try {
+                subject = WSSubject.getCallerSubject();
+            } catch (WSSecurityException e) {
+                LOG.error("Could not read subject");
+            }
+            LOG.info("Remote User: {}, Principal: {}, Subject {}", user, principal, subject);
+            if (principal != null && subject != null) {
+                // return TAIResult.create(HttpServletResponse.SC_OK, principal, subject);
             } else {
-                throw new Exception("Missing required parameter [wctx or wresult]");
+                TAIResult taiResult = checkUserAuthentication(req);
+                if (taiResult != null) {
+                    return taiResult;
+                }
             }
-        } else {
-            throw new Exception("Incorrect method GET for Sign-In-Response");
+
+            LOG.info("No Subject found in existing session. Redirecting to IDP");
+            redirectToIdp(req, resp, fedCtx);
+            return TAIResult.create(HttpServletResponse.SC_FOUND);
+
+        } catch (Exception e) {
+            LOG.error("Exception occured validating request", e);
+            throw new WebTrustAssociationFailedException(e.getMessage());
         }
     }
 
-    private TAIResult handleNoWA(HttpServletRequest req, HttpServletResponse resp) throws IOException,
-        WebTrustAssociationFailedException, Exception {
+    private TAIResult checkUserAuthentication(HttpServletRequest req) throws Exception {
+        TAIResult result = null;
         HttpSession session = req.getSession(false);
-        if (session == null) {
-            LOG.debug("No session found. Sending a token request");
-            redirectToIdp(req, resp);
-            return TAIResult.create(HttpServletResponse.SC_FOUND);
-        } else {
+        if (session != null) {
             LOG.debug("Session ID is {}", session.getId());
-
             FedizResponse federationResponse = (FedizResponse)session
                 .getAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
             if (federationResponse != null) {
                 LOG.info("Security Token found in session: {}", federationResponse.getUsername());
 
-                TAIResult result = null;
                 // check that the target WebApp is properly configured for Token TTL enforcement
-                if (authorizedWebApps.contains(req.getContextPath())) {
-
-                    LOG.info("Security Filter properly configured - forwarding subject");
-
+                if (checkSecurityToken(federationResponse)) {
                     // proceed creating the JAAS Subject
+                    LOG.info("Security Filter properly configured - forwarding subject");
                     List<String> groupsIds = groupIdsFromTokenRoles(federationResponse);
                     Subject subject = createSubject(federationResponse, groupsIds, session.getId());
 
                     result = TAIResult.create(HttpServletResponse.SC_OK, federationResponse.getUsername(), subject);
-                } else {
-                    result = TAIResult.create(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-                    LOG.warn("No Security Filter configured for {}", req.getContextPath());
                 }
                 // leave the Session untouched
-                session.removeAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
-                return result;
-            } else {
-                LOG.info("No Subject found in existing session. Redirecting to IDP");
-                redirectToIdp(req, resp);
-                return TAIResult.create(HttpServletResponse.SC_FOUND);
+                // session.removeAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
             }
         }
+        return result;
     }
 
-    protected void redirectToIdp(HttpServletRequest request, HttpServletResponse response)
+    protected void redirectToIdp(HttpServletRequest request, HttpServletResponse response, FedizContext fedCtx)
         throws IOException, WebTrustAssociationFailedException {
         FedizProcessor processor = new FederationProcessorImpl();
 
-        String contextName = request.getContextPath();
-        if (contextName == null || contextName.isEmpty()) {
-            contextName = "/";
-        }
-        FedizContext fedCtx = getFederationContext(request);
-
         try {
             RedirectionResponse redirectionResponse = processor.createSignInRequest(request, fedCtx);
             String redirectURL = redirectionResponse.getRedirectionURL();
@@ -360,36 +359,56 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             LOG.error("Failed to create SignInRequest", ex);
             throw new WebTrustAssociationFailedException(ex.getMessage());
         }
+    }
+
+    protected FedizResponse getCachedFederationResponse(Subject subject) {
+        Iterator<?> i = subject.getPublicCredentials().iterator();
+        while (i.hasNext()) {
+            Object o = i.next();
+            if (o instanceof Hashtable) {
+                Map<?, ?> table = (Hashtable<?, ?>)o;
+                return (FedizResponse)table.get(Constants.SUBJECT_TOKEN_KEY);
+            }
+        }
+        return null;
+    }
 
+    private boolean checkSecurityToken(FedizResponse response) {
+        long currentTime = System.currentTimeMillis();
+        return response.getTokenExpires().getTime() > currentTime;
     }
 
     private List<String> groupIdsFromTokenRoles(FedizResponse federationResponse) throws Exception {
+
+        List<String> localGroups = mapper.groupsFromRoles(federationResponse.getRoles());
+        List<String> groupIds = new ArrayList<String>(localGroups.size());
+
         InitialContext ctx = new InitialContext();
         try {
             UserRegistry reg = (UserRegistry)ctx.lookup(Constants.USER_REGISTRY_JNDI_NAME);
 
-            List<String> localGroups = mapper.groupsFromRoles(federationResponse.getRoles());
-
-            List<String> groupIds = new ArrayList<String>(1);
             if (localGroups != null) {
                 LOG.debug("Converting {} group names to uids", localGroups.size());
                 for (String localGroup : localGroups) {
-                    String guid = convertGroupNameToUniqueId(reg, localGroup);
-                    LOG.debug("Group '{}' maps to guid: {}", localGroup, guid);
-                    groupIds.add(guid);
+                    try {
+                        String guid = convertGroupNameToUniqueId(reg, localGroup);
+                        LOG.debug("Group '{}' maps to guid: {}", localGroup, guid);
+                        groupIds.add(guid);
+                    } catch (EntryNotFoundException e) {
+                        LOG.warn("Group entry could not be found in UserRegistry: {}", localGroup);
+                    }
                 }
             }
-            if (LOG.isInfoEnabled()) {
-                LOG.info("Group list: " + groupIds.toString());
-            }
-            return groupIds;
         } catch (NamingException ex) {
-            LOG.error("User Registry could not be loaded from JNDI context.");
-            LOG.warn("No groups/roles could be mapped for user: {}", federationResponse.getUsername());
-            return new ArrayList<String>();
+            LOG.error("User Registry could not be loaded via JNDI context.");
+            LOG.warn("GroupIDs from mapping will be used instead of UserRegistry mapping for user: {}",
+                     federationResponse.getUsername());
+            groupIds.addAll(localGroups);
         } finally {
             ctx.close();
         }
+        LOG.debug("Group list: {}", groupIds);
+        return groupIds;
     }
 
     /**
@@ -417,34 +436,6 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         return subject;
     }
 
-    public FedizResponse processSigninRequest(HttpServletRequest req, HttpServletResponse resp)
-        throws ProcessingException {
-        FedizContext fedCtx = getFederationContext(req);
-        FedizRequest federationRequest = new FedizRequest();
-
-        String wa = req.getParameter(FederationConstants.PARAM_ACTION);
-        String responseToken = getResponseToken(req, fedCtx);
-
-        federationRequest.setAction(wa);
-        federationRequest.setResponseToken(responseToken);
-        federationRequest.setState(req.getParameter("RelayState"));
-        federationRequest.setRequest(req);
-
-        LOG.debug("FederationRequest: {}", federationRequest);
-
-        FedizProcessor processor = new FederationProcessorImpl();
-        return processor.processRequest(federationRequest, fedCtx);
-    }
-
-    private String getResponseToken(HttpServletRequest request, FedizContext fedConfig) {
-        if (fedConfig.getProtocol() instanceof FederationProtocol) {
-            return request.getParameter(FederationConstants.PARAM_RESULT);
-        } else if (fedConfig.getProtocol() instanceof SAMLProtocol) {
-            return request.getParameter(SAMLSSOConstants.SAML_RESPONSE);
-        }
-        return null;
-    }
-
     /**
      * Convenience method for converting a list of group names to their unique group IDs
      * 


[09/12] cxf-fediz git commit: Improved TAI invocation and Handler integration

Posted by jb...@apache.org.
Improved TAI invocation and Handler integration


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

Branch: refs/heads/master
Commit: 06720e6bb1bbc79630104a60253e789d42ce9679
Parents: d95850e
Author: Jan Bernhardt <jb...@talend.com>
Authored: Tue Mar 10 17:47:30 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Thu Mar 19 17:26:57 2015 +0100

----------------------------------------------------------------------
 .../cxf/fediz/core/handler/LogoutHandler.java   |   4 +-
 .../cxf/fediz/core/handler/RequestHandler.java  |   6 +-
 .../cxf/fediz/core/handler/SigninHandler.java   |  24 ++--
 .../core/metadata/MetadataDocumentHandler.java  |   4 +-
 .../cxf/fediz/was/tai/FedizInterceptor.java     | 141 +++++++++++++++----
 5 files changed, 131 insertions(+), 48 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/06720e6b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java
index d58de21..af532ae 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/LogoutHandler.java
@@ -37,7 +37,7 @@ import org.apache.wss4j.common.saml.SamlAssertionWrapper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class LogoutHandler implements RequestHandler {
+public class LogoutHandler implements RequestHandler<Boolean> {
 
     private static final Logger LOG = LoggerFactory.getLogger(LogoutHandler.class);
     protected final FedizContext fedizConfig;
@@ -67,7 +67,7 @@ public class LogoutHandler implements RequestHandler {
     }
 
     @Override
-    public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
+    public Boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
         String wa = request.getParameter(FederationConstants.PARAM_ACTION);
         if (FederationConstants.ACTION_SIGNOUT.equals(wa)) {
             return signout(request, response);

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/06720e6b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java
index cc15e59..b9c9915 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/RequestHandler.java
@@ -21,7 +21,7 @@ package org.apache.cxf.fediz.core.handler;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
-public interface RequestHandler {
+public interface RequestHandler<T> {
 
     /**
      * @param request Check if handler can handle this given request
@@ -34,7 +34,7 @@ public interface RequestHandler {
      *
      * @param request Request to be handled.
      * @param response Response to be populated.
-     * @return Returns true if request handling was successful.
+     * @return Returns result of request handling.
      */
-    boolean handleRequest(HttpServletRequest request, HttpServletResponse response);
+    T handleRequest(HttpServletRequest request, HttpServletResponse response);
 }

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/06720e6b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
index a8d214d..1f62e57 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/handler/SigninHandler.java
@@ -38,7 +38,7 @@ import org.slf4j.LoggerFactory;
  * It is recommended to extend this class and implement the resumeRequest method to continue invoking the originally
  * requested website.
  */
-public class SigninHandler implements RequestHandler {
+public class SigninHandler<T> implements RequestHandler<T> {
 
     private static final Logger LOG = LoggerFactory.getLogger(SigninHandler.class);
     protected final FedizContext fedizConfig;
@@ -53,34 +53,38 @@ public class SigninHandler implements RequestHandler {
     }
 
     @Override
-    public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
+    public T handleRequest(HttpServletRequest request, HttpServletResponse response) {
         if (request.getMethod().equals("POST")) {
             LOG.debug("Sign-In-Response received");
             String wresult = request.getParameter(FederationConstants.PARAM_RESULT);
-            String wctx = request.getParameter(FederationConstants.PARAM_CONTEXT);
-            if (wresult != null && wctx != null) {
+            if (wresult != null) {
                 LOG.debug("Validating RSTR...");
                 // process and validate the token
                 try {
                     FedizResponse federationResponse = processSigninRequest(request, response);
-                    LOG.info("RSTR validated successfully");
+                    LOG.debug("RSTR validated successfully");
+                    T principal = createPrincipal(request, response, federationResponse);
                     resumeRequest(request, response, federationResponse);
-                    return true;
+                    return principal;
                 } catch (ProcessingException e) {
                     LOG.error("RSTR validated failed.");
                 }
             } else {
-                throw new RuntimeException("Missing required parameter [wctx or wresult]");
+                throw new RuntimeException("Missing required parameter 'wresult'");
             }
         } else {
             throw new RuntimeException("Incorrect method GET for Sign-In-Response");
         }
-        return false;
+        return null;
     }
 
-    public void resumeRequest(HttpServletRequest request, HttpServletResponse response,
-        FedizResponse federationResponse) {
+    protected T createPrincipal(HttpServletRequest request, HttpServletResponse response,
+                              FedizResponse federationResponse) {
+        return null;
+    }
 
+    protected void resumeRequest(HttpServletRequest request, HttpServletResponse response,
+        FedizResponse federationResponse) {
     }
 
     public FedizResponse processSigninRequest(HttpServletRequest req, HttpServletResponse resp)

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/06720e6b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java
----------------------------------------------------------------------
diff --git a/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java
index 364bb22..32d366f 100644
--- a/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java
+++ b/plugins/core/src/main/java/org/apache/cxf/fediz/core/metadata/MetadataDocumentHandler.java
@@ -38,7 +38,7 @@ import org.apache.wss4j.common.util.DOM2Writer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class MetadataDocumentHandler implements RequestHandler {
+public class MetadataDocumentHandler implements RequestHandler<Boolean> {
 
     private static final Logger LOG = LoggerFactory.getLogger(MetadataDocumentHandler.class);
     protected final FedizContext fedizConfig;
@@ -64,7 +64,7 @@ public class MetadataDocumentHandler implements RequestHandler {
     }
 
     @Override
-    public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
+    public Boolean handleRequest(HttpServletRequest request, HttpServletResponse response) {
         LOG.debug("Metadata document requested");
         FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedizConfig.getProtocol());
         PrintWriter out = null;

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/06720e6b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
index 4707df3..1fb30a8 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
@@ -30,6 +30,7 @@ import java.util.Properties;
 import javax.naming.InitialContext;
 import javax.naming.NamingException;
 import javax.security.auth.Subject;
+import javax.servlet.http.Cookie;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
@@ -49,7 +50,6 @@ import org.apache.cxf.fediz.core.config.FedizConfigurator;
 import org.apache.cxf.fediz.core.config.FedizContext;
 import org.apache.cxf.fediz.core.exception.ProcessingException;
 import org.apache.cxf.fediz.core.handler.LogoutHandler;
-import org.apache.cxf.fediz.core.handler.RequestHandler;
 import org.apache.cxf.fediz.core.handler.SigninHandler;
 import org.apache.cxf.fediz.core.metadata.MetadataDocumentHandler;
 import org.apache.cxf.fediz.core.processor.FederationProcessorImpl;
@@ -119,8 +119,8 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
      * Registers a WebApplication using its contextPath as a key. This method must be called by the associated
      * security ServletFilter instance of a secured application at initialization time
      * 
-     * @deprecated Not used/needed any longer since version 1.2.0
      * @param contextPath
+     * @deprecated Not used/needed any longer since version 1.2.0
      */
     @Deprecated
     public static void registerContext(String contextPath) {
@@ -130,8 +130,8 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
      * Deregister a WebApplication using its contextPath as a key. This method must be called by the
      * associated security ServletFilter instance of a secured application in the #destroy() method
      * 
-     * @deprecated Not used/needed any longer since version 1.2.0
      * @param contextPath
+     * @deprecated Not used/needed any longer since version 1.2.0
      */
     @Deprecated
     public static void deRegisterContext(String contextPath) {
@@ -195,25 +195,74 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             contextPath = "/";
         }
         return configurator.getFedizContext(contextPath);
-
     }
 
-    /*
-     * (non-Javadoc)
-     * @see com.ibm.wsspi.security.tai.TrustAssociationInterceptor#isTargetInterceptor(javax.servlet.http.
-     * HttpServletRequest)
+    /**
+     * This method decides weather the interceptor shall be called for #negotiateValidateandEstablishTrust. If
+     * the request is applicable for a metadata document, logout URL, or provides a signin token, this method
+     * returns true. I the use , otherwise this interceptor will not be called.
+     * 
+     * @see com.ibm.wsspi.security.tai.TrustAssociationInterceptor#isTargetInterceptor(HttpServletRequest)
      */
     @Override
     public boolean isTargetInterceptor(HttpServletRequest req) throws WebTrustAssociationException {
+        boolean isTargetInterceptor = false;
         LOG.debug("Request URI: {}", req.getRequestURI());
-        FedizContext context = getFederationContext(req);
+        FedizContext fedCtx = getFederationContext(req);
+
+        if (fedCtx != null) {
+            // Handle Metadata Document requests
+            MetadataDocumentHandler mddHandler = new MetadataDocumentHandler(fedCtx);
+            if (mddHandler.canHandleRequest(req)) {
+                LOG.debug("MetadataDocument request detected");
+                return true;
+            }
+
+            // Handle Logout requests
+            LogoutHandler logoutHandler = new LogoutHandler(fedCtx);
+            if (logoutHandler.canHandleRequest(req)) {
+                LOG.debug("Logout URL request detected");
+                return true;
+            }
+
+            // Handle Signin requests
+            SigninHandler signinHandler = new SigninHandler(fedCtx);
+            if (signinHandler.canHandleRequest(req)) {
+                LOG.debug("SignIn request detected");
+                return true;
+            }
+            HttpSession session = req.getSession(false);
+            if (session != null) {
+                // Check if user is already authenticated
+                Cookie[] cookies = req.getCookies();
+                if (cookies != null) {
+                    for (Cookie c : cookies) {
+                        // TODO Make Cookie Name customizable
+                        if ("LtpaToken2".equals(c.getName())) {
+                            LOG.debug("User is already authenticated. Fediz TAI Interceptor will not be invoked");
+                            isTargetInterceptor = false;
+                            break;
+                        }
+                    }
+                }
+                // Check if token is already in session 
+                Object token = session.getAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
+                if (token != null) {
+                    LOG.debug("SAML Token found in session");
+                    isTargetInterceptor = true;
+                }
+                return isTargetInterceptor;
+            }
 
-        if (context != null) {
-            return true;
+            // TODO enable/disable SAML lifetime checks
+
+            // User not authenticated
+            LOG.debug("User is not yet authenticated. Fediz TAI Interceptor will be invoked");
+            isTargetInterceptor = true;
         } else {
             LOG.warn("No Federation Context configured for context-path {}", req.getContextPath());
         }
-        return false;
+        return isTargetInterceptor;
     }
 
     /*
@@ -235,12 +284,10 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         }
 
         try {
-
             // Handle Metadata Document requests
-            RequestHandler mddHandler = new MetadataDocumentHandler(fedCtx);
+            MetadataDocumentHandler mddHandler = new MetadataDocumentHandler(fedCtx);
             if (mddHandler.canHandleRequest(req)) {
-                boolean success = mddHandler.handleRequest(req, resp);
-                return TAIResult.create(success
+                return TAIResult.create(mddHandler.handleRequest(req, resp)
                     ? HttpServletResponse.SC_OK
                     : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
             }
@@ -248,20 +295,38 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             // Handle Logout requests
             LogoutHandler logoutHandler = new LogoutHandler(fedCtx);
             if (logoutHandler.canHandleRequest(req)) {
-                boolean success = logoutHandler.handleRequest(req, resp);
-                return TAIResult.create(success
+                return TAIResult.create(logoutHandler.handleRequest(req, resp)
                     ? HttpServletResponse.SC_OK
                     : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
             }
 
             // Handle Signin requests
-            SigninHandler signinHandler = new SigninHandler(fedCtx) {
+            SigninHandler<TAIResult> signinHandler = new SigninHandler<TAIResult>(fedCtx) {
+
+                @Override
+                protected TAIResult createPrincipal(HttpServletRequest request, HttpServletResponse response,
+                    FedizResponse federationResponse) {
+                    // proceed creating the JAAS Subject
+                    HttpSession session = request.getSession(true);
+                    session.setAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY, federationResponse);
+                    String username = federationResponse.getUsername();
+                    // List<String> groupsIds = groupIdsFromTokenRoles(federationResponse);
+                    // Subject subject = createSubject(federationResponse, groupsIds, session.getId());
+                    // LOG.info("UserPrincipal was created successfully for {}", username);
+                    try {
+                        // return TAIResult.create(HttpServletResponse.SC_FOUND, username, subject);
+                        return TAIResult.create(HttpServletResponse.SC_FOUND);
+                    } catch (WebTrustAssociationFailedException e) {
+                        LOG.error("TAIResult for user '" + username + "' could not be created", e);
+                        return null;
+                    }
+                }
+
                 @Override
                 public void resumeRequest(HttpServletRequest request, HttpServletResponse response,
                     FedizResponse federationResponse) {
                     String wctx = request.getParameter(FederationConstants.PARAM_CONTEXT);
                     HttpSession session = request.getSession(true);
-                    session.setAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY, federationResponse);
                     RequestState requestState = (RequestState)session.getAttribute(wctx);
                     if (requestState != null && requestState.getTargetAddress() != null) {
                         LOG.info("Redirecting request to {}", requestState.getTargetAddress());
@@ -275,11 +340,11 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
                 }
             };
             if (signinHandler.canHandleRequest(req)) {
-                signinHandler.handleRequest(req, resp);
-                return TAIResult.create(HttpServletResponse.SC_FOUND);
+                return signinHandler.handleRequest(req, resp);
             }
 
             // Check if user was authenticated previously and token is still valid
+            // TODO validate SAML TTL
             TAIResult taiResult = checkUserAuthentication(req);
             if (taiResult != null) {
                 return taiResult;
@@ -295,7 +360,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         }
     }
 
-    private TAIResult checkUserAuthentication(HttpServletRequest req) throws Exception {
+    private TAIResult checkUserAuthentication(HttpServletRequest req) throws WebTrustAssociationFailedException {
         TAIResult result = null;
         HttpSession session = req.getSession(false);
         if (session != null) {
@@ -303,7 +368,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
             FedizResponse federationResponse = (FedizResponse)session
                 .getAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
             if (federationResponse != null) {
-                LOG.info("Security Token found in session: {}", federationResponse.getUsername());
+                LOG.info("Security Token found in session for user: {}", federationResponse.getUsername());
 
                 // validate Security Token and create User Principal
                 if (checkSecurityToken(federationResponse)) {
@@ -314,6 +379,8 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
 
                     result = TAIResult.create(HttpServletResponse.SC_OK, federationResponse.getUsername(), subject);
                 }
+                // Cleanup session
+                session.removeAttribute(Constants.SECURITY_TOKEN_SESSION_ATTRIBUTE_KEY);
             }
         }
         return result;
@@ -358,7 +425,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         return response.getTokenExpires().getTime() > currentTime;
     }
 
-    private List<String> groupIdsFromTokenRoles(FedizResponse federationResponse) throws Exception {
+    private List<String> groupIdsFromTokenRoles(FedizResponse federationResponse) {
 
         List<String> localGroups = mapper.groupsFromRoles(federationResponse.getRoles());
         List<String> groupIds = new ArrayList<String>(localGroups.size());
@@ -368,15 +435,16 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
                       + "GrouUID");
             groupIds.addAll(localGroups);
         } else {
-            InitialContext ctx = new InitialContext();
+            InitialContext ctx = null;
             try {
-                UserRegistry reg = (UserRegistry)ctx.lookup(Constants.USER_REGISTRY_JNDI_NAME);
+                ctx = new InitialContext();
+                UserRegistry userRegistry = (UserRegistry)ctx.lookup(Constants.USER_REGISTRY_JNDI_NAME);
 
                 if (localGroups != null) {
                     LOG.debug("Converting {} group names to uids", localGroups.size());
                     for (String localGroup : localGroups) {
                         try {
-                            String guid = convertGroupNameToUniqueId(reg, localGroup);
+                            String guid = convertGroupNameToUniqueId(userRegistry, localGroup);
                             LOG.debug("Group '{}' maps to guid: {}", localGroup, guid);
                             groupIds.add(guid);
                         } catch (EntryNotFoundException e) {
@@ -387,12 +455,23 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
                 }
             } catch (NamingException ex) {
                 LOG.error("User Registry could not be loaded via JNDI context.");
-                LOG.warn("Since Group mapping failed no groups will be set for user '{}'", federationResponse
-                    .getUsername());
+                LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
                 LOG.info("To switch to direct GroupUID Mapping without UserRegistry being involved set "
                          + "fedizDirectGroupMapping=\"true\"  in TAI Interceptor properties.");
+            } catch (RemoteException e) {
+                LOG.error("RemoteException in UserRegistry", e);
+                LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
+            } catch (CustomRegistryException e) {
+                LOG.error("CustomRegistryException in UserRegistry", e);
+                LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
             } finally {
-                ctx.close();
+                if (ctx != null) {
+                    try {
+                        ctx.close();
+                    } catch (NamingException e) {
+                        // Ignore
+                    }
+                }
             }
         }
         LOG.debug("Group list: {}", groupIds);