cxf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From cohei...@apache.org
Subject [15/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR
Date Fri, 27 Jan 2017 11:22:58 GMT
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
new file mode 100644
index 0000000..7c5baec
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
@@ -0,0 +1,180 @@
+/**
+ * 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.service.idp.metadata;
+
+import java.security.cert.X509Certificate;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.w3c.dom.Document;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.core.util.SignatureUtils;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.staxutils.W3CDOMStreamWriter;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.apache.xml.security.utils.Base64;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.cxf.fediz.core.FedizConstants.SAML2_METADATA_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.SCHEMA_INSTANCE_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.WS_ADDRESSING_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.WS_FEDERATION_NS;
+
+public class IdpMetadataWriter {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(IdpMetadataWriter.class);
+    
+    //CHECKSTYLE:OFF
+    public Document getMetaData(Idp config) throws RuntimeException {
+        try {
+            //Return as text/xml
+            Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());
+
+            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
+
+            writer.writeStartDocument("UTF-8", "1.0");
+
+            String referenceID = IDGenerator.generateID("_");
+            writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS);
+            writer.writeAttribute("ID", referenceID);
+
+            writer.writeAttribute("entityID", config.getIdpUrl().toString());
+
+            writer.writeNamespace("md", SAML2_METADATA_NS);
+            writer.writeNamespace("fed", WS_FEDERATION_NS);
+            writer.writeNamespace("wsa", WS_ADDRESSING_NS);
+            writer.writeNamespace("auth", WS_FEDERATION_NS);
+            writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
+
+            writeFederationMetadata(writer, config, crypto);
+
+            writer.writeEndElement(); // EntityDescriptor
+
+            writer.writeEndDocument();
+
+            writer.close();
+
+            if (LOG.isDebugEnabled()) {
+                String out = DOM2Writer.nodeToString(writer.getDocument());
+                LOG.debug("***************** unsigned ****************");
+                LOG.debug(out);
+                LOG.debug("***************** unsigned ****************");
+            }
+
+            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), 
+                                                          writer.getDocument(), referenceID);
+            if (result != null) {
+                return result;
+            } else {
+                throw new RuntimeException("Failed to sign the metadata document: result=null");
+            }
+        } catch (Exception e) {
+            LOG.error("Error creating service metadata information ", e);
+            throw new RuntimeException("Error creating service metadata information: " + e.getMessage());
+        }
+
+    }
+    
+    private void writeFederationMetadata(
+        XMLStreamWriter writer, Idp config, Crypto crypto
+    ) throws XMLStreamException {
+
+        writer.writeStartElement("md", "RoleDescriptor", WS_FEDERATION_NS);
+        writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType");
+        writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
+        if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) {
+            writer.writeAttribute("ServiceDescription", config.getServiceDescription());
+        }
+        if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) {
+            writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName());
+        }
+
+        //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd
+        //missing organization, contactperson
+
+        //KeyDescriptor
+        writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS);
+        writer.writeAttribute("use", "signing");
+        writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
+        writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
+        writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
+
+        try {
+            String keyAlias = crypto.getDefaultX509Identifier();
+            X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
+            writer.writeCharacters(Base64.encode(cert.getEncoded()));
+        } catch (Exception ex) {
+            LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);
+        }
+
+        writer.writeEndElement(); // X509Certificate
+        writer.writeEndElement(); // X509Data
+        writer.writeEndElement(); // KeyInfo
+        writer.writeEndElement(); // KeyDescriptor
+
+
+        // SecurityTokenServiceEndpoint
+        writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS);
+        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
+
+        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
+        writer.writeCharacters(config.getStsUrl().toString());
+
+        writer.writeEndElement(); // Address
+        writer.writeEndElement(); // EndpointReference
+        writer.writeEndElement(); // SecurityTokenServiceEndpoint
+
+
+        // PassiveRequestorEndpoint
+        writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
+        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
+
+        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
+        writer.writeCharacters(config.getIdpUrl().toString());
+
+        writer.writeEndElement(); // Address
+        writer.writeEndElement(); // EndpointReference
+        writer.writeEndElement(); // PassiveRequestorEndpoint
+
+
+        // create ClaimsType section
+        if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) {
+            writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS);
+            for (Claim claim : config.getClaimTypesOffered()) {
+
+                writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS);
+                writer.writeAttribute("Uri", claim.getClaimType().toString());
+                writer.writeAttribute("Optional", "true");
+                writer.writeEndElement(); // ClaimType
+
+            }
+            writer.writeEndElement(); // ClaimTypesOffered
+        }
+
+        writer.writeEndElement(); // RoleDescriptor
+    }
+
+ 
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
new file mode 100644
index 0000000..3118d8f
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
@@ -0,0 +1,214 @@
+/**
+ * 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.service.idp.metadata;
+
+import java.security.cert.X509Certificate;
+import java.util.Map;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.w3c.dom.Document;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.core.util.SignatureUtils;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler;
+import org.apache.cxf.staxutils.W3CDOMStreamWriter;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.apache.xml.security.utils.Base64;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.cxf.fediz.core.FedizConstants.SAML2_METADATA_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.SCHEMA_INSTANCE_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.WS_ADDRESSING_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.WS_FEDERATION_NS;
+
+public class ServiceMetadataWriter {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(ServiceMetadataWriter.class);
+
+    //CHECKSTYLE:OFF
+    public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException {
+
+        try {
+            Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());
+            
+            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
+
+            writer.writeStartDocument("UTF-8", "1.0");
+
+            String referenceID = IDGenerator.generateID("_");
+            writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS);
+            writer.writeAttribute("ID", referenceID);
+            
+            String serviceURL = config.getIdpUrl().toString();
+            writer.writeAttribute("entityID", config.getRealm());
+            
+            writer.writeNamespace("md", SAML2_METADATA_NS);
+            writer.writeNamespace("fed", WS_FEDERATION_NS);
+            writer.writeNamespace("wsa", WS_ADDRESSING_NS);
+            writer.writeNamespace("auth", WS_FEDERATION_NS);
+            writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
+
+            if ("http://docs.oasis-open.org/wsfed/federation/200706".equals(serviceConfig.getProtocol())) {
+                writeFederationMetadata(writer, serviceConfig, serviceURL);
+            } else if ("urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser".equals(serviceConfig.getProtocol())) {
+                writeSAMLMetadata(writer, serviceConfig, serviceURL, crypto);
+            }
+            
+            writer.writeEndElement(); // EntityDescriptor
+
+            writer.writeEndDocument();
+            
+            writer.close();
+
+            if (LOG.isDebugEnabled()) {
+                String out = DOM2Writer.nodeToString(writer.getDocument());
+                LOG.debug("***************** unsigned ****************");
+                LOG.debug(out);
+                LOG.debug("***************** unsigned ****************");
+            }
+
+            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), 
+                                                          writer.getDocument(), referenceID);
+            if (result != null) {
+                return result;
+            } else {
+                throw new RuntimeException("Failed to sign the metadata document: result=null");
+            }
+        } catch (ProcessingException e) {
+            throw e;
+        } catch (Exception e) {
+            LOG.error("Error creating service metadata information ", e);
+            throw new ProcessingException("Error creating service metadata information: " + e.getMessage());
+        }
+
+    }
+
+    private void writeFederationMetadata(
+        XMLStreamWriter writer, 
+        TrustedIdp config,
+        String serviceURL
+    ) throws XMLStreamException {
+
+        writer.writeStartElement("md", "RoleDescriptor", WS_FEDERATION_NS);
+        writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:ApplicationServiceType");
+        writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
+
+        writer.writeStartElement("fed", "ApplicationServiceEndpoint", WS_FEDERATION_NS);
+        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
+
+        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
+        writer.writeCharacters(serviceURL);
+        
+        writer.writeEndElement(); // Address
+        writer.writeEndElement(); // EndpointReference
+        writer.writeEndElement(); // ApplicationServiceEndpoint
+
+        // create target scope element
+        writer.writeStartElement("fed", "TargetScope", WS_FEDERATION_NS);
+        writer.writeEndElement(); // TargetScope
+
+        // create sign in endpoint section
+
+        writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
+        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
+        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
+
+        writer.writeCharacters(serviceURL);
+
+        // writer.writeCharacters("http://host:port/url Issuer from config");
+        writer.writeEndElement(); // Address
+        writer.writeEndElement(); // EndpointReference
+
+        writer.writeEndElement(); // PassiveRequestorEndpoint
+        writer.writeEndElement(); // RoleDescriptor
+    }
+    
+    private void writeSAMLMetadata(
+        XMLStreamWriter writer, 
+        TrustedIdp config,
+        String serviceURL,
+        Crypto crypto
+    ) throws Exception {
+        
+        writer.writeStartElement("md", "SPSSODescriptor", SAML2_METADATA_NS);
+        boolean signRequest = 
+            isPropertyConfigured(config, TrustedIdpSAMLProtocolHandler.SIGN_REQUEST, true);
+        writer.writeAttribute("AuthnRequestsSigned", Boolean.toString(signRequest));
+        writer.writeAttribute("WantAssertionsSigned", "true");
+        writer.writeAttribute("protocolSupportEnumeration", "urn:oasis:names:tc:SAML:2.0:protocol");
+        
+        writer.writeStartElement("md", "AssertionConsumerService", SAML2_METADATA_NS);
+        writer.writeAttribute("Location", serviceURL);
+        writer.writeAttribute("index", "0");
+        writer.writeAttribute("isDefault", "true");
+        writer.writeAttribute("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
+        writer.writeEndElement(); // AssertionConsumerService
+        
+        if (signRequest) {
+            writer.writeStartElement("md", "KeyDescriptor", SAML2_METADATA_NS);
+            writer.writeAttribute("use", "signing");
+            
+            writer.writeStartElement("ds", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
+            writer.writeNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
+            writer.writeStartElement("ds", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
+            writer.writeStartElement("ds", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
+
+            // Write the Base-64 encoded certificate
+            
+            String keyAlias = crypto.getDefaultX509Identifier();
+            X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
+            
+            if (cert == null) {
+                throw new ProcessingException(
+                    "No signing certs were found to insert into the metadata using name: " 
+                        + keyAlias);
+            }
+            byte data[] = cert.getEncoded();
+            String encodedCertificate = Base64.encode(data);
+            writer.writeCharacters(encodedCertificate);
+            
+            writer.writeEndElement(); // X509Certificate
+            writer.writeEndElement(); // X509Data
+            writer.writeEndElement(); // KeyInfo
+            writer.writeEndElement(); // KeyDescriptor
+        }
+        
+        writer.writeEndElement(); // SPSSODescriptor
+    }
+    
+    // Is a property configured. Defaults to "true" if not
+    private boolean isPropertyConfigured(TrustedIdp trustedIdp, String property, boolean defaultValue) {
+        Map<String, String> parameters = trustedIdp.getParameters();
+        
+        if (parameters != null && parameters.containsKey(property)) {
+            return Boolean.parseBoolean(parameters.get(property));
+        }
+        
+        return defaultValue;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
new file mode 100644
index 0000000..9b9c5cd
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
@@ -0,0 +1,44 @@
+/**
+ * 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.service.idp.model;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+public class IDPConfig extends Idp {
+
+    private static final long serialVersionUID = -5570301342547139039L;
+
+    public void setServices(Map<String, Application> applications) {
+        this.applications = new ArrayList<>(applications.values());
+    }
+    
+    public void setTrustedIdps(Map<String, TrustedIDPConfig> trustedIdps) {
+        this.trustedIdpList = new ArrayList<TrustedIdp>(trustedIdps.values());
+    }
+    
+    @Deprecated
+    public void setTrustedIDPs(Map<String, TrustedIDPConfig> trustedIdps) {
+        setTrustedIdps(trustedIdps);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
new file mode 100644
index 0000000..6fd3d05
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
@@ -0,0 +1,26 @@
+/**
+ * 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.service.idp.model;
+
+//@XmlRootElement(name = "Claim", namespace = "http://org.apache.cxf.fediz")
+public class RequestClaim extends org.apache.cxf.fediz.service.idp.domain.RequestClaim {
+    
+    private static final long serialVersionUID = 2635896159019665467L;
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
new file mode 100644
index 0000000..fdae8f5
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
@@ -0,0 +1,35 @@
+/**
+ * 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.service.idp.model;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+
+//import javax.persistence.Column;
+//import javax.persistence.Entity;
+//import javax.persistence.Id;
+//import javax.persistence.Table;
+
+//@Entity
+//@Table(name = "SERVICE")
+//@XmlRootElement(name = "Service", namespace = "http://org.apache.cxf.fediz")
+public class ServiceConfig extends Application {
+        
+    private static final long serialVersionUID = 585676715065240699L;       
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
new file mode 100644
index 0000000..89c2bbb
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
@@ -0,0 +1,30 @@
+/**
+ * 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.service.idp.model;
+
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+//@XmlRootElement(name = "TrustedIDP", namespace = "http://org.apache.cxf.fediz")
+public class TrustedIDPConfig extends TrustedIdp {
+
+    private static final long serialVersionUID = -1182000443945024801L;
+
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
new file mode 100644
index 0000000..44cb3a2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
@@ -0,0 +1,36 @@
+/**
+ * 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.service.idp.model;
+
+import java.io.Serializable;
+
+public class TrustedIDPSelection implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+    
+    private String homeRealm;
+
+    public String getHomeRealm() {
+        return homeRealm;
+    }
+
+    public void setHomeRealm(String homeRealm) {
+        this.homeRealm = homeRealm;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
new file mode 100644
index 0000000..84a70ca
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
@@ -0,0 +1,207 @@
+/**
+ * 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.service.idp.protocols;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.Date;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.saml.SAMLCallback;
+import org.apache.wss4j.common.saml.SAMLUtil;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.wss4j.common.saml.bean.ConditionsBean;
+import org.apache.wss4j.common.saml.bean.SubjectBean;
+import org.apache.wss4j.common.saml.bean.Version;
+import org.apache.wss4j.common.saml.builder.SAML2Constants;
+import org.joda.time.DateTime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.webflow.execution.RequestContext;
+
+public abstract class AbstractTrustedIdpOAuth2ProtocolHandler extends AbstractTrustedIdpProtocolHandler {
+    
+    /**
+     * The client_id value to send to the IdP.
+     */
+    public static final String CLIENT_ID = "client.id";
+    
+    /**
+     * The secret associated with the client to authenticate to the IdP.
+     */
+    public static final String CLIENT_SECRET = "client.secret";
+    
+    /**
+     * The Token endpoint. The authorization endpoint is specified by TrustedIdp.url.
+     */
+    public static final String TOKEN_ENDPOINT = "token.endpoint";
+    
+    /**
+     * Additional (space-separated) parameters to be sent in the "scope" to the authorization endpoint.
+     * The default value depends on the subclass.
+     */
+    public static final String SCOPE = "scope";
+    
+    private static final Logger LOG = LoggerFactory.getLogger(AbstractTrustedIdpOAuth2ProtocolHandler.class);
+
+    @Override
+    public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+        
+        String clientId = getProperty(trustedIdp, CLIENT_ID);
+        if (clientId == null || clientId.isEmpty()) {
+            LOG.warn("A CLIENT_ID must be configured for OAuth 2.0");
+            throw new IllegalStateException("No CLIENT_ID specified");
+        }
+        
+        String scope = getScope(trustedIdp);
+        LOG.debug("Using scope: {}", scope);
+        
+        try {
+            StringBuilder sb = new StringBuilder();
+            sb.append(trustedIdp.getUrl());
+            sb.append("?");
+            sb.append("response_type").append('=');
+            sb.append("code");
+            sb.append("&");
+            sb.append("client_id").append('=');
+            sb.append(clientId);
+            sb.append("&");
+            sb.append("redirect_uri").append('=');
+            sb.append(URLEncoder.encode(idp.getIdpUrl().toString(), "UTF-8"));
+            sb.append("&");
+            sb.append("scope").append('=');
+            sb.append(URLEncoder.encode(scope, "UTF-8"));
+            
+            String state = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
+            sb.append("&").append("state").append('=');
+            sb.append(state);
+            
+            return new URL(sb.toString());
+        } catch (MalformedURLException ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        } catch (UnsupportedEncodingException ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        }
+    }
+    
+    protected SamlAssertionWrapper createSamlAssertion(Idp idp, TrustedIdp trustedIdp, String subjectName,
+                                                     Date notBefore,
+                                                     Date expires) throws Exception {
+        SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
+        String issuer = idp.getServiceDisplayName();
+        if (issuer == null) {
+            issuer = idp.getRealm();
+        }
+        if (issuer != null) {
+            callbackHandler.setIssuer(issuer);
+        }
+        
+        // Subject
+        SubjectBean subjectBean =
+            new SubjectBean(subjectName, SAML2Constants.NAMEID_FORMAT_UNSPECIFIED, SAML2Constants.CONF_BEARER);
+        callbackHandler.setSubjectBean(subjectBean);
+        
+        // Conditions
+        ConditionsBean conditionsBean = new ConditionsBean();
+        conditionsBean.setNotAfter(new DateTime(expires));
+        if (notBefore != null) {
+            DateTime notBeforeDT = new DateTime(notBefore);
+            conditionsBean.setNotBefore(notBeforeDT);
+        } else {
+            conditionsBean.setNotBefore(new DateTime());
+        }
+        callbackHandler.setConditionsBean(conditionsBean);
+        
+        SAMLCallback samlCallback = new SAMLCallback();
+        SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
+        
+        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
+        
+        Crypto crypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
+        assertion.signAssertion(crypto.getDefaultX509Identifier(), idp.getCertificatePassword(), 
+                                crypto, false);
+        
+        return assertion;
+    }
+    
+    private static class SamlCallbackHandler implements CallbackHandler {
+        private ConditionsBean conditionsBean;
+        private SubjectBean subjectBean;
+        private String issuer;
+        
+        /**
+         * Set the SubjectBean
+         */
+        public void setSubjectBean(SubjectBean subjectBean) {
+            this.subjectBean = subjectBean;
+        }
+        
+        /**
+         * Set the ConditionsBean
+         */
+        public void setConditionsBean(ConditionsBean conditionsBean) {
+            this.conditionsBean = conditionsBean;
+        }
+        
+        /**
+         * Set the issuer name
+         */
+        public void setIssuer(String issuerName) {
+            this.issuer = issuerName;
+        }
+        
+        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+            for (Callback callback : callbacks) {
+                if (callback instanceof SAMLCallback) {
+                    SAMLCallback samlCallback = (SAMLCallback) callback;
+
+                    // Set the Subject
+                    if (subjectBean != null) {
+                        samlCallback.setSubject(subjectBean);
+                    }
+                    samlCallback.setSamlVersion(Version.SAML_20);
+                    
+                    // Set the issuer
+                    samlCallback.setIssuer(issuer);
+
+                    // Set the conditions
+                    samlCallback.setConditions(conditionsBean);
+                }
+            }
+        }
+        
+    }
+    
+    abstract String getScope(TrustedIdp trustedIdp);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
new file mode 100644
index 0000000..2329eb2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
@@ -0,0 +1,58 @@
+/**
+ * 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.service.idp.protocols;
+
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
+
+public abstract class AbstractTrustedIdpProtocolHandler implements TrustedIdpProtocolHandler {
+    
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    protected String getProperty(TrustedIdp trustedIdp, String property) {
+        Map<String, String> parameters = trustedIdp.getParameters();
+        
+        if (parameters != null && parameters.containsKey(property)) {
+            return parameters.get(property);
+        }
+        
+        return null;
+    }
+    
+    // Is a property configured. Defaults to the boolean "defaultValue" if not
+    protected boolean isBooleanPropertyConfigured(TrustedIdp trustedIdp, String property, boolean defaultValue) {
+        Map<String, String> parameters = trustedIdp.getParameters();
+        
+        if (parameters != null && parameters.containsKey(property)) {
+            return Boolean.parseBoolean(parameters.get(property));
+        }
+        
+        return defaultValue;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
new file mode 100644
index 0000000..c2be3eb
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
@@ -0,0 +1,60 @@
+/**
+ * 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.service.idp.protocols;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ApplicationProtocolControllerImpl implements ProtocolController<ApplicationProtocolHandler> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ApplicationProtocolControllerImpl.class);
+    
+    @Autowired
+    private List<ApplicationProtocolHandler> protocolHandlers;
+    
+    @Override
+    public ApplicationProtocolHandler getProtocolHandler(String protocol) {
+        for (ApplicationProtocolHandler protocolHandler : protocolHandlers) {
+            if (protocolHandler.getProtocol() != null && protocolHandler.getProtocol().equals(protocol)) {
+                return protocolHandler;
+            }
+        }
+        LOG.warn("No protocol handler found for {}", protocol);
+        return null;
+    }
+    
+    @Override
+    public List<String> getProtocols() {
+        List<String> protocols = new ArrayList<>();
+        for (ApplicationProtocolHandler protocolHandler : protocolHandlers) {
+            protocols.add(protocolHandler.getProtocol());
+        }
+        return Collections.unmodifiableList(protocols);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
new file mode 100644
index 0000000..ebab362
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
@@ -0,0 +1,57 @@
+/**
+ * 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.service.idp.protocols;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
+
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+@Component
+public class ApplicationSAMLSSOProtocolHandler implements ApplicationProtocolHandler {
+    
+    public static final String PROTOCOL = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser";
+
+    //private static final Logger LOG = LoggerFactory.getLogger(ApplicationWSFedProtocolHandler.class);
+
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public void mapSignInRequest(RequestContext context) {
+        // TODO Auto-generated method stub
+    }
+
+    @Override
+    public void mapSignInResponse(RequestContext context) {
+        // TODO Auto-generated method stub
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
new file mode 100644
index 0000000..2024e3d
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
@@ -0,0 +1,57 @@
+/**
+ * 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.service.idp.protocols;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
+
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+@Component
+public class ApplicationWSFedProtocolHandler implements ApplicationProtocolHandler {
+    
+    public static final String PROTOCOL = "http://docs.oasis-open.org/wsfed/federation/200706";
+
+    //private static final Logger LOG = LoggerFactory.getLogger(ApplicationWSFedProtocolHandler.class);
+
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public void mapSignInRequest(RequestContext context) {
+        // TODO Auto-generated method stub
+    }
+
+    @Override
+    public void mapSignInResponse(RequestContext context) {
+        // TODO Auto-generated method stub
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
new file mode 100644
index 0000000..d4da6c2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
@@ -0,0 +1,32 @@
+/**
+ * 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.service.idp.protocols;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.spi.ProtocolHandler;
+
+public interface ProtocolController<T extends ProtocolHandler> {
+
+    T getProtocolHandler(String protocol);
+
+    List<String> getProtocols();
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
new file mode 100644
index 0000000..36db3ae
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
@@ -0,0 +1,226 @@
+/**
+ * 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.service.idp.protocols;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.Response;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.helpers.DOMUtils;
+import org.apache.cxf.interceptor.LoggingInInterceptor;
+import org.apache.cxf.interceptor.LoggingOutInterceptor;
+import org.apache.cxf.jaxrs.client.ClientConfiguration;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.jaxrs.json.basic.JsonMapObject;
+import org.apache.cxf.jaxrs.provider.json.JsonMapObjectProvider;
+import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
+import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider;
+import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Extension of AbstractTrustedIdpOAuth2ProtocolHandler for Facebook Connect.
+ * Default values:
+ *  - scope: email
+ *  - token.endpoint: https://graph.facebook.com/v2.6/oauth/access_token
+ */
+@Component
+public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2ProtocolHandler {
+    
+    /**
+     * The facebook API endpoint for querying claims (such as email address). If not specified
+     * it defaults to "https://graph.facebook.com/v2.6".
+     */
+    public static final String API_ENDPOINT = "api.endpoint";
+    
+    /**
+     * The Claim to use for the subject username to insert into the SAML Token. It defaults to 
+     * "email".
+     */
+    public static final String SUBJECT_CLAIM = "subject.claim";
+    
+    public static final String PROTOCOL = "facebook-connect";
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpFacebookProtocolHandler.class);
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+
+        String code = (String) WebUtils.getAttributeFromFlowScope(context,
+                                                                  OAuthConstants.CODE_RESPONSE_TYPE);
+        if (code != null && !code.isEmpty()) {
+            
+            String tokenEndpoint = getProperty(trustedIdp, TOKEN_ENDPOINT);
+            if (tokenEndpoint == null || tokenEndpoint.isEmpty()) {
+                tokenEndpoint = "https://graph.facebook.com/v2.6/oauth/access_token";
+            }
+            
+            String apiEndpoint = getProperty(trustedIdp, API_ENDPOINT);
+            if (apiEndpoint == null || apiEndpoint.isEmpty()) {
+                apiEndpoint = "https://graph.facebook.com/v2.6";
+            }
+            
+            String clientId = getProperty(trustedIdp, CLIENT_ID);
+            String clientSecret = getProperty(trustedIdp, CLIENT_SECRET);
+            if (clientSecret == null || clientSecret.isEmpty()) {
+                LOG.warn("A CLIENT_SECRET must be configured to use the TrustedIdpFacebookProtocolHandler");
+                throw new IllegalStateException("No CLIENT_SECRET specified");
+            }
+            
+            // Here we need to get the AccessToken using the authorization code
+            ClientAccessToken accessToken = getAccessTokenUsingCode(tokenEndpoint, code, clientId,
+                                                                    clientSecret, idp.getIdpUrl().toString());
+            if (accessToken == null || accessToken.getTokenKey() == null) {
+                LOG.warn("No Access Token received from the Facebook IdP");
+                return null;
+            }
+            
+            // Now we need to invoke on the API endpoint using the access token to get the 
+            // user's claims
+            String subjectName = getSubjectName(apiEndpoint, accessToken.getTokenKey(), trustedIdp);
+            try {
+                String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
+                if (whr == null) {
+                    LOG.warn("Home realm is null");
+                    throw new IllegalStateException("Home realm is null");
+                }
+        
+                // Convert into a SAML Token
+                Date expires = new Date();
+                expires.setTime(expires.getTime() + (accessToken.getExpiresIn() * 1000L));
+                SecurityToken idpToken = new SecurityToken(IDGenerator.generateID(null), null, expires);
+                SamlAssertionWrapper assertion = 
+                    createSamlAssertion(idp, trustedIdp, subjectName, null, expires);
+                Document doc = DOMUtils.createDocument();
+                Element token = assertion.toDOM(doc);
+        
+                // Create new Security token with new id. 
+                // Parameters for freshness computation are copied from original IDP_TOKEN
+                idpToken.setToken(token);
+        
+                LOG.info("[IDP_TOKEN={}] for user '{}' issued by home realm [{}]",
+                         assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(), 
+                         whr);
+                LOG.debug("Expired date={}", expires);
+                
+                return idpToken;
+            } catch (IllegalStateException ex) {
+                throw ex;
+            } catch (Exception ex) {
+                LOG.warn("Unexpected exception occured", ex);
+                throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
+            }
+        }
+        return null;
+    }
+    
+    private ClientAccessToken getAccessTokenUsingCode(String tokenEndpoint, String code, String clientId,
+                                                      String clientSecret, String redirectURI) {
+        // Here we need to get the AccessToken using the authorization code
+        List<Object> providers = new ArrayList<Object>();
+        providers.add(new OAuthJSONProvider());
+        
+        WebClient client = 
+            WebClient.create(tokenEndpoint, providers, "cxf-tls.xml");
+        
+        ClientConfiguration config = WebClient.getConfig(client);
+
+        if (LOG.isDebugEnabled()) {
+            config.getOutInterceptors().add(new LoggingOutInterceptor());
+            config.getInInterceptors().add(new LoggingInInterceptor());
+        }
+        
+        client.type("application/x-www-form-urlencoded");
+        client.accept("application/json");
+
+        Form form = new Form();
+        form.param("grant_type", "authorization_code");
+        form.param("code", code);
+        form.param("client_id", clientId);
+        form.param("redirect_uri", redirectURI);
+        form.param("client_secret", clientSecret);
+        Response response = client.post(form);
+
+        return response.readEntity(ClientAccessToken.class);
+    }
+    
+    private String getSubjectName(String apiEndpoint, String accessToken, TrustedIdp trustedIdp) {
+        WebClient client = WebClient.create(apiEndpoint, 
+                                  Collections.singletonList(new JsonMapObjectProvider()), 
+                                  "cxf-tls.xml");
+        client.path("/me");
+        ClientConfiguration config = WebClient.getConfig(client);
+
+        if (LOG.isDebugEnabled()) {
+            config.getOutInterceptors().add(new LoggingOutInterceptor());
+            config.getInInterceptors().add(new LoggingInInterceptor());
+        }
+
+        client.accept("application/json");
+        client.query("access_token", accessToken);
+        
+        String subjectName = getProperty(trustedIdp, SUBJECT_CLAIM);
+        if (subjectName == null || subjectName.isEmpty()) {
+            subjectName = "email";
+        }
+        client.query("fields", subjectName);
+        JsonMapObject mapObject = client.get(JsonMapObject.class);
+        
+        String parsedSubjectName = (String)mapObject.getProperty(subjectName);
+        if (subjectName.contains("email")) {
+            parsedSubjectName = parsedSubjectName.replace("\\u0040", "@");
+        }
+        return parsedSubjectName;
+    }
+    
+    protected String getScope(TrustedIdp trustedIdp) {
+        String scope = getProperty(trustedIdp, SCOPE);
+        if (scope != null) {
+            scope = scope.trim();
+        }
+        
+        if (scope == null || scope.isEmpty()) {
+            scope = "email";
+        }
+        return scope;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
new file mode 100644
index 0000000..b45c763
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
@@ -0,0 +1,335 @@
+/**
+ * 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.service.idp.protocols;
+
+import java.io.IOException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.Response;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.core.util.DOMUtils;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.interceptor.LoggingInInterceptor;
+import org.apache.cxf.interceptor.LoggingOutInterceptor;
+import org.apache.cxf.jaxrs.client.ClientConfiguration;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.rs.security.jose.common.JoseConstants;
+import org.apache.cxf.rs.security.jose.jaxrs.JsonWebKeysProvider;
+import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm;
+import org.apache.cxf.rs.security.jose.jwk.JsonWebKey;
+import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys;
+import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer;
+import org.apache.cxf.rs.security.jose.jwt.JwtConstants;
+import org.apache.cxf.rs.security.jose.jwt.JwtToken;
+import org.apache.cxf.rs.security.jose.jwt.JwtUtils;
+import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
+import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider;
+import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.xml.security.exceptions.Base64DecodingException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Extension of AbstractTrustedIdpOAuth2ProtocolHandler for OpenId Connect.
+ * Default values:
+ *  - scope: openid
+ */
+@Component
+public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2ProtocolHandler {
+    
+    /**
+     * The signature algorithm to use in verifying the IdToken. The default is "RS256".
+     */
+    public static final String SIGNATURE_ALGORITHM = "signature.algorithm";
+    
+    /**
+     * The Claim in which to extract the Subject username to insert into the generated SAML token. 
+     * It defaults to "preferred_username", otherwise it falls back to the "sub" claim.
+     */
+    public static final String SUBJECT_CLAIM = "subject.claim";
+    
+    /**
+     * Additional (space-separated) parameters to be sent in the "scope" to the authorization endpoint.
+     * Fediz will automatically use "openid" for this value. 
+     */
+    public static final String SCOPE = "scope";
+    
+    /**
+     * The URI from which to retrieve the JSON Web Keys to validate the signed IdToken.
+     */
+    public static final String JWKS_URI = "jwks.uri";
+    
+    public static final String PROTOCOL = "openid-connect-1.0";
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpOIDCProtocolHandler.class);
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+
+        String code = (String) WebUtils.getAttributeFromFlowScope(context,
+                                                                  OAuthConstants.CODE_RESPONSE_TYPE);
+        if (code != null && !code.isEmpty()) {
+            
+            String tokenEndpoint = getProperty(trustedIdp, TOKEN_ENDPOINT);
+            if (tokenEndpoint == null || tokenEndpoint.isEmpty()) {
+                LOG.warn("A TOKEN_ENDPOINT must be configured to use the OIDCProtocolHandler");
+                throw new IllegalStateException("No TOKEN_ENDPOINT specified");
+            }
+            
+            String clientId = getProperty(trustedIdp, CLIENT_ID);
+            String clientSecret = getProperty(trustedIdp, CLIENT_SECRET);
+            if (clientSecret == null || clientSecret.isEmpty()) {
+                LOG.warn("A CLIENT_SECRET must be configured to use the OIDCProtocolHandler");
+                throw new IllegalStateException("No CLIENT_SECRET specified");
+            }
+            
+            // Here we need to get the IdToken using the authorization code
+            List<Object> providers = new ArrayList<Object>();
+            providers.add(new OAuthJSONProvider());
+            
+            WebClient client = 
+                WebClient.create(tokenEndpoint, providers, clientId, clientSecret, "cxf-tls.xml");
+            
+            ClientConfiguration config = WebClient.getConfig(client);
+
+            if (LOG.isDebugEnabled()) {
+                config.getOutInterceptors().add(new LoggingOutInterceptor());
+                config.getInInterceptors().add(new LoggingInInterceptor());
+            }
+            
+            client.type("application/x-www-form-urlencoded").accept("application/json");
+
+            Form form = new Form();
+            form.param("grant_type", "authorization_code");
+            form.param("code", code);
+            form.param("client_id", clientId);
+            form.param("redirect_uri", idp.getIdpUrl().toString());
+            Response response = client.post(form);
+
+            ClientAccessToken accessToken = response.readEntity(ClientAccessToken.class);
+            String idToken = accessToken.getParameters().get("id_token");
+            if (idToken == null) {
+                LOG.warn("No IdToken received from the OIDC IdP");
+                return null;
+            }
+            
+            client.close();
+            
+            try {
+                String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
+                if (whr == null) {
+                    LOG.warn("Home realm is null");
+                    throw new IllegalStateException("Home realm is null");
+                }
+        
+                // Parse the received Token
+                JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
+                JwtToken jwt = jwtConsumer.getJwtToken();
+                
+                if (jwt != null && jwt.getClaims() != null && LOG.isDebugEnabled()) {
+                    LOG.debug("Received Claims:");
+                    for (Map.Entry<String, Object> claim : jwt.getClaims().asMap().entrySet()) {
+                        LOG.debug(claim.getKey() + ": " + claim.getValue());
+                    }
+                }
+                
+                if (jwt != null && jwt.getJwsHeaders() != null && LOG.isDebugEnabled()) {
+                    LOG.debug("Received JWS Headers:");
+                    for (Map.Entry<String, Object> header : jwt.getJwsHeaders().asMap().entrySet()) {
+                        LOG.debug(header.getKey() + ": " + header.getValue());
+                    }
+                }
+                
+                if (!validateSignature(trustedIdp, jwtConsumer)) {
+                    LOG.warn("Signature does not validate");
+                    return null;
+                }
+                
+                // Make sure the received token is valid according to the spec
+                validateToken(jwt, clientId);
+                
+                Date created = new Date((long)jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) * 1000L);
+                Date notBefore = null;
+                if (jwt.getClaim(JwtConstants.CLAIM_NOT_BEFORE) != null) {
+                    notBefore = new Date((long)jwt.getClaim(JwtConstants.CLAIM_NOT_BEFORE) * 1000L);
+                } 
+                
+                Date expires = new Date((long)jwt.getClaim(JwtConstants.CLAIM_EXPIRY) * 1000L);
+                
+                // Subject
+                String subjectName = getProperty(trustedIdp, SUBJECT_CLAIM);
+                LOG.debug("Trying to extract subject name using the claim name {}", subjectName);
+                if (subjectName == null || jwt.getClaim(subjectName) == null) {
+                    LOG.debug("No claim available in the token for {}", subjectName);
+                    subjectName = "preferred_username";
+                    LOG.debug("Falling back to use subject claim name {}", subjectName);
+                    if (subjectName == null || jwt.getClaim(subjectName) == null) {
+                        subjectName = JwtConstants.CLAIM_SUBJECT;
+                        LOG.debug("No claim available in the token for preferred_username. "
+                                  + "Falling back to use {}", subjectName);
+                    }
+                }
+                
+                // Convert into a SAML Token
+                SamlAssertionWrapper assertion = 
+                    createSamlAssertion(idp, trustedIdp, (String)jwt.getClaim(subjectName), notBefore, expires);
+                Document doc = DOMUtils.createDocument();
+                Element token = assertion.toDOM(doc);
+        
+                // Create new Security token with new id. 
+                // Parameters for freshness computation are copied from original IDP_TOKEN
+                SecurityToken idpToken = new SecurityToken(assertion.getId(), created, expires);
+                idpToken.setToken(token);
+        
+                LOG.info("[IDP_TOKEN={}] for user '{}' created from [RP_TOKEN={}] issued by home realm [{}/{}]",
+                         assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(), 
+                         jwt.getClaim(JwtConstants.CLAIM_JWT_ID), whr, jwt.getClaim(JwtConstants.CLAIM_ISSUER));
+                LOG.debug("Created date={}", created);
+                LOG.debug("Expired date={}", expires);
+                
+                return idpToken;
+            } catch (IllegalStateException ex) {
+                throw ex;
+            } catch (Exception ex) {
+                LOG.warn("Unexpected exception occured", ex);
+                throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
+            }
+        }
+        return null;
+    }
+    
+    protected void validateToken(JwtToken jwt, String clientId) {
+        // We must have the following claims
+        if (jwt.getClaim(JwtConstants.CLAIM_ISSUER) == null
+            || jwt.getClaim(JwtConstants.CLAIM_SUBJECT) == null
+            || jwt.getClaim(JwtConstants.CLAIM_AUDIENCE) == null
+            || jwt.getClaim(JwtConstants.CLAIM_EXPIRY) == null
+            || jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) == null) {
+            LOG.warn("The IdToken is missing a required claim");
+            throw new IllegalStateException("The IdToken is missing a required claim");
+        }
+        
+        // The audience must match the client_id of this client
+        boolean match = false;
+        for (String audience : jwt.getClaims().getAudiences()) {
+            if (clientId.equals(audience)) {
+                match = true;
+                break;
+            }
+        }
+        if (!match) {
+            LOG.warn("The audience of the token does not match this client");
+            throw new IllegalStateException("The audience of the token does not match this client");
+        }
+        
+        JwtUtils.validateTokenClaims(jwt.getClaims(), 300, 0, false);
+    }
+    
+    private boolean validateSignature(TrustedIdp trustedIdp, JwsJwtCompactConsumer jwtConsumer) 
+        throws CertificateException, WSSecurityException, Base64DecodingException, 
+            ProcessingException, IOException {
+        
+        // Validate the Signature
+        String sigAlgo = getProperty(trustedIdp, SIGNATURE_ALGORITHM);
+        if (sigAlgo == null || sigAlgo.isEmpty()) {
+            sigAlgo = "RS256";
+        }
+        
+        JwtToken jwt = jwtConsumer.getJwtToken();
+        String jwksUri = getProperty(trustedIdp, JWKS_URI);
+        JsonWebKey verifyingKey = null;
+        
+        if (jwksUri != null && jwt.getJwsHeaders() != null 
+            && jwt.getJwsHeaders().containsHeader(JoseConstants.HEADER_KEY_ID)) {
+            String kid = (String)jwt.getJwsHeaders().getHeader(JoseConstants.HEADER_KEY_ID);
+            LOG.debug("Attemping to retrieve key id {} from uri {}", kid, jwksUri);
+            List<Object> jsonKeyProviders = new ArrayList<Object>();
+            jsonKeyProviders.add(new JsonWebKeysProvider());
+            
+            WebClient client = 
+                WebClient.create(jwksUri, jsonKeyProviders, "cxf-tls.xml");
+            client.accept("application/json");
+            
+            ClientConfiguration config = WebClient.getConfig(client);
+            if (LOG.isDebugEnabled()) {
+                config.getOutInterceptors().add(new LoggingOutInterceptor());
+                config.getInInterceptors().add(new LoggingInInterceptor());
+            }
+            
+            Response response = client.get();
+            JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);
+            if (jsonWebKeys != null) {
+                verifyingKey = jsonWebKeys.getKey(kid);
+            }
+        }
+        
+        if (verifyingKey != null) {
+            return jwtConsumer.verifySignatureWith(verifyingKey, SignatureAlgorithm.getAlgorithm(sigAlgo));
+        }
+        
+        X509Certificate validatingCert = CertsUtils.parseX509Certificate(trustedIdp.getCertificate());
+        if (validatingCert != null) {
+            return jwtConsumer.verifySignatureWith(validatingCert, SignatureAlgorithm.getAlgorithm(sigAlgo));
+        }
+        
+        LOG.warn("No key supplied to verify the signature of the IdToken");
+        return false;
+    }
+    
+    protected String getScope(TrustedIdp trustedIdp) {
+        String scope = getProperty(trustedIdp, SCOPE);
+        if (scope != null) {
+            scope = scope.trim();
+            if (!scope.contains("openid")) {
+                scope = "openid " + scope;
+            }
+        }
+        
+        if (scope == null || scope.isEmpty()) {
+            scope = "openid";
+        }
+        return scope;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
new file mode 100644
index 0000000..31bc572
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
@@ -0,0 +1,60 @@
+/**
+ * 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.service.idp.protocols;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class TrustedIdpProtocolControllerImpl implements ProtocolController<TrustedIdpProtocolHandler> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpProtocolControllerImpl.class);
+    
+    @Autowired
+    private List<TrustedIdpProtocolHandler> protocolHandlers;
+    
+    @Override
+    public TrustedIdpProtocolHandler getProtocolHandler(String protocol) {
+        for (TrustedIdpProtocolHandler protocolHandler : protocolHandlers) {
+            if (protocolHandler.getProtocol().equals(protocol)) {
+                return protocolHandler;
+            }
+        }
+        LOG.warn("No protocol handler found for {}", protocol);
+        return null;
+    }
+    
+    @Override
+    public List<String> getProtocols() {
+        List<String> protocols = new ArrayList<>();
+        for (TrustedIdpProtocolHandler protocolHandler : protocolHandlers) {
+            protocols.add(protocolHandler.getProtocol());
+        }
+        return Collections.unmodifiableList(protocols);
+    }
+
+}


Mime
View raw message