at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet.java Source code

Java tutorial

Introduction

Here is the source code for at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet.java

Source

/*******************************************************************************
 * Copyright 2014 Federal Chancellery Austria
 * MOA-ID has been developed in a cooperation between BRZ, the Federal
 * Chancellery Austria - ICT staff unit, and Graz University of Technology.
 * 
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
 * the European Commission - subsequent versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 * http://www.osor.eu/eupl/
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 * 
 * This product combines work with different licenses. See the "NOTICE" text
 * file for details on the various modules and licenses.
 * The "NOTICE" text file is part of the distribution. Any derivative works
 * that you distribute must include a readable copy of the "NOTICE" text file.
 ******************************************************************************/
/*
 * Copyright 2003 Federal Chancellery Austria
 * MOA-ID has been developed in a cooperation between BRZ, the Federal
 * Chancellery Austria - ICT staff unit, and Graz University of Technology.
 *
 * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
 * the European Commission - subsequent versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 * http://www.osor.eu/eupl/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the Licence is distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Licence for the specific language governing permissions and
 * limitations under the Licence.
 *
 * This product combines work with different licenses. See the "NOTICE" text
 * file for details on the various modules and licenses.
 * The "NOTICE" text file is part of the distribution. Any derivative works
 * that you distribute must include a readable copy of the "NOTICE" text file.
 */

package at.gv.egovernment.moa.id.auth.servlet;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.TransformerException;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang.StringEscapeUtils;
import org.w3c.dom.Element;

import at.gv.egovernment.moa.id.auth.AuthenticationServer;
import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse;
import at.gv.egovernment.moa.id.auth.data.IdentityLink;
import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
import at.gv.egovernment.moa.id.auth.exception.ParseException;
import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
import at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetForeignIDTask;
import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser;
import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser;
import at.gv.egovernment.moa.id.client.SZRGWClientException;
import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
import at.gv.egovernment.moa.id.moduls.ModulUtils;
import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
import at.gv.egovernment.moa.logging.Logger;
import at.gv.egovernment.moa.util.DOMUtils;
import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse;

/**
 * Servlet requested for getting the foreign eID
 * provided by the security layer implementation.
 * Utilizes the {@link AuthenticationServer}.
 * @deprecated Use {@link GetForeignIDTask} instead.
 *
 */
public class GetForeignIDServlet extends AuthServlet {

    /**
      * 
      */
    private static final long serialVersionUID = -3415644214702379483L;

    /**
       * Constructor for GetForeignIDServlet.
       */
    public GetForeignIDServlet() {
        super();
    }

    /**
     * GET requested by security layer implementation to verify
     * that data URL resource is available.
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse)
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        super.doGet(req, resp);
    }

    /**
     * Verifies the identity link and responds with a new 
     * <code>CreateXMLSignatureRequest</code>.
     * <br>
     * Request parameters:
     * <ul>
     * <li>MOASessionID: ID of associated authentication session</li>
     * <li>XMLResponse: <code>&lt;InfoboxReadResponse&gt;</code></li>
     * </ul>
     * Response:
     * <ul>
     * <li>Content type: <code>"text/xml"</code></li>
     * <li>Content: see return value of {@link AuthenticationServer#verifyIdentityLink}</li>
     * <li>Error status: <code>500</code>
     * </ul>
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse)
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Logger.debug("POST GetForeignIDServlet");

        Logger.warn(getClass().getName() + " is deprecated and should not be used any more.");

        resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
        resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
        resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
        resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

        Map<String, String> parameters;

        String pendingRequestID = null;

        try {
            parameters = getParameters(req);
        } catch (FileUploadException e) {
            Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
            throw new IOException(e.getMessage());
        }
        String sessionID = req.getParameter(PARAM_SESSIONID);
        pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID);

        // escape parameter strings
        sessionID = StringEscapeUtils.escapeHtml(sessionID);

        String redirectURL = null;
        AuthenticationSession session = null;
        try {
            String xmlCreateXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE);
            // check parameter
            if (!ParamValidatorUtils.isValidSessionID(sessionID))
                throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12");
            if (!ParamValidatorUtils.isValidXMLDocument(xmlCreateXMLSignatureResponse))
                throw new WrongParametersException("GetForeignID", PARAM_XMLRESPONSE, "auth.12");

            session = AuthenticationServer.getSession(sessionID);

            //change MOASessionID
            sessionID = AuthenticationSessionStoreage.changeSessionID(session);

            Logger.debug(xmlCreateXMLSignatureResponse);

            CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse)
                    .parseResponseDsig();

            try {
                String serializedAssertion = DOMUtils.serializeNode(csresp.getDsigSignature());
                session.setAuthBlock(serializedAssertion);

            } catch (TransformerException e) {
                throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE });

            } catch (IOException e) {
                throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE });

            }

            Element signature = csresp.getDsigSignature();

            try {
                session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature));
            } catch (CertificateException e) {
                Logger.error("Could not extract certificate from CreateXMLSignatureResponse");
                throw new MOAIDException("auth.14", null);
            }

            // make SZR request to the identity link
            CreateIdentityLinkResponse response = AuthenticationServer.getInstance().getIdentityLink(signature);

            if (null != response.getErrorResponse()) {
                // TODO fix exception parameter
                throw new SZRGWClientException("service.08", (String) response.getErrorResponse().getErrorCode(),
                        (String) response.getErrorResponse().getInfo());
            } else {
                IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(
                        new ByteArrayInputStream(response.getIdentityLink()));
                IdentityLink identitylink = ilParser.parseIdentityLink();
                session.setIdentityLink(identitylink);

                //set QAA Level four in case of card authentifcation
                session.setQAALevel(PVPConstants.STORK_QAA_1_4);

                String samlArtifactBase64 = AuthenticationServer.getInstance()
                        .getForeignAuthenticationData(session);

                //session is implicit stored in changeSessionID!!!! 
                String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session);

                Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID);
                Logger.info("Daten angelegt zu MOASession " + newMOASessionID);

                if (!samlArtifactBase64.equals("Redirect to Input Processor")) {
                    /*redirectURL = session.getOAURLRequested();
                    if (!session.getBusinessService()) {
                       redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8"));
                    }
                    redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8"));
                    redirectURL = resp.encodeRedirectURL(redirectURL);*/

                    redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(),
                            ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID),
                            newMOASessionID);
                    redirectURL = resp.encodeRedirectURL(redirectURL);

                } else {
                    redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(),
                            AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, newMOASessionID);

                }

                try {
                    AuthenticationSessionStoreage.storeSession(session);
                } catch (MOADatabaseException e) {
                    throw new MOAIDException("Session store error", null);
                }

                resp.setContentType("text/html");
                resp.setStatus(302);
                resp.addHeader("Location", redirectURL);
                Logger.debug("REDIRECT TO: " + redirectURL);
            }

        } catch (MOAIDException ex) {
            handleError(null, ex, req, resp, pendingRequestID);

        } catch (Exception e) {
            Logger.error("GetForeignIDServlet has an interal Error.", e);

        }
    }

    /**
     * Builds the szrgw:GetIdentityLinkRequest fuer the SZR-GW
     * @param givenname
     * @param familyname
     * @param birthday
     * @return
     */
    //  private static Document buildGetIdentityLinkRequest(X509Certificate cert) {
    //     
    //     try {
    //           byte[] certbyte = cert.getEncoded();
    //           String certstring = Base64.encode(certbyte); 
    //         
    //         DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
    //         factory.setNamespaceAware(true);
    //           DocumentBuilder builder = factory.newDocumentBuilder();
    //           Document doc = builder.newDocument();
    //           
    //           Element getIdentityLink = doc.createElementNS(SZRGWConstants.SZRGW_REQUEST_NS, "szrgw:GetIdentityLinkRequest");
    //           getIdentityLink.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:szrgw", SZRGWConstants.SZRGW_REQUEST_NS);
    //           doc.appendChild(getIdentityLink);
    //           
    //           Element x509certificate = doc.createElementNS(SZRGWConstants.SZRGW_REQUEST_NS, "szrgw:X509Certificate");
    //           getIdentityLink.appendChild(x509certificate);
    //           Text certbase64 = doc.createTextNode(certstring);
    //           x509certificate.appendChild(certbase64);
    //                             
    //           return doc;
    //       } catch (ParserConfigurationException e) {
    //          e.printStackTrace();
    //       } catch (CertificateEncodingException e) {
    //         e.printStackTrace();
    //      }
    //       return null;
    //   
    //   }
    //  
    //    /**
    //   * Checks a parameter.
    //   * @param param parameter
    //   * @return true if the parameter is null or empty
    //   */
    //  private boolean isEmpty(String param) {
    //    return param == null || param.length() == 0;
    //  }

}