001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nelson Silva <nelson.silva@inevo.pt>
016 */
017
018package org.nuxeo.ecm.platform.auth.saml.web;
019
020import org.apache.commons.logging.Log;
021import org.apache.commons.logging.LogFactory;
022import org.nuxeo.ecm.platform.auth.saml.SAMLConfiguration;
023import org.nuxeo.ecm.platform.ui.web.auth.NuxeoAuthenticationFilter;
024import org.nuxeo.ecm.platform.web.common.vh.VirtualHostHelper;
025import org.opensaml.saml2.metadata.EntityDescriptor;
026import org.opensaml.xml.Configuration;
027import org.opensaml.xml.io.Marshaller;
028import org.opensaml.xml.io.MarshallingException;
029import org.opensaml.xml.util.XMLHelper;
030import org.w3c.dom.Element;
031
032import javax.servlet.http.HttpServlet;
033import javax.servlet.http.HttpServletRequest;
034import javax.servlet.http.HttpServletResponse;
035import java.io.IOException;
036
037/**
038 * Servlet that returns local SP metadata for configuring IdPs.
039 *
040 * @since 6.0
041 */
042public class MetadataServlet extends HttpServlet {
043
044    protected static final Log log = LogFactory.getLog(MetadataServlet.class);
045
046    @Override
047    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
048
049        String baseURL = VirtualHostHelper.getBaseURL(request);
050        baseURL += (baseURL.endsWith("/") ? "" : "/") + NuxeoAuthenticationFilter.DEFAULT_START_PAGE;
051
052        EntityDescriptor descriptor = SAMLConfiguration.getEntityDescriptor(baseURL);
053
054        try {
055            Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(descriptor);
056            if (marshaller == null) {
057                log.error("Unable to marshall message, no marshaller registered for message object: "
058                        + descriptor.getElementQName());
059            }
060            Element dom = marshaller.marshall(descriptor);
061            XMLHelper.writeNode(dom, response.getWriter());
062        } catch (MarshallingException e) {
063            log.error("Unable to write metadata.");
064        }
065    }
066}