001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nelson Silva <nelson.silva@inevo.pt>
018 */
019
020package org.nuxeo.ecm.platform.auth.saml.web;
021
022import org.apache.commons.logging.Log;
023import org.apache.commons.logging.LogFactory;
024import org.nuxeo.ecm.platform.auth.saml.SAMLConfiguration;
025import org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter;
026import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
027import org.opensaml.saml2.metadata.EntityDescriptor;
028import org.opensaml.xml.Configuration;
029import org.opensaml.xml.io.Marshaller;
030import org.opensaml.xml.io.MarshallingException;
031import org.opensaml.xml.util.XMLHelper;
032import org.w3c.dom.Element;
033
034import javax.servlet.http.HttpServlet;
035import javax.servlet.http.HttpServletRequest;
036import javax.servlet.http.HttpServletResponse;
037import java.io.IOException;
038
039/**
040 * Servlet that returns local SP metadata for configuring IdPs.
041 *
042 * @since 6.0
043 */
044public class MetadataServlet extends HttpServlet {
045
046    protected static final Log log = LogFactory.getLog(MetadataServlet.class);
047
048    @Override
049    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
050
051        String baseURL = VirtualHostHelper.getBaseURL(request);
052        baseURL += (baseURL.endsWith("/") ? "" : "/") + NuxeoAuthenticationFilter.DEFAULT_START_PAGE;
053
054        EntityDescriptor descriptor = SAMLConfiguration.getEntityDescriptor(baseURL);
055
056        try {
057            Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(descriptor);
058            if (marshaller == null) {
059                log.error("Unable to marshall message, no marshaller registered for message object: "
060                        + descriptor.getElementQName());
061            }
062            Element dom = marshaller.marshall(descriptor);
063            XMLHelper.writeNode(dom, response.getWriter());
064        } catch (MarshallingException e) {
065            log.error("Unable to write metadata.");
066        }
067    }
068}