aboutsummaryrefslogtreecommitdiff
path: root/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth
diff options
context:
space:
mode:
Diffstat (limited to 'id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth')
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java39
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java113
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java225
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java447
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java228
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java451
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java791
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java64
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java286
9 files changed, 0 insertions, 2644 deletions
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java
deleted file mode 100644
index 41384690e..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package at.gv.egovernment.moa.id.auth.modules.stork;
-
-import org.apache.commons.lang3.StringUtils;
-
-import at.gv.egovernment.moa.id.auth.modules.AuthModule;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-
-/**
- * Module descriptor for an auth module providing stork authentication related processes.
- * @author tknall
- */
-public class STORKAuthModuleImpl implements AuthModule {
-
- private int priority = 0;
-
- @Override
- public int getPriority() {
- return priority;
- }
-
- /**
- * Sets the priority of this module. Default value is {@code 0}.
- * @param priority The priority.
- */
- public void setPriority(int priority) {
- this.priority = priority;
- }
-
- @Override
- public String selectProcess(ExecutionContext context) {
- return StringUtils.isNotBlank((String) context.get("ccc")) ? "STORKAuthentication" : null;
- }
-
- @Override
- public String[] getProcessDefinitions() {
- return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthentication.process.xml" };
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java
deleted file mode 100644
index efc1cd498..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java
+++ /dev/null
@@ -1,113 +0,0 @@
-package at.gv.egovernment.moa.id.auth.modules.stork;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.servlet.annotation.WebServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathFactory;
-
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.util.xml.SimpleNamespaceContext;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
-import at.gv.egovernment.moa.id.auth.servlet.ProcessEngineSignalServlet;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.Base64Utils;
-
-/**
- * STORK module specific servlet, overloading {@link ProcessEngineSignalServlet}'s method
- * {@linkplain ProcessEngineSignalServlet#getMoaSessionId(HttpServletRequest) getMoaSessionId(HttpServletRequest)}
- * extending its capabilities for retrieving the current moa session id.
- * <p/>
- * This {@code STORKProcessEngineSignalServlet} tries to resolve the moa session id using the following strategy:
- * <ul>
- * <li>Use the super class' approach, looking at the HttpServletRequest parameter
- * {@link MOAIDAuthConstants#PARAM_SESSIONID}.</li>
- * <li>Evaluate the request parameter "{@code RelayState}".
- * <li>Finally evaluate the SAML response, which should come base64 encoded as request parameter "{@code SAMLResponse}".</li>
- * </ul>
- *
- * @author tknall
- *
- */
-@WebServlet(urlPatterns = { "/PEPSConnectorWithLocalSigning", "/PEPSConnector" }, loadOnStartup = 1)
-public class STORKProcessEngineSignalServlet extends ProcessEngineSignalServlet {
-
- private static final long serialVersionUID = 1L;
-
- public STORKProcessEngineSignalServlet() {
- super();
- Logger.debug("Registering servlet " + getClass().getName() + " with mappings '/PEPSConnectorWithLocalSigning', '/PEPSConnector'.");
- }
-
- @Override
- public String getMoaSessionId(HttpServletRequest request) {
- String sessionId = super.getMoaSessionId(request);
-
- try {
-
- // use SAML2 relayState
- if (sessionId == null) {
- sessionId = StringEscapeUtils.escapeHtml(request.getParameter("RelayState"));
- }
-
- // take from InResponseTo attribute of SAMLResponse
- if (sessionId == null) {
- String base64SamlToken = request.getParameter("SAMLResponse");
- if (base64SamlToken != null) {
- byte[] samlToken = Base64Utils.decode(base64SamlToken, false);
- Document samlResponse = parseDocument(new ByteArrayInputStream(samlToken));
-
- XPath xPath = XPathFactory.newInstance().newXPath();
- SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
- nsContext.bindNamespaceUri("saml2p", "urn:oasis:names:tc:SAML:2.0:protocol");
- xPath.setNamespaceContext(nsContext);
- XPathExpression expression = xPath.compile("string(/saml2p:Response/@InResponseTo)");
- sessionId = (String) expression.evaluate(samlResponse, XPathConstants.STRING);
- sessionId = StringEscapeUtils.escapeHtml(StringUtils.trimToNull(sessionId));
- } else {
- Logger.warn("No parameter 'SAMLResponse'. Unable to retrieve MOA session id.");
- }
- }
-
- } catch (Exception e) {
- Logger.warn("Unable to retrieve moa session id.", e);
- }
-
- return sessionId;
- }
-
- /**
- * Parses a xml document (namespace aware).
- *
- * @param in
- * The input stream.
- * @return The DOM document.
- * @throws ParserConfigurationException
- * Thrown in case of configuration error.
- * @throws IOException
- * Thrown in case of error reading from the input stream.
- * @throws SAXException
- * Thrown in case of error parsing the document.
- */
- public static Document parseDocument(InputStream in) throws ParserConfigurationException, SAXException, IOException {
- DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
- documentBuilderFactory.setNamespaceAware(true);
- documentBuilderFactory.setIgnoringElementContentWhitespace(false);
- documentBuilderFactory.setValidating(false);
- DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
- return documentBuilder.parse(in);
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java
deleted file mode 100644
index 939390847..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java
+++ /dev/null
@@ -1,225 +0,0 @@
-package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import iaik.x509.X509Certificate;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.security.cert.CertificateException;
-import java.util.HashMap;
-
-import javax.activation.DataSource;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactoryConfigurationError;
-
-import org.apache.commons.io.IOUtils;
-import org.xml.sax.SAXException;
-
-import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
-import at.gv.egovernment.moa.id.auth.data.IdentityLink;
-import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.BKUException;
-import at.gv.egovernment.moa.id.auth.exception.BuildException;
-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.ServiceException;
-import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask;
-import at.gv.egovernment.moa.id.auth.stork.STORKException;
-import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor;
-import at.gv.egovernment.moa.id.config.ConfigurationException;
-import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
-import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
-import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.spss.MOAException;
-import at.gv.egovernment.moa.spss.api.SPSSFactory;
-import at.gv.egovernment.moa.spss.api.SignatureVerificationService;
-import at.gv.egovernment.moa.spss.api.common.Content;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureInfo;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse;
-import at.gv.util.xsd.xmldsig.SignatureType;
-import at.gv.util.xsd.xmldsig.X509DataType;
-import eu.stork.oasisdss.api.LightweightSourceResolver;
-import eu.stork.oasisdss.api.exceptions.ApiUtilsException;
-import eu.stork.oasisdss.api.exceptions.UtilsException;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-
-public abstract class AbstractPepsConnectorWithLocalSigningTask extends AbstractAuthServletTask {
-
- public static final String PEPSCONNECTOR_SERVLET_URL_PATTERN = "/PEPSConnectorWithLocalSigning";
-
- String getCitizienSignatureFromSignResponse(SignResponse dssSignResponse) throws IllegalArgumentException,
- TransformerConfigurationException, UtilsException, TransformerException,
- TransformerFactoryConfigurationError, IOException, ApiUtilsException {
- // fetch signed doc
- DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse);
- if (ds == null) {
- throw new ApiUtilsException("No datasource found in response");
- }
-
- InputStream incoming = ds.getInputStream();
- String citizenSignature = IOUtils.toString(incoming);
- incoming.close();
-
- return citizenSignature;
- }
-
- void SZRGInsertion(AuthenticationSession moaSession, IPersonalAttributeList personalAttributeList,
- String authnContextClassRef, String citizenSignature) throws STORKException, MOAIDException {
- Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)");
- Logger.debug("Citizen signature will be verified by SZR Gateway!");
-
- Logger.debug("fetching OAParameters from database");
-
- OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(
- moaSession.getPublicOAURLPrefix());
- if (oaParam == null)
- throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });
-
- // retrieve target
- // TODO: check in case of SSO!!!
- String targetType = null;
- if (oaParam.getBusinessService()) {
- String id = oaParam.getIdentityLinkDomainIdentifier();
- if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
- targetType = id;
- else
- targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier();
- } else {
- targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
- }
-
- Logger.debug("Starting connecting SZR Gateway");
- // contact SZR Gateway
- IdentityLink identityLink = null;
-
- identityLink = STORKResponseProcessor.connectToSZRGateway(personalAttributeList, oaParam.getFriendlyName(),
- targetType, null, oaParam.getMandateProfiles(), citizenSignature);
- Logger.debug("SZR communication was successfull");
-
- if (identityLink == null) {
- Logger.error("SZR Gateway did not return an identity link.");
- throw new MOAIDException("stork.10", null);
- }
- Logger.info("Received Identity Link from SZR Gateway");
- moaSession.setIdentityLink(identityLink);
-
- Logger.debug("Adding addtional STORK attributes to MOA session");
- moaSession.setStorkAttributes(personalAttributeList);
-
- // We don't have BKUURL, setting from null to "Not applicable"
- moaSession.setBkuURL("Not applicable (STORK Authentication)");
-
- // free for single use
- moaSession.setAuthenticatedUsed(false);
-
- // stork did the authentication step
- moaSession.setAuthenticated(true);
-
- // TODO: found better solution, but QAA Level in response could be not supported yet
- try {
- if (authnContextClassRef == null)
- authnContextClassRef = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel();
- moaSession.setQAALevel(authnContextClassRef);
-
- } catch (Throwable e) {
- Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
- moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
-
- }
-
- }
-
- X509Certificate getSignerCertificate(String citizenSignature) throws CertificateException, JAXBException,
- UnsupportedEncodingException {
- JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName());
- SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller().unmarshal(
- IOUtils.toInputStream(citizenSignature))).getValue();
-
- // extract certificate
- for (Object current : root.getKeyInfo().getContent())
- if (((JAXBElement<?>) current).getValue() instanceof X509DataType) {
- for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue()
- .getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
- JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data);
- if (casted.getName().getLocalPart().equals("X509Certificate")) {
- return new X509Certificate(((String) casted.getValue()).getBytes("UTF-8"));
- }
- }
- }
- return null;
- }
-
- VerifyXMLSignatureResponse verifyXMLSignature(String signature) throws AuthenticationException, ParseException,
- BKUException, BuildException, ConfigurationException, ServiceException, UnsupportedEncodingException,
- SAXException, IOException, ParserConfigurationException, MOAException {
- // Based on MOA demo client
- // Factory und Service instanzieren
- SPSSFactory spssFac = SPSSFactory.getInstance();
- SignatureVerificationService sigVerifyService = SignatureVerificationService.getInstance();
-
- Content sigDocContent1 = spssFac.createContent(IOUtils.toInputStream(signature, "UTF-8"), null);
-
- // Position der zu prüfenden Signatur im Dokument angeben
- // (Nachdem im XPath-Ausdruck ein NS-Präfix verwendet wird, muss in einer Lookup-Tabelle
- // der damit bezeichnete Namenraum mitgegeben werden)
- HashMap nSMap = new HashMap();
- nSMap.put("dsig", "http://www.w3.org/2000/09/xmldsig#");
- VerifySignatureLocation sigLocation = spssFac.createVerifySignatureLocation("//dsig:Signature", nSMap);
-
- // Zu prüfendes Dokument und Signaturposition zusammenfassen
-
- VerifySignatureInfo sigInfo = spssFac.createVerifySignatureInfo(sigDocContent1, sigLocation);
-
- // Prüfrequest zusammenstellen
- VerifyXMLSignatureRequest verifyRequest = spssFac.createVerifyXMLSignatureRequest(null, // Wird Prüfzeit nicht
- // angegeben, wird
- // aktuelle Zeit
- // verwendet
- sigInfo, null, // Keine Ergänzungsobjekte notwendig
- null, // Signaturmanifest-Prüfung soll nicht durchgeführt werden
- false, // Hash-Inputdaten, d.h. tatsächlich signierte Daten werden nicht zurückgeliefert
- "MOAIDBuergerkartePersonenbindungMitTestkarten");// TODO load from config
- // "Test-Signaturdienste"); // ID des verwendeten Vertrauensprofils
-
- VerifyXMLSignatureResponse verifyResponse = null;
- try {
- // Aufruf der Signaturprüfung
- verifyResponse = sigVerifyService.verifyXMLSignature(verifyRequest);
- } catch (MOAException e) {
- // Service liefert Fehler
- System.err.println("Die Signaturprüfung hat folgenden Fehler geliefert:");
- System.err.println("Fehlercode: " + e.getMessageId());
- System.err.println("Fehlernachricht: " + e.getMessage());
- throw e;
- }
-
- return verifyResponse;
- }
-
- at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse convert(
- VerifyXMLSignatureResponse xMLVerifySignatureResponse) {
- at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse response = new at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse();
- response.setCertificateCheckCode(xMLVerifySignatureResponse.getCertificateCheck().getCode());
- response.setPublicAuthority(xMLVerifySignatureResponse.getSignerInfo().isPublicAuthority());
- // response.setPublicAuthorityCode(publicAuthorityCode)
- response.setQualifiedCertificate(xMLVerifySignatureResponse.getSignerInfo().isQualifiedCertificate());
- response.setSignatureCheckCode(xMLVerifySignatureResponse.getSignatureCheck().getCode());
- response.setSignatureManifestCheckCode(xMLVerifySignatureResponse.getSignatureManifestCheck().getCode());
- // response.setSigningDateTime()
- // response.setX509certificate(x509certificate)
- response.setXmlDSIGManifestCheckCode(xMLVerifySignatureResponse.getSignatureManifestCheck().getCode());
- // response.setXmlDSIGManigest(xMLVerifySignatureResponse.getSignatureManifestCheck())
- // response.setXmlDsigSubjectName(xmlDsigSubjectName)
- return response;
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java
deleted file mode 100644
index 138776976..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java
+++ /dev/null
@@ -1,447 +0,0 @@
-package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.math.BigInteger;
-import java.net.URL;
-import java.security.NoSuchAlgorithmException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.BooleanUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.opensaml.common.IdentifierGenerator;
-import org.opensaml.common.impl.SecureRandomIdentifierGenerator;
-import org.w3c.dom.DOMException;
-
-import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
-import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
-import at.gv.egovernment.moa.id.auth.builder.CreateXMLSignatureRequestBuilder;
-import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
-import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
-import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask;
-import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
-import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
-import at.gv.egovernment.moa.id.config.ConfigurationException;
-import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
-import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
-import at.gv.egovernment.moa.id.config.stork.CPEPS;
-import at.gv.egovernment.moa.id.config.stork.STORKConfig;
-import at.gv.egovernment.moa.id.config.stork.StorkAttribute;
-import at.gv.egovernment.moa.id.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
-import at.gv.egovernment.moa.id.util.VelocityProvider;
-import at.gv.egovernment.moa.logging.Logger;
-import eu.stork.oasisdss.api.AdditionalProfiles;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.api.Profiles;
-import eu.stork.oasisdss.api.QualityLevels;
-import eu.stork.oasisdss.api.SignatureTypes;
-import eu.stork.oasisdss.api.exceptions.ApiUtilsException;
-import eu.stork.oasisdss.profile.AnyType;
-import eu.stork.oasisdss.profile.DocumentType;
-import eu.stork.oasisdss.profile.SignRequest;
-import eu.stork.peps.auth.commons.PEPSUtil;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-import eu.stork.peps.auth.commons.PersonalAttributeList;
-import eu.stork.peps.auth.commons.STORKAuthnRequest;
-import eu.stork.peps.auth.engine.STORKSAMLEngine;
-import eu.stork.peps.exceptions.STORKSAMLEngineException;
-
-/**
- * Creates a SAML2 STORK authentication request, embeds it in a form (in order to satisfy saml post binging) and returns the form withing the HttpServletResponse.<p/>
- * In detail:
- * <ul>
- * <li>Validates the stork configuration in order to make sure the selected country is supported.</li>
- * <li>Puts a flag ({@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}) into the ExecutionContext reflecting the capability of the C-PEPS to create xml signatures.</li>
- * <li>Invokes {@link AuthenticationServer#startSTORKAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationSession)} which</li>
- * <ul>
- * <li>Creates and signs a SAML2 stork authentication request.</li>
- * <li>Creates a signature request for auth block signature (either to be performed by the C-PEPS or locally).</li>
- * <li>Using the velocity template engine in order to create a form with the embedded stork request.</li>
- * <li>Writes the form to the response output stream.</li>
- * </ul>
- * </ul>
- * Expects:
- * <ul>
- * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
- * <li>Property {@code ccc} set within the moa session.</li>
- * </ul>
- * Result:
- * <ul>
- * <li>Form containing a SAML2 Stork authentication request and an action url pointing to the selected C-PEPS.</li>
- * <li>Assertion consumer URL for C-PEPS set either to {@code /PEPSConnector} in case of a C-PEPS supporting xml signatures or {@code /PEPSConnectorWithLocalSigning} if the selected C-PEPS does not support xml signatures.</li>
- * <li>In case of a C-PEPS not supporting xml signature: moasession with set signedDoc property (containing the signature request for local signing).</li>
- * <li>ExecutionContext contains the boolean flag {@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}.
- * </ul>
- * Code taken from {@link StartAuthenticationBuilder#build(AuthenticationSession, HttpServletRequest, HttpServletResponse)}.<br/>
- * Using {@link AuthenticationServer#startSTORKAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationSession)}
- * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse)
- */
-public class CreateStorkAuthRequestFormTask extends AbstractAuthServletTask {
-
- /**
- * Boolean value reflecting the capability of the selected c-peps of creating xml signatures.
- */
- public static final String PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED = "C-PEPS:XMLSignatureSupported";
-
- @Override
- public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp)
- throws TaskExecutionException {
-
- String pendingRequestID = null;
- String sessionID = null;
- try {
- setNoCachingHeaders(resp);
-
- sessionID = (String) executionContext.get(PARAM_SESSIONID);
- pendingRequestID = (String) executionContext.get("pendingRequestID");
- String ccc = (String) executionContext.get("CCC");
-
-
- // check parameter
- if (!ParamValidatorUtils.isValidSessionID(sessionID)) {
- throw new WrongParametersException("CreateStorkAuthRequestFormTask", PARAM_SESSIONID, "auth.12");
- }
- AuthenticationSession moasession = BaseAuthenticationServer.getSession(sessionID);
- IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
-
- if (StringUtils.isEmpty(ccc)) {
- // illegal state; task should not have been executed without a selected country
- throw new AuthenticationException("stork.22", new Object[] { sessionID });
-
- }
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_STORK_REQUESTED);
-
- STORKConfig storkConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig();
- if (!storkConfig.isSTORKAuthentication(moasession.getCcc())) {
- throw new AuthenticationException("stork.23", new Object[] { moasession.getCcc(), sessionID });
- }
-
- // STORK authentication
- // cpeps cannot be null
- CPEPS cpeps = storkConfig.getCPEPS(ccc);
- Logger.debug("Found C-PEPS configuration for citizen of country: " + moasession.getCcc());
- executionContext.put(PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED, cpeps.isXMLSignatureSupported());
-
- //add selected Country-Code to MOASession DAO
- moasession.setCcc(ccc);
-
- Logger.info("Starting STORK authentication for a citizen of country: " + moasession.getCcc());
- startSTORKAuthentication(req, resp, moasession, pendingReq);
-
- } catch (MOAIDException ex) {
- throw new TaskExecutionException(ex.getMessage(), ex);
-
- } catch (Exception e) {
- Logger.error("CreateStorkAuthRequestFormTask has an interal Error.", e);
- throw new TaskExecutionException("CreateStorkAuthRequestFormTask has an interal Error.", e);
-
- }
-
- finally {
-
- }
- }
-
- /**
- * Starts a MOA-ID authentication process using STORK
- *
- * @param req HttpServletRequest
- * @param resp HttpServletResponse
- * @param pendingReq
- * @param ccc Citizen country code
- * @param oaURL URL of the online application
- * @param target Target parameter
- * @param targetFriendlyName Friendly Name of Target
- * @param authURL Authentication URL
- * @param sourceID SourceID parameter
- * @throws MOAIDException
- * @throws AuthenticationException
- * @throws WrongParametersException
- * @throws ConfigurationException
- */
- public void startSTORKAuthentication(
- HttpServletRequest req,
- HttpServletResponse resp,
- AuthenticationSession moasession, IRequest pendingReq) throws MOAIDException, AuthenticationException, WrongParametersException, ConfigurationException {
-
- if (moasession == null) {
- throw new AuthenticationException("auth.18", new Object[]{});
- }
-
- //read configuration paramters of OA
- OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix());
- if (oaParam == null)
- throw new AuthenticationException("auth.00", new Object[]{moasession.getPublicOAURLPrefix()});
-
- //Start of STORK Processing
- STORKConfig storkConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig();
-
- CPEPS cpeps = storkConfig.getCPEPS(moasession.getCcc());
-
- Logger.debug("Preparing to assemble STORK AuthnRequest with the following values:");
- String destination = cpeps.getPepsURL().toExternalForm();
- Logger.debug("C-PEPS URL: " + destination);
-
-
- String issuerValue = pendingReq.getAuthURL();
- // String acsURL = new DataURLBuilder().buildDataURL(issuerValue,
- // PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN, moasession.getSessionID());
-
-
- String providerName = oaParam.getFriendlyName();
- Logger.debug("Issuer value: " + issuerValue);
-
- // prepare collection of required attributes
- // - attributes for online application
- Collection<StorkAttribute> attributesFromConfig = oaParam.getRequestedSTORKAttributes();
-
- // - prepare attribute list
- PersonalAttributeList attributeList = new PersonalAttributeList();
-
- // - fill container
- for (StorkAttribute current : attributesFromConfig) {
- PersonalAttribute newAttribute = new PersonalAttribute();
- newAttribute.setName(current.getName());
-
- boolean globallyMandatory = false;
- for (StorkAttribute currentGlobalAttribute : storkConfig.getStorkAttributes())
- if (current.getName().equals(currentGlobalAttribute.getName())) {
- globallyMandatory = BooleanUtils.isTrue(currentGlobalAttribute.getMandatory());
- break;
- }
-
- newAttribute.setIsRequired(current.getMandatory() || globallyMandatory);
- attributeList.add(newAttribute);
- }
-
- // add sign request
- PersonalAttribute newAttribute = new PersonalAttribute();
- newAttribute.setName("signedDoc");
- newAttribute.setIsRequired(true);
- List<String> value = new ArrayList<String>();
-
- Logger.debug("PEPS supports XMLSignatures:"+cpeps.isXMLSignatureSupported());
- String acsURL;
- if(cpeps.isXMLSignatureSupported())//Send SignRequest to PEPS
- {
- //solve Problem with sessionIDs
- acsURL = issuerValue + PepsConnectorTask.PEPSCONNECTOR_SERVLET_URL_PATTERN;
-
- value.add(generateDssSignRequest(CreateXMLSignatureRequestBuilder.buildForeignIDTextToBeSigned("wie im Signaturzertifikat (as in my signature certificate)", oaParam, moasession),
- "application/xhtml+xml", moasession.getCcc()));
- newAttribute.setValue(value);
- attributeList.add(newAttribute);
-
- // TODO[branch]: STORK AuthReq CPEPS acsURL "/PEPSConnector"
- }
- else//Process SignRequest locally with MOCCA
- {
- String target = moasession.getTarget();
- moasession.setTarget("AT");
- String signedDoc = (generateDssSignRequest(CreateXMLSignatureRequestBuilder.buildForeignIDTextToBeSigned("wie im Signaturzertifikat (as in my signature certificate)", oaParam, moasession),
- "application/xhtml+xml", "AT"));//moasession.getCcc()
- moasession.setTarget(target);
- Logger.warn("signedDoc to store:"+signedDoc);
- //attributeList.add(newAttribute);
-
- //store SignRequest for later...
- moasession.setSignedDoc(signedDoc);
-
- acsURL = issuerValue + AbstractPepsConnectorWithLocalSigningTask.PEPSCONNECTOR_SERVLET_URL_PATTERN;
- // TODO[branch]: STORK AuthReq acsURL "/PEPSConnectorWithLocalSigning"
- try {
- AuthenticationSessionStoreage.storeSession(moasession);
- } catch (MOADatabaseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL);
-
- if (Logger.isDebugEnabled()) {
- Logger.debug("The following attributes are requested for this OA:");
- for (StorkAttribute logReqAttr : attributesFromConfig)
- Logger.debug("OA specific requested attribute: " + logReqAttr.getName() + ", isRequired: " + logReqAttr.getMandatory());
- }
-
- //TODO: check Target in case of SSO!!
- String spSector = StringUtils.isEmpty(moasession.getTarget()) ? "Business" : moasession.getTarget();
- String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName();
- String spApplication = spInstitution;
- String spCountry = "AT"; // intentionally set AT - the flow is limited on that use case only
-
- //generate AuthnRquest
- STORKAuthnRequest authnRequest = new STORKAuthnRequest();
- authnRequest.setDestination(destination);
- authnRequest.setAssertionConsumerServiceURL(acsURL);//PEPSConnectorWithLocalSigning
- authnRequest.setProviderName(providerName);
- authnRequest.setIssuer(issuerValue);
- authnRequest.setQaa(oaParam.getQaaLevel());
- authnRequest.setSpInstitution(spInstitution);
- authnRequest.setSpCountry(spCountry);
- authnRequest.setSpApplication(spApplication);
- authnRequest.setSpSector(spSector);
- authnRequest.setPersonalAttributeList(attributeList);
-
- //TODO change
- authnRequest.setEIDCrossBorderShare(true);
- authnRequest.setEIDCrossSectorShare(true);
- authnRequest.setEIDSectorShare(true);
-
- authnRequest.setCitizenCountryCode(moasession.getCcc());
-
- Logger.debug("STORK AuthnRequest succesfully assembled.");
-
- STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("outgoing");
-
- if (samlEngine == null) {
- Logger.error("Could not initalize STORK SAML engine.");
- throw new MOAIDException("stork.00", null);
- }
-
- try {
- authnRequest = samlEngine.generateSTORKAuthnRequest(authnRequest);
- } catch (STORKSAMLEngineException e) {
- Logger.error("Could not sign STORK SAML AuthnRequest.", e);
- throw new MOAIDException("stork.00", null);
- }
-
- Logger.info("STORK AuthnRequest successfully signed!");
-
- //validate AuthnRequest
- try {
- samlEngine.validateSTORKAuthnRequest(authnRequest.getTokenSaml());
- } catch (STORKSAMLEngineException e) {
- Logger.error("STORK SAML AuthnRequest not valid.", e);
- throw new MOAIDException("stork.01", null);
- }
-
- Logger.debug("STORK AuthnRequest successfully internally validated.");
-
- //send
- moasession.setStorkAuthnRequest(authnRequest);
-
- // do PEPS-conform logging for easier evaluation
- try {
- // 2015-03-12 16:44:27.144#S-PEPS receives request from SP#spurl#spepsurl#spapp#spdomain#citizen country#qaa#msghash#msg_id id1#
- Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS receives request from SP#" +
- moasession.getPublicOAURLPrefix() + "#" + issuerValue + "#" + spApplication + "#" +
- new URL(moasession.getPublicOAURLPrefix()).getHost() + "#" + moasession.getCcc() + "#" + oaParam.getQaaLevel() +
- "#_hash_#" + moasession.getProcessInstanceId() + "#");
- } catch (Exception e1) {
- Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage());
- }
-
- AuthenticationSessionStoreage.changeSessionID(moasession, authnRequest.getSamlId());
-
-
- Logger.info("Preparing to send STORK AuthnRequest.");
- Logger.info("prepared STORKAuthnRequest: ");
- Logger.info(new String(authnRequest.getTokenSaml()));
-
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/saml2-post-binding-moa.vm");
- VelocityContext context = new VelocityContext();
- context.put("SAMLRequest", PEPSUtil.encodeSAMLToken(authnRequest.getTokenSaml()));
- context.put("RelayState", moasession.getSessionID());
- context.put("action", destination);
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
-
- // TODO[branch]: SAML2 Form Submit to CPEPS, response to acsURL Servlet
-
- resp.setContentType("text/html;charset=UTF-8");
- resp.getOutputStream().write(writer.toString().getBytes("UTF-8"));
-
- } catch (Exception e) {
- Logger.error("Error sending STORK SAML AuthnRequest.", e);
- throw new MOAIDException("stork.02", new Object[]{destination});
-
- }
-
- Logger.info("STORK AuthnRequest successfully successfully prepared for client with target location: " + authnRequest.getDestination());
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_REQUESTED, authnRequest.getDestination());
-
- // do PEPS-conform logging for easier evaluation
- try {
- // 2015-03-12 16:44:27.144#S-PEPS generates request to C-PEPS#spepsurl#cpepsurl#spapp#spdomain#citizen country#qaa#msghash#msg_id id1#id2#
- Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS generates request to C-PEPS#" +
- issuerValue + "#" + destination + "#" + spApplication + "#" +
- new URL(moasession.getPublicOAURLPrefix()).getHost() + "#" + moasession.getCcc() + "#" + oaParam.getQaaLevel() +
- "#_hash_#" + moasession.getProcessInstanceId() + "#" + authnRequest.getSamlId() + "#");
- } catch (Exception e1) {
- Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage());
- }
- }
-
- private String generateDssSignRequest(String text, String mimeType, String citizenCountry) {
- IdentifierGenerator idGenerator;
- try {
- idGenerator = new SecureRandomIdentifierGenerator();
-
- DocumentType doc = new DocumentType();
- doc.setBase64XML(text.getBytes("UTF-8"));
- doc.setID(idGenerator.generateIdentifier());
-
- SignRequest request = new SignRequest();
- request.setInputDocuments(ApiUtils.createInputDocuments(doc));
-
- String id = idGenerator.generateIdentifier();
- request.setRequestID(id);
- request.setDocUI(id);
-
- request.setProfile(Profiles.XADES_BES.toString());
- request.setNumberOfSigners(BigInteger.ONE);
- request.setTargetCountry(citizenCountry);
-
- // no, no todo. PEPS will alter this value anyhow.
- request.setReturnURL("http://invalid_return");
-
- AnyType required = new AnyType();
- required.getAny().add(ApiUtils.createSignatureType(SignatureTypes.XMLSIG_RFC3275.toString()));
- required.getAny().add(ApiUtils.createAdditionalProfile(AdditionalProfiles.XADES.toString()));
- required.getAny().add(ApiUtils.createQualityRequirements(QualityLevels.QUALITYLEVEL_QUALIFIEDSIG));
- required.getAny().add(ApiUtils.createIncludeObject(doc));
- request.setOptionalInputs(required);
-
- return IOUtils.toString(ApiUtils.marshalToInputStream(request));
- } catch (NoSuchAlgorithmException e) {
- Logger.error("Cannot generate id", e);
- throw new RuntimeException(e);
- } catch (ApiUtilsException e) {
- Logger.error("Could not create SignRequest", e);
- throw new RuntimeException(e);
- } catch (DOMException e) {
- Logger.error("Could not create SignRequest", e);
- throw new RuntimeException(e);
- } catch (IOException e) {
- Logger.error("Could not create SignRequest", e);
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java
deleted file mode 100644
index 7b9fa3f12..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java
+++ /dev/null
@@ -1,228 +0,0 @@
-package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import iaik.x509.X509Certificate;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-
-import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
-import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
-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.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
-import at.gv.egovernment.moa.id.auth.stork.STORKException;
-
-import at.gv.egovernment.moa.id.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.ModulUtils;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.VelocityProvider;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse;
-import at.gv.egovernment.moa.util.Base64Utils;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-
-/**
- * Processes the citizen's signature, creates identity link using szr gateway and finalizes authentication.
- * <p/>
- * In detail:
- * <ul>
- * <li>Changes moa session id.</li>
- * <li>Decodes and validates the sign response, extracting the citizen's signature.</li>
- * <li>Verifies the citizen's signature.</li>
- * <li>Create {@code signedDoc} attribute.</li>
- * <li>Retrieve identity link from SZR gateway using the citizen's signature.</li>
- * <li>If the S-PEPS did not provide any gender information, the szr gateway will not be able to issue an identity link.
- * Therefore a form is presented asking for the subject's gender. The form finally submits the user back to the
- * {@code /PepsConnectorWithLocalSigning} servlet (this task).</li>
- * <li>The moa session is updated with authentication information.</li>
- * <li>Change moa session id.</li>
- * <li>Redirects back to {@code /dispatcher} in order to finalize the authentication.</li>
- * </ul>
- * Expects:
- * <ul>
- * <li>HttpServletRequest parameter {@code moaSessionID}</li>
- * <li>HttpServletRequest parameter {@code signresponse}</li>
- * </ul>
- * Result:
- * <ul>
- * <li>Updated moa id session (signed auth block, signer certificate etc.)</li>
- * <li>Redirect to {@code /dispatcher}.</li>
- * <li>{@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.</li>
- * </ul>
- * Possible branches:
- * <ul>
- * <li>In case the szr gateway throws exception due to missing gender information:
- * <ul>
- * <li>Returns a form for gender selection with action url back to this servlet/task.</li>
- * </ul>
- * </li>
- * </ul>
- * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.<br/>
- *
- * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse)
- */
-public class PepsConnectorHandleLocalSignResponseTask extends AbstractPepsConnectorWithLocalSigningTask {
-
- @Override
- public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response)
- throws TaskExecutionException {
- String moaSessionID = request.getParameter("moaSessionID");
- String signResponse = request.getParameter("signresponse");
- Logger.info("moaSessionID:" + moaSessionID);
- Logger.info("signResponse:" + signResponse);
-
- if (moaSessionID != null && signResponse != null) {
- // redirect from oasis with signresponse
- handleSignResponse(executionContext, request, response);
- } else {
- // should not occur
- throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", null);
- }
- return;
- }
-
- private void handleSignResponse(ExecutionContext executionContext, HttpServletRequest request,
- HttpServletResponse response) throws TaskExecutionException {
- Logger.info("handleSignResponse started");
- String moaSessionID = request.getParameter("moaSessionID");
- String signResponse = request.getParameter("signresponse");
- Logger.info("moaSessionID:" + moaSessionID);
- Logger.info("signResponse:" + signResponse);
- String pendingRequestID = null;
- try {
-
- // load MOASession from database
- AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
- // change MOASessionID
- moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);
- IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
-
- Logger.info("pendingRequestID:" + pendingRequestID);
- String signResponseString = new String(Base64Utils.decode(signResponse, false), "UTF8");
- Logger.info("RECEIVED signresponse:" + signResponseString);
- // create SignResponse object
- Source response1 = new StreamSource(new java.io.StringReader(signResponseString));
- SignResponse dssSignResponse = ApiUtils.unmarshal(response1, SignResponse.class);
-
- // SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(new
- // java.io.StringReader(Base64.signResponse)));
-
- String citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse);
-
- // memorize signature into authblock
- moaSession.setAuthBlock(citizenSignature);
-
- X509Certificate cert = getSignerCertificate(citizenSignature);
- moaSession.setSignerCertificate(cert);
- VerifyXMLSignatureResponse xMLVerifySignatureResponse = verifyXMLSignature(citizenSignature);
- at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse tmp = convert(xMLVerifySignatureResponse);
-
- moaSession.setXMLVerifySignatureResponse(tmp);
- executionContext.put("identityLinkAvailable", false);
- try {
- IPersonalAttributeList personalAttributeList = moaSession.getAuthnResponseGetPersonalAttributeList();
- // Add SignResponse TODO Add signature (extracted from signResponse)?
- List<String> values = new ArrayList<String>();
- values.add(signResponseString);
- // values.add(citizenSignature);
- Logger.debug("Assembling signedDoc attribute");
- PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values, "Available");
- personalAttributeList.add(signedDocAttribute);
-
- String authnContextClassRef = moaSession.getAuthnContextClassRef();
- SZRGInsertion(moaSession, personalAttributeList, authnContextClassRef, citizenSignature);
- executionContext.put("identityLinkAvailable", true);
- } catch (STORKException e) {
- // this is really nasty but we work against the system here. We are supposed to get the gender attribute
- // from
- // stork. If we do not, we cannot register the person in the ERnP - we have to have the
- // gender for the represented person. So here comes the dirty hack.
- if (e.getCause() instanceof STORKException
- && e.getCause().getMessage().equals("gender not found in response")) {
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
- VelocityContext context = new VelocityContext();
- context.put("SAMLResponse", request.getParameter("SAMLResponse"));
- context.put("action", request.getRequestURL());
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
- response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
- } catch (Exception e1) {
- Logger.error("Error sending gender retrival form.", e1);
- // httpSession.invalidate();
- throw new MOAIDException("stork.10", null);
- }
-
- return;
- }
-
- Logger.error("Error connecting SZR Gateway", e);
- throw new MOAIDException("stork.10", null);
- }
-
- Logger.debug("Add full STORK AuthnResponse to MOA session");
- moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));// TODO ask Florian/Thomas
- // authnResponse?
-
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED);
-
- moaSession.setForeigner(true);
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);
-
- // redirect
- String redirectURL = null;
- redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
- ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
- newMOASessionID);
- redirectURL = response.encodeRedirectURL(redirectURL);
-
- response.sendRedirect(redirectURL);
- Logger.info("REDIRECT TO: " + redirectURL);
-
- } catch (AuthenticationException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (MOAIDException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (Exception e) {
- Logger.error("PEPSConnector has an interal Error.", e);
- throw new TaskExecutionException(e.getMessage(), e);
- }
-
- finally {
-
- }
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java
deleted file mode 100644
index e84c33d5d..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java
+++ /dev/null
@@ -1,451 +0,0 @@
-package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import iaik.x509.X509Certificate;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.opensaml.saml2.core.StatusCode;
-
-import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
-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.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
-import at.gv.egovernment.moa.id.auth.stork.STORKException;
-import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor;
-
-import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
-import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin;
-import at.gv.egovernment.moa.id.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.ModulUtils;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.HTTPUtils;
-import at.gv.egovernment.moa.id.util.VelocityProvider;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.Base64Utils;
-import at.gv.egovernment.moa.util.StringUtils;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.profile.SignRequest;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-import eu.stork.peps.auth.commons.PEPSUtil;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-import eu.stork.peps.auth.commons.STORKAuthnRequest;
-import eu.stork.peps.auth.commons.STORKAuthnResponse;
-import eu.stork.peps.auth.engine.STORKSAMLEngine;
-import eu.stork.peps.exceptions.STORKSAMLEngineException;
-
-/**
- * Validates the SAML response from C-PEPS.
- * <p/>
- * In detail:
- * <ul>
- * <li>Decodes and validates SAML response from C-PEPS.</li>
- * <li>Retrieves the moa session using the session id provided by HttpServletRequest parameter {@code RelayState} or by {@code inResponseTo} attribute of the saml response.</li>
- * <li>Store saml response in moa session.</li>
- * <li>Change moa session id.</li>
- * <li>Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.</li>
- * </ul>
- * Expects:
- * <ul>
- * <li>HttpServletRequest parameter {@code moaSessionID} <strong>to be {@code null}</strong></li>
- * <li>HttpServletRequest parameter {@code signresponse} <strong>to be {@code null}</strong></li>
- * <li>HttpServletRequest parameter {@code SAMLResponse}</li>
- * <li>Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute within the saml response, both reflecting the moa session id.</li>
- * </ul>
- * Result:
- * <ul>
- * <li>Updated moa session (with saml response).</li>
- * <li>Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.</li>
- * </ul>
- * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.<br/>
- *
- * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse)
- */
-public class PepsConnectorHandleResponseWithoutSignatureTask extends AbstractPepsConnectorWithLocalSigningTask {
-
- private String oasisDssWebFormURL = "https://testvidp.buergerkarte.at/oasis-dss/DSSWebFormServlet";
- // load from config below
-
- @Override
- public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response)
- throws TaskExecutionException {
- String moaSessionID = request.getParameter("moaSessionID");
- String signResponse = request.getParameter("signresponse");
- Logger.info("moaSessionID:" + moaSessionID);
- Logger.info("signResponse:" + signResponse);
-
- if (moaSessionID == null && signResponse == null) {
- // normal saml response
- handleSAMLResponse(executionContext, request, response);
-
- } else {
- // should not occur
- throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", null);
- }
- return;
- }
-
- private void handleSAMLResponse(ExecutionContext executionContext, HttpServletRequest request,
- HttpServletResponse response) throws TaskExecutionException {
- Logger.info("handleSAMLResponse started");
- String pendingRequestID = null;
-
- setNoCachingHeaders(response);
- try {
- Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message.");
- Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request));
-
- Logger.trace("No Caching headers set for HTTP response");
-
- // check if https or only http
- super.checkIfHTTPisAllowed(request.getRequestURL().toString());
-
- Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");
-
- // extract STORK Response from HTTP Request
- // Decodes SAML Response
- byte[] decSamlToken;
- try {
- decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
- Logger.debug("SAMLResponse: " + new String(decSamlToken));
-
- } catch (NullPointerException e) {
- Logger.error("Unable to retrieve STORK Response", e);
- throw new MOAIDException("stork.04", null);
- }
-
- // Get SAMLEngine instance
- STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing");
-
- STORKAuthnResponse authnResponse = null;
- try {
- // validate SAML Token
- Logger.debug("Starting validation of SAML response");
- authnResponse = engine.validateSTORKAuthnResponseWithQuery(decSamlToken, (String) request.getRemoteHost());
- Logger.info("SAML response succesfully verified!");
- } catch (STORKSAMLEngineException e) {
- Logger.error("Failed to verify STORK SAML Response", e);
- throw new MOAIDException("stork.05", null);
- }
-
- Logger.info("STORK SAML Response message succesfully extracted");
- Logger.debug("STORK response: ");
- Logger.debug(authnResponse.toString());
-
- Logger.debug("Trying to find MOA Session-ID ...");
- // String moaSessionID = request.getParameter(PARAM_SESSIONID);
- // first use SAML2 relayState
- String moaSessionID = request.getParameter("RelayState");
-
- // escape parameter strings
- moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);
-
- // check if SAML2 relaystate includes a MOA sessionID
- if (StringUtils.isEmpty(moaSessionID)) {
- // if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier
-
- moaSessionID = authnResponse.getInResponseTo();
- moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);
-
- if (StringUtils.isEmpty(moaSessionID)) {
- // No authentication session has been started before
- Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
- Logger.debug("PEPSConnectorURL was: " + request.getRequestURL());
- throw new AuthenticationException("auth.02", new Object[] { moaSessionID });
-
- } else
- Logger.trace("Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute.");
-
- } else
- // Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter.");
- Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState.");
-
- /*
- * INFO!!!! SAML message IDs has an different format then MOASessionIDs This is only a workaround because
- * many PEPS does not support SAML2 relayState or MOASessionID as AttributConsumerServiceURL GET parameter
- */
- // if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
- // throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");
-
- pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);
- IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
-
- // load MOASession from database
- AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
- // change MOASessionID
- moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Found MOA sessionID: " + moaSessionID);
-
- String statusCodeValue = authnResponse.getStatusCode();
-
- if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) {
- Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue);
- throw new MOAIDException("stork.06", new Object[] { statusCodeValue });
- }
-
- Logger.info("Got SAML response with authentication success message.");
-
- Logger.debug("MOA session is still valid");
-
- STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();
-
- if (storkAuthnRequest == null) {
- Logger.error("Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
- throw new MOAIDException("stork.07", null);
- }
-
- Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
-
-
- // first, try to fetch the attributes from the list of total attributes. Note that this very list is only filled
- // with ALL attributes when there is more than one assertion in the SAML2 STORK message.
- IPersonalAttributeList attributeList = authnResponse.getTotalPersonalAttributeList();
-
- // if the list is empty, there was just one assertion... probably
- if(attributeList.isEmpty())
- attributeList = authnResponse.getPersonalAttributeList();
-
- // //////////// incorporate gender from parameters if not in stork response
- // but first, check if we have a representation case
- if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList)
- || STORKResponseProcessor.hasAttribute("representative", attributeList)
- || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
- // in a representation case...
- moaSession.setUseMandate("true");
-
- // and check if we have the gender value
- PersonalAttribute gender = attributeList.get("gender");
- if (null == gender) {
- String gendervalue = (String) request.getParameter("gender");
- if (null != gendervalue) {
- gender = new PersonalAttribute();
- gender.setName("gender");
- ArrayList<String> tmp = new ArrayList<String>();
- tmp.add(gendervalue);
- gender.setValue(tmp);
-
- attributeList.add(gender);
- }
- }
- }
-
-
-
- // ////////////////////////////////////////////////////////////////////////
-
- Logger.debug("Starting extraction of signedDoc attribute");
- // extract signed doc element and citizen signature
- String citizenSignature = null;
- try {
- PersonalAttribute signedDoc = attributeList.get("signedDoc");
- String signatureInfo = null;
- // FIXME: Remove nonsense code (signedDoc attribute... (throw Exception for "should not occur" situations)), adjust error messages in order to reflect the true problem...
- if (signedDoc != null) {
- signatureInfo = signedDoc.getValue().get(0);
- // should not occur
- } else {
-
- // store SAMLResponse
- moaSession.setSAMLResponse(request.getParameter("SAMLResponse"));
- // store authnResponse
-
- // moaSession.setAuthnResponse(authnResponse);//not serializable
- moaSession.setAuthnResponseGetPersonalAttributeList(attributeList);
-
- String authnContextClassRef = null;
- try {
- authnContextClassRef = authnResponse.getAssertions().get(0).getAuthnStatements().get(0)
- .getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef();
- } catch (Throwable e) {
- Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
- }
-
- moaSession.setAuthnContextClassRef(authnContextClassRef);
- moaSession.setReturnURL(request.getRequestURL());
-
- // load signedDoc
- String signRequest = moaSession.getSignedDoc();
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- // set return url to PEPSConnectorWithLocalSigningServlet and add newMOASessionID
- // signRequest
-
- String issuerValue = pendingReq.getAuthURL();
- String acsURL = issuerValue
- + AbstractPepsConnectorWithLocalSigningTask.PEPSCONNECTOR_SERVLET_URL_PATTERN;
-
- String url = acsURL + "?moaSessionID=" + newMOASessionID;
- // redirect to OASIS module and sign there
-
- boolean found = false;
- try {
- Collection<StorkAttributeProviderPlugin> aps = AuthConfigurationProviderFactory.getInstance()
- .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()).getStorkAPs();
- Logger.info("Found AttributeProviderPlugins:" + aps.size());
- for (StorkAttributeProviderPlugin ap : aps) {
- Logger.info("Found AttributeProviderPlugin attribute:" + ap.getAttributes());
- if (ap.getAttributes().equalsIgnoreCase("signedDoc")) {
- // FIXME: A servlet's class field is not thread safe!!!
- oasisDssWebFormURL = ap.getUrl();
- found = true;
- Logger.info("Loaded signedDoc attribute provider url from config:" + oasisDssWebFormURL);
- break;
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- Logger.error("Loading the signedDoc attribute provider url from config failed");
- }
- if (!found) {
- Logger.error("Failed to load the signedDoc attribute provider url from config");
- }
- performRedirect(url, request, response, signRequest);
-
- return;
- }
-
- // FIXME: This servlet/task is intended to handle peps responses without signature, so why do we try to process that signature here?
- SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(
- new java.io.StringReader(signatureInfo)));
-
- citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse);
-
- // memorize signature into authblock
- moaSession.setAuthBlock(citizenSignature);
-
- X509Certificate cert = getSignerCertificate(citizenSignature);
- moaSession.setSignerCertificate(cert);
- moaSession.setForeigner(true);
-
- } catch (Throwable e) {
- Logger.error("Could not extract citizen signature from C-PEPS", e);
- throw new MOAIDException("stork.09", null);
- }
-
- // FIXME: Same here; we do not have the citizen's signature, so this code might be regarded as dead code.
- try {
- SZRGInsertion(moaSession, attributeList, authnResponse.getAssertions()
- .get(0).getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef()
- .getAuthnContextClassRef(), citizenSignature);
- } catch (STORKException e) {
- // this is really nasty but we work against the system here. We are supposed to get the gender attribute
- // from
- // stork. If we do not, we cannot register the person in the ERnP - we have to have the
- // gender for the represented person. So here comes the dirty hack.
- if (e.getCause() instanceof STORKException
- && e.getCause().getMessage().equals("gender not found in response")) {
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
- VelocityContext context = new VelocityContext();
- context.put("SAMLResponse", request.getParameter("SAMLResponse"));
- context.put("action", request.getRequestURL());
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
-
- response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
- } catch (Exception e1) {
- Logger.error("Error sending gender retrival form.", e1);
- // httpSession.invalidate();
- throw new MOAIDException("stork.10", null);
- }
-
- return;
- }
-
- Logger.error("Error connecting SZR Gateway", e);
- throw new MOAIDException("stork.10", null);
- }
-
- Logger.debug("Add full STORK AuthnResponse to MOA session");
- moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));// TODO ask Florian/Thomas
- // authnResponse?
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);
-
- // redirect
- String redirectURL = null;
- redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
- ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
- newMOASessionID);
- redirectURL = response.encodeRedirectURL(redirectURL);
-
- response.setContentType("text/html");
- response.setStatus(302);
- response.addHeader("Location", redirectURL);
- Logger.info("REDIRECT TO: " + redirectURL);
-
- } catch (AuthenticationException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (MOAIDException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (Exception e) {
- Logger.error("PEPSConnector has an interal Error.", e);
- throw new TaskExecutionException(e.getMessage(), e);
- }
-
- finally {
-
- }
-
- }
-
- private void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, String signRequestString)
- throws MOAIDException {
-
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/oasis_dss_webform_binding.vm");
- VelocityContext context = new VelocityContext();
-
- Logger.debug("performRedirect, signrequest:" + signRequestString);
- Source signDoc = new StreamSource(new java.io.StringReader(signRequestString));
- SignRequest signRequest = ApiUtils.unmarshal(signDoc, SignRequest.class);
- signRequest.setReturnURL("TODO");
- signRequestString = IOUtils.toString(ApiUtils.marshalToInputStream(signRequest));
- context.put("signrequest", Base64Utils.encode(signRequestString.getBytes("UTF8")));
- context.put("clienturl", url);
- context.put("action", oasisDssWebFormURL);
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
-
- resp.getOutputStream().write(writer.toString().getBytes("UTF-8"));
- } catch (Exception e) {
- Logger.error("Error sending DSS signrequest.", e);
- throw new MOAIDException("stork.11", null);
- }
- }
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java
deleted file mode 100644
index b505605ab..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java
+++ /dev/null
@@ -1,791 +0,0 @@
-package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import iaik.x509.X509Certificate;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringWriter;
-import java.net.URL;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-
-import javax.activation.DataSource;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.namespace.QName;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.ws.BindingProvider;
-import javax.xml.ws.Service;
-import javax.xml.ws.soap.SOAPBinding;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.opensaml.saml2.core.StatusCode;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
-import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-
-import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
-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.IdentityLink;
-import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask;
-import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
-import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser;
-import at.gv.egovernment.moa.id.auth.stork.STORKException;
-import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor;
-
-import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
-import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
-import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
-import at.gv.egovernment.moa.id.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.ModulUtils;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.HTTPUtils;
-import at.gv.egovernment.moa.id.util.IdentityLinkReSigner;
-import at.gv.egovernment.moa.id.util.VelocityProvider;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.DOMUtils;
-import at.gv.egovernment.moa.util.StringUtils;
-import at.gv.egovernment.moa.util.XPathUtils;
-import at.gv.util.xsd.xmldsig.SignatureType;
-import at.gv.util.xsd.xmldsig.X509DataType;
-import eu.stork.documentservice.DocumentService;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.api.LightweightSourceResolver;
-import eu.stork.oasisdss.profile.DocumentType;
-import eu.stork.oasisdss.profile.DocumentWithSignature;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-import eu.stork.peps.auth.commons.PEPSUtil;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-import eu.stork.peps.auth.commons.PersonalAttributeList;
-import eu.stork.peps.auth.commons.STORKAttrQueryRequest;
-import eu.stork.peps.auth.commons.STORKAuthnRequest;
-import eu.stork.peps.auth.commons.STORKAuthnResponse;
-import eu.stork.peps.auth.engine.STORKSAMLEngine;
-import eu.stork.peps.exceptions.STORKSAMLEngineException;
-
-/**
- * Evaluates the SAML response from the C-PEPS and authenticates the user.
- * <p/>
- * In detail:
- * <ul>
- * <li>Decodes and validates the SAML response from the C-PEPS.</li>
- * <li>Change moa session id.</li>
- * <li>Extracts the subject's gender from request parameter {@code gender} if not available from the saml response.</li>
- * <li>Extracts the {@code signedDoc} attribute from the response, get signed doc payload using stork attribute query request.</li>
- * <li>Request SZR gateway for verification of the citizen's signature and for creating of an identity link.</li>
- * <li>In case of mandate mode: If the S-PEPS did not provide any gender information, the szr gateway will not be able to issue an identity link. Therefore a form is presented asking for the subject's gender. The form submits the user back to the {@code /PepsConnector} servlet (this task).</li>
- * <li>The moa session is updated with authentication information.</li>
- * <li>Change moa session id.</li>
- * <li>Redirects back to {@code /dispatcher} in order to finalize the authentication.</li>
- * </ul>
- * Expects:
- * <ul>
- * <li>HttpServletRequest parameter {@code SAMLResponse}</li>
- * <li>Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute from the SAML response (both depicting the moa session id)</li>
- * <li>HttpServletRequest parameter {@code gender} in case the request comes from the gender selection form</li>
- * <li>{@code signedDoc} attribute within the SAML response.</li>
- * </ul>
- * Result:
- * <ul>
- * <li>Updated moa id session (identity link, stork attributes...)</li>
- * <li>{@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.</li>
- * <li>Redirect to {@code /dispatcher}.</li>
- * </ul>
- * Possible branches:
- * <ul>
- * <li>In case the szr gateway throws exception due to missing gender information:
- * <ul>
- * <li>Returns a form for gender selection with action url back to this servlet/task.</li>
- * </ul>
- * </li>
- * </ul>
- * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet}.<br/>
- *
- * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse)
- */
-public class PepsConnectorTask extends AbstractAuthServletTask {
-
- public static final String PEPSCONNECTOR_SERVLET_URL_PATTERN = "/PEPSConnector";
-
- public PepsConnectorTask() {
- super();
-
- }
-
- @Override
- public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response)
- throws TaskExecutionException {
- String pendingRequestID = null;
-
- setNoCachingHeaders(response);
-
- try {
-
- Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message.");
- Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request));
-
- // check if https or only http
- super.checkIfHTTPisAllowed(request.getRequestURL().toString());
-
- Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");
-
- // extract STORK Response from HTTP Request
- // Decodes SAML Response
- byte[] decSamlToken;
- try {
- decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
- Logger.debug("SAMLResponse: " + new String(decSamlToken));
-
- } catch (NullPointerException e) {
- Logger.error("Unable to retrieve STORK Response", e);
- throw new MOAIDException("stork.04", null);
- }
-
- // Get SAMLEngine instance
- STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing");
-
- STORKAuthnResponse authnResponse = null;
- try {
- // validate SAML Token
- Logger.debug("Starting validation of SAML response");
- authnResponse = engine.validateSTORKAuthnResponseWithQuery(decSamlToken, (String) request.getRemoteHost());
- Logger.info("SAML response succesfully verified!");
- } catch (STORKSAMLEngineException e) {
- Logger.error("Failed to verify STORK SAML Response", e);
- throw new MOAIDException("stork.05", null);
- }
-
- Logger.info("STORK SAML Response message succesfully extracted");
- Logger.debug("STORK response: ");
- Logger.debug(authnResponse.toString());
-
- // do PEPS-conform logging for easier evaluation
- try {
- // 2015-03-12 16:44:27.144#S-PEPS receives response from C-PEPS#orig_msg_id id2 (in response to)#orig_msg_id id1 (in response to)#status#msghash#msg_id id3#
- Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS receives response from C-PEPS#" +
- authnResponse.getInResponseTo() + "#NA#" + authnResponse.getMessage() + "#_hash_#" + authnResponse.getSamlId() + "#");
- } catch (Exception e1) {
- Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage());
- }
-
- Logger.debug("Trying to find MOA Session-ID ...");
- // String moaSessionID = request.getParameter(PARAM_SESSIONID);
- // first use SAML2 relayState
- String moaSessionID = request.getParameter("RelayState");
-
- // escape parameter strings
- moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);
-
- // check if SAML2 relaystate includes a MOA sessionID
- if (StringUtils.isEmpty(moaSessionID)) {
- // if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier
-
- moaSessionID = authnResponse.getInResponseTo();
- moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);
-
- if (StringUtils.isEmpty(moaSessionID)) {
- // No authentication session has been started before
- Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
- Logger.debug("PEPSConnectorURL was: " + request.getRequestURL());
- throw new AuthenticationException("auth.02", new Object[] { moaSessionID });
-
- } else
- Logger.trace("Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute.");
-
- } else
- // Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter.");
- Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState.");
-
- /*
- * INFO!!!! SAML message IDs has an different format then MOASessionIDs This is only a workaround because
- * many PEPS does not support SAML2 relayState or MOASessionID as AttributConsumerServiceURL GET parameter
- */
- // if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
- // throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");
-
- pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);
- IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
-
- // load MOASession from database
- AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
- // change MOASessionID
- moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Found MOA sessionID: " + moaSessionID);
-
- String statusCodeValue = authnResponse.getStatusCode();
-
- if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) {
- Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue);
- throw new MOAIDException("stork.06", new Object[] { statusCodeValue });
- }
-
- Logger.info("Got SAML response with authentication success message.");
-
- Logger.debug("MOA session is still valid");
-
- STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();
-
- if (storkAuthnRequest == null) {
- Logger.error("Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
- throw new MOAIDException("stork.07", null);
- }
-
- OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix());
- if (oaParam == null)
- throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });
-
- //================== Check QAA level start ====================
- int reqQaa = -1;
- int authQaa = -1;
- String authQaaStr = null;
- try {
- reqQaa = storkAuthnRequest.getQaa();
-
- //TODO: found better solution, but QAA Level in response could be not supported yet
- try {
-
- authQaaStr = authnResponse.getAssertions().get(0).
- getAuthnStatements().get(0).getAuthnContext().
- getAuthnContextClassRef().getAuthnContextClassRef();
- moaSession.setQAALevel(authQaaStr);
-
- } catch (Throwable e) {
- Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
- moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
- authQaaStr = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel();
- }
- if(authQaaStr != null)//Check value only if set
- {
- authQaa = Integer.valueOf(authQaaStr.substring(PVPConstants.STORK_QAA_PREFIX.length()));
-// authQaa = Integer.valueOf(authQaaStr);
- if (reqQaa > authQaa) {
- Logger.warn("Requested QAA level does not match to authenticated QAA level");
- throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa});
-
- }
- }
- } catch (MOAIDException e) {
- throw e;
-
- } catch (Exception e) {
- if (Logger.isDebugEnabled())
- Logger.warn("STORK QAA Level evaluation error", e);
-
- else
- Logger.warn("STORK QAA Level evaluation error (ErrorMessage="
- + e.getMessage() + ")");
-
- throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa});
-
- }
- //================== Check QAA level end ====================
-
-
- Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
-
- // fetch attribute list from response
- IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList();
- if(authnResponse.getAssertions().size() > 1) {
- for(IPersonalAttributeList currentList : authnResponse.getPersonalAttributeLists()) {
- for(PersonalAttribute currentAttribute : currentList.values()) {
- if(!attributeList.containsKey(currentAttribute.getName()))
- attributeList.add((PersonalAttribute) currentAttribute.clone());
- else {
- if(!attributeList.get(currentAttribute.getName()).getValue().equals(currentAttribute.getValue()))
- throw new TaskExecutionException("data integrity failure", new Exception("data integrity failure: found non-matching values in multiple attributes of type " + currentAttribute.getName()));
- }
- }
- }
- }
-
- // //////////// incorporate gender from parameters if not in stork response
-
- // but first, check if we have a representation case
- if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList)
- || STORKResponseProcessor.hasAttribute("representative", attributeList)
- || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
- // in a representation case...
- moaSession.setUseMandate("true");
-
- // and check if we have the gender value
- PersonalAttribute gender = attributeList.get("gender"); // TODO Do we need to check gender value if
- // there is no representation case?
- if (null == gender) {
- String gendervalue = (String) request.getParameter("gender");
- if (null != gendervalue) {
- gender = new PersonalAttribute();
- gender.setName("gender");
- ArrayList<String> tmp = new ArrayList<String>();
- tmp.add(gendervalue);
- gender.setValue(tmp);
-
- attributeList.add(gender);
- }
- }
- }
-
- // ////////////////////////////////////////////////////////////////////////
-
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED);
-
- AuthConfiguration config = AuthConfigurationProviderFactory.getInstance();
- String citizenSignature = null;
- if(config.isStorkFakeIdLActive() && config.getStorkNoSignatureCountries().contains(storkAuthnRequest.getCitizenCountryCode()) && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) {
- Logger.debug("signedDoc extraction skipped due to configuration");
- } else {
- Logger.debug("Starting extraction of signedDoc attribute");
- // extract signed doc element and citizen signature
- try {
-
- if (attributeList.get("signedDoc") == null
- || attributeList.get("signedDoc").getValue() == null
- || attributeList.get("signedDoc").getValue().get(0) == null) {
- Logger.info("STORK Response include NO signedDoc attribute!");
- throw new STORKException("STORK Response include NO signedDoc attribute.");
-
- }
-
- String signatureInfo = attributeList.get("signedDoc").getValue().get(0);
-
-
- Logger.debug("signatureInfo:" + signatureInfo);
-
- SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(
- new java.io.StringReader(signatureInfo)));
-
- // fetch signed doc
- DataSource ds = null;
- try{
- ds = LightweightSourceResolver.getDataSource(dssSignResponse);
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- if(ds == null){
- //Normal DocumentServices return a http-page, but the SI DocumentService returns HTTP error 500
- //which results in an exception and ds==null
-
- //try to load document from documentservice
- citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
- //throw new ApiUtilsException("No datasource found in response");
- }
- else
- {
- InputStream incoming = ds.getInputStream();
- citizenSignature = IOUtils.toString(incoming);
- incoming.close();
-
- Logger.debug("citizenSignature:"+citizenSignature);
- if(isDocumentServiceUsed(citizenSignature)==true)
- {
- citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
- // Logger.debug("Loading document from DocumentService.");
- // String url = getDtlUrlFromResponse(dssSignResponse);
- // //get Transferrequest
- // String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url);
- // //Load document from DocumentService
- // byte[] data = getDocumentFromDtl(transferRequest, url);
- // citizenSignature = new String(data, "UTF-8");
- // Logger.debug("Overridung citizenSignature with:"+citizenSignature);
- }
- }
-
- JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName());
- SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller().unmarshal(
- IOUtils.toInputStream(citizenSignature))).getValue();
-
- // memorize signature into authblock
- moaSession.setAuthBlock(citizenSignature);
-
- // extract certificate
- for (Object current : root.getKeyInfo().getContent())
- if (((JAXBElement<?>) current).getValue() instanceof X509DataType) {
- for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue()
- .getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
- JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data);
- if (casted.getName().getLocalPart().equals("X509Certificate")) {
- moaSession.setSignerCertificate(new X509Certificate(((String) casted.getValue())
- .getBytes("UTF-8")));
- break;
- }
- }
- }
-
- } catch (Throwable e) {
- Logger.error("Could not extract citizen signature from C-PEPS", e);
- throw new MOAIDException("stork.09", null);
- }
- }
- Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)");
- Logger.debug("Citizen signature will be verified by SZR Gateway!");
-
- Logger.debug("fetching OAParameters from database");
-
- // //read configuration paramters of OA
- // AuthenticationSession moasession;
- // try {
- // moasession = AuthenticationSessionStoreage.getSession(moaSessionID);
- // } catch (MOADatabaseException e2) {
- // Logger.error("could not retrieve moa session");
- // throw new AuthenticationException("auth.01", null);
- // }
-
- // retrieve target
- // TODO: check in case of SSO!!!
- String targetType = null;
- if (oaParam.getBusinessService()) {
- String id = oaParam.getIdentityLinkDomainIdentifier();
- if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
- targetType = id;
- else
- targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier();
- } else {
- targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
- }
-
- Logger.debug("Starting connecting SZR Gateway");
- // contact SZR Gateway
- IdentityLink identityLink = null;
- executionContext.put("identityLinkAvailable", false);
- try {
- if(config.isStorkFakeIdLActive() && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) {
- // create fake IdL
- // - fetch IdL template from resources
- InputStream s = PepsConnectorTask.class.getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml");
- Element idlTemplate = DOMUtils.parseXmlValidating(s);
-
- identityLink = new IdentityLinkAssertionParser(idlTemplate).parseIdentityLink();
-
- // replace data
- Element idlassertion = identityLink.getSamlAssertion();
- // - set bpk/wpbk;
- Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH);
- if(!STORKResponseProcessor.hasAttribute("eIdentifier", attributeList))
- throw new STORKException("eIdentifier is missing");
- String eIdentifier = STORKResponseProcessor.getAttributeValue("eIdentifier", attributeList, false);
- prIdentification.getFirstChild().setNodeValue(eIdentifier);
-
- // - set last name
- Node prFamilyName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH);
- if(!STORKResponseProcessor.hasAttribute("surname", attributeList))
- throw new STORKException("surname is missing");
- String familyName = STORKResponseProcessor.getAttributeValue("surname", attributeList, false);
- prFamilyName.getFirstChild().setNodeValue(familyName);
-
- // - set first name
- Node prGivenName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH);
- if(!STORKResponseProcessor.hasAttribute("givenName", attributeList))
- throw new STORKException("givenName is missing");
- String givenName = STORKResponseProcessor.getAttributeValue("givenName", attributeList, false);
- prGivenName.getFirstChild().setNodeValue(givenName);
-
- // - set date of birth
- Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH);
- if(!STORKResponseProcessor.hasAttribute("dateOfBirth", attributeList))
- throw new STORKException("dateOfBirth is missing");
- String dateOfBirth = STORKResponseProcessor.getAttributeValue("dateOfBirth", attributeList, false);
- dateOfBirth = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(dateOfBirth));
- prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth);
-
- identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink();
-
- //resign IDL
- IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance();
- Element resignedilAssertion = identitylinkresigner.resignIdentityLink(identityLink.getSamlAssertion(), config.getStorkFakeIdLResigningKey());
- identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink();
-
- } else {
- //contact SZR Gateway
- Logger.debug("Starting connecting SZR Gateway");
-
- identityLink = STORKResponseProcessor.connectToSZRGateway(
- attributeList,
- oaParam.getFriendlyName(),
- targetType,
- null,
- oaParam.getMandateProfiles(),
- citizenSignature);
-
- }
-
- } catch (STORKException e) {
- // this is really nasty but we work against the system here. We are supposed to get the gender attribute
- // from
- // stork. If we do not, we cannot register the person in the ERnP - we have to have the
- // gender for the represented person. So here comes the dirty hack.
- if (e.getCause() instanceof STORKException
- && e.getCause().getMessage().equals("gender not found in response")) {
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
- VelocityContext context = new VelocityContext();
- context.put("SAMLResponse", request.getParameter("SAMLResponse"));
- context.put("action", request.getRequestURL());
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
-
- response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
- } catch (Exception e1) {
- Logger.error("Error sending gender retrival form.", e1);
- // httpSession.invalidate();
- throw new MOAIDException("stork.10", null);
- }
-
- return;
- }
-
- Logger.error("Error connecting SZR Gateway", e);
- throw new MOAIDException("stork.10", null);
- }
- Logger.debug("SZR communication was successfull");
-
- if (identityLink == null) {
- Logger.error("SZR Gateway did not return an identity link.");
- throw new MOAIDException("stork.10", null);
- }
-
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_IDL_RECEIVED);
- moaSession.setForeigner(true);
-
- Logger.info("Received Identity Link from SZR Gateway");
- executionContext.put("identityLinkAvailable", true);
- moaSession.setIdentityLink(identityLink);
-
- Logger.debug("Adding addtional STORK attributes to MOA session");
- moaSession.setStorkAttributes(attributeList);
-
- Logger.debug("Add full STORK AuthnResponse to MOA session");
- moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));
-
- // We don't have BKUURL, setting from null to "Not applicable"
- moaSession.setBkuURL("Not applicable (STORK Authentication)");
-
- // free for single use
- moaSession.setAuthenticatedUsed(false);
-
- // stork did the authentication step
- moaSession.setAuthenticated(true);
-
- // do PEPS-conform logging for easier evaluation
- try {
- // 2015-03-12 16:44:27.144#S-PEPS generates response to SP#orig_msg_id id1 (in response to)#status#msghash#msg_id id4#
- Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS generates response to SP#" +
- "#" + moaSession.getProcessInstanceId() + "#" + authnResponse.getMessage() + "#_hash_#" + moaSession.getProcessInstanceId() + "#");
- } catch (Exception e1) {
- Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage());
- }
-
- // TODO: found better solution, but QAA Level in STORK response is not be supported yet
-// try {
-//
-// moaSession.setQAALevel(authnResponse.getAssertions().get(0).getAuthnStatements().get(0)
-// .getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef());
-//
-// } catch (Throwable e) {
-// Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
-// moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
-//
-// }
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);
-
- // redirect
- String redirectURL = null;
- redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
- ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
- newMOASessionID);
- redirectURL = response.encodeRedirectURL(redirectURL);
-
- // response.setContentType("text/html");
- // response.setStatus(302);
- // response.addHeader("Location", redirectURL);
- response.sendRedirect(redirectURL);
- Logger.info("REDIRECT TO: " + redirectURL);
-
- } catch (AuthenticationException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (MOAIDException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (Exception e) {
- Logger.error("PEPSConnector has an interal Error.", e);
- throw new TaskExecutionException(e.getMessage(), e);
- }
-
- finally {
-
- }
-
- }
-
- private boolean isDocumentServiceUsed(String citizenSignature) // TODo add better check
- {
- if (citizenSignature
- .contains("<table border=\"0\"><tr><td>Service Name:</td><td>{http://stork.eu}DocumentService</td></tr><tr><td>Port Name:</td><td>{http://stork.eu}DocumentServicePort</td></tr></table>")) {
- Logger.trace("isDocumentServiceUsed => true");
- return true;
- }
-
- Logger.trace("isDocumentServiceUsed => false");
- return false;
- }
-
- /**
- * Get DTL uril from the oasis sign response
- *
- * @param signRequest
- * The signature response
- * @return The URL of DTL service
- * @throws SimpleException
- */
- private String getDtlUrlFromResponse(SignResponse dssSignResponse) {
- List<DocumentWithSignature> documents = ApiUtils.findNamedElement(dssSignResponse.getOptionalOutputs(),
- ApiUtils.OPTIONAL_OUTPUT_DOCUMENTWITHSIGNATURE, DocumentWithSignature.class);
- DocumentType sourceDocument = documents.get(0).getDocument();
-
- if (sourceDocument.getDocumentURL() != null)
- return sourceDocument.getDocumentURL();
- else
- return null;// throw new Exception("No document url found");
- }
-
- // From DTLPEPSUTIL
-
- /**
- * Get document from DTL
- *
- * @param transferRequest
- * The transfer request (attribute query)
- * @param eDtlUrl
- * The DTL url of external DTL
- * @return the document data
- * @throws SimpleException
- */
- private byte[] getDocumentFromDtl(String transferRequest, String eDtlUrl) throws Exception {
- URL url = null;
- try {
-
- Logger.trace("getDocumentFromDtl, dtlUrl:'"+getdtlUrl()+"' eDtlUrl:'"+eDtlUrl+"'");
- url = new URL(getdtlUrl());
- QName qname = new QName("http://stork.eu", "DocumentService");
-
- Service service = Service.create(url, qname);
- DocumentService docservice = service.getPort(DocumentService.class);
-
- BindingProvider bp = (BindingProvider) docservice;
- SOAPBinding binding = (SOAPBinding) bp.getBinding();
- binding.setMTOMEnabled(true);
-
- if (eDtlUrl.equalsIgnoreCase(getdtlUrl()))
- return docservice.getDocument(transferRequest, "");
- else
- return docservice.getDocument(transferRequest, eDtlUrl);
- } catch (Exception e) {
- e.printStackTrace();
- throw new Exception("Error in getDocumentFromDtl", e);
- }
- }
-
- /**
- * Get a document transfer request (attribute query)
- *
- * @param docId
- * @return
- * @throws SimpleException
- */
- private String getDocTransferRequest(String docId, String destinationUrl) throws Exception {
- String spCountry = docId.substring(0, docId.indexOf("/"));
- final STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
- STORKAttrQueryRequest req = new STORKAttrQueryRequest();
- req.setAssertionConsumerServiceURL(getdtlUrl());
- req.setDestination(destinationUrl);
- req.setSpCountry(spCountry);
- req.setQaa(3);// TODO
- PersonalAttributeList pal = new PersonalAttributeList();
- PersonalAttribute attr = new PersonalAttribute();
- attr.setName("docRequest");
- attr.setIsRequired(true);
- attr.setValue(Arrays.asList(docId));
- pal.add(attr);
- req.setPersonalAttributeList(pal);
-
- STORKAttrQueryRequest req1;
- try {
- req1 = engine.generateSTORKAttrQueryRequest(req);
- return PEPSUtil.encodeSAMLTokenUrlSafe(req1.getTokenSaml());
- } catch (STORKSAMLEngineException e) {
- e.printStackTrace();
- throw new Exception("Error in doc request attribute query generation", e);
- }
- }
-
- private String getdtlUrl() {
- String dtlUrl;
- try {
- AuthConfiguration authConfigurationProvider = AuthConfigurationProviderFactory.getInstance();
- dtlUrl = authConfigurationProvider.getDocumentServiceUrl();
- Logger.info ("PEPSConnectorServlet, using dtlUrl:"+dtlUrl);
-
- } catch (Exception e) {
- dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService";
- Logger.error("Loading documentservice url failed, using default value:"+dtlUrl, e);
-
- }
-
-
-// Properties props = new Properties();
-// try {
-// props.load(DatabaseConnectorMySQLImpl.class.getResourceAsStream("docservice.properties"));
-// dtlUrl = props.getProperty("docservice.url");
-// } catch (IOException e) {
-// dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService";
-// Logger.error("Loading DTL config failed, using default value:" + dtlUrl);
-// e.printStackTrace();
-// }
-
- return dtlUrl;
-
- }
-
- private String loadDocumentFromDocumentService(SignResponse dssSignResponse) throws Exception
- {
- Logger.debug("Loading document from DocumentService.");
- String url = getDtlUrlFromResponse(dssSignResponse);
- Logger.debug("Loading document from DocumentService, url:"+url);
- //get Transferrequest
- String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url);
- //Load document from DocumentService
- byte[] data = getDocumentFromDtl(transferRequest, url);
- String citizenSignature = new String(data, "UTF-8");
- Logger.debug("Overridung citizenSignature with:"+citizenSignature);
- return citizenSignature;
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java
deleted file mode 100644
index 79641d085..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*******************************************************************************
- * 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.
- ******************************************************************************/
-/**
- *
- */
-package at.gv.egovernment.moa.id.auth.stork;
-
-
-/**
- * Exception thrown if error occurs in STORK processing
- * @author bzwattendorfer
- *
- */
-public class STORKException extends Exception{
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- public STORKException() {
- super();
-
- }
-
- public STORKException(String message, Throwable cause) {
- super(message, cause);
-
- }
-
- public STORKException(String message) {
- super(message);
-
- }
-
- public STORKException(Throwable cause) {
- super(cause);
-
- }
-
-
-
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java
deleted file mode 100644
index 65a3637a9..000000000
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*******************************************************************************
- * 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.
- ******************************************************************************/
-/**
- *
- */
-package at.gv.egovernment.moa.id.auth.stork;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Vector;
-
-import javax.activation.DataSource;
-import javax.xml.transform.Source;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactoryConfigurationError;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.StringEscapeUtils;
-
-import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute;
-import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttributeImpl;
-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.parser.IdentityLinkAssertionParser;
-import at.gv.egovernment.moa.id.client.SZRGWClientException;
-import at.gv.egovernment.moa.id.client.utils.SZRGWClientUtils;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.Constants;
-import at.gv.egovernment.moa.util.DateTimeUtils;
-import at.gv.egovernment.moa.util.StringUtils;
-import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.api.LightweightSourceResolver;
-import eu.stork.oasisdss.api.exceptions.ApiUtilsException;
-import eu.stork.oasisdss.api.exceptions.UtilsException;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-
-/**
- *
- * Handles all functionality for the processing of a STORK response
- * @author bzwattendorfer
- *
- */
-public class STORKResponseProcessor {
-
- /** OASIS DSS Namespace */
- public static final String OASIS_DSS_NS = "urn:oasis:names:tc:dss:1.0:core:schema";
-
- /** OASIS DSS Success Message */
- public static final String OASIS_DSS_SUCCESS_MSG = "urn:oasis:names:tc:dss:1.0:resultmajor:Success";
-
- /**
- * Checks for attribute.
- *
- * @param attributeName the attribute name
- * @param attributeList the attribute list
- * @return true, if successful
- */
- public static boolean hasAttribute(String attributeName, IPersonalAttributeList attributeList) {
- try {
- getAttributeValue(attributeName, attributeList);
- return true;
- } catch(STORKException e) {
- return false;
- }
- }
-
- /**
- * helper for reading attributes. Handles logging and error handling.
- *
- * @param attributeName the attribute name
- * @param attributeList the attribute list
- * @return the attribute value
- * @throws STORKException the sTORK exception
- */
- private static String getAttributeValue(String attributeName, IPersonalAttributeList attributeList) throws STORKException {
- return getAttributeValue(attributeName, attributeList, true);
- }
- public static String getAttributeValue(String attributeName, IPersonalAttributeList attributeList, boolean throwException) throws STORKException {
- try {
- String result = attributeList.get(attributeName).getValue().get(0);
- Logger.trace(attributeName + " : " + result);
- return result;
- } catch(Exception e) {
- Logger.error(attributeName + " not found in response");
- if(throwException)
- throw new STORKException(attributeName + " not found in response");
- else
- return null;
- }
- }
-
- /**
- * Handels connection to SZR-GW and returns Identity Link on success.
- *
- * @param attributeList the attribute list
- * @param oaFriendlyName the oa friendly name
- * @param targetType the target type
- * @param targetValue the target value
- * @param filters the filters
- * @param citizenSignature2
- * @return Identity Link
- * @throws STORKException the sTORK exception
- * @throws MOAIDException
- */
- public static IdentityLink connectToSZRGateway(IPersonalAttributeList attributeList, String oaFriendlyName, String targetType, String targetValue, List<String> filters, String citizenSignature) throws STORKException, MOAIDException {
- Logger.trace("Calling SZR Gateway with the following attributes:");
-
- CreateIdentityLinkResponse identityLinkResponse = null;
- IdentityLink identityLink = null;
- try {
- Logger.trace("Starting call...");
-
- // if there is no signedDoc attribute, we cannot go on
- if(citizenSignature==null || citizenSignature.length()==0)
- {
- String signResponseString = getAttributeValue("signedDoc", attributeList);
-
- //Extract signature from SIgnResponse
- Source response1 = new StreamSource(new java.io.StringReader(signResponseString));
- SignResponse dssSignResponse = ApiUtils.unmarshal(response1, SignResponse.class);
- citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse);
- }
-
- String fiscalNumber = getAttributeValue("fiscalNumber", attributeList, false);
-
- // if we have a signedDoc we test for a representation case
- // - according to stork samlengine and commons
- if(hasAttribute("mandate", attributeList)) {
- // we have a representation case
- String mandate = getAttributeValue("mandate", attributeList, false);
-
- if(!hasAttribute("dateOfBirth", attributeList)) {
- // if we get here, we have a natural person representing a legal person
- String organizationAddress = getAttributeValue("canonicalRegisteredAddress", attributeList, false);
- String organizationType = getAttributeValue("translateableType", attributeList, false);
-
- identityLinkResponse = SZRGWClientUtils.getIdentityLink(citizenSignature, null, null, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
- } else {
- // if we get here, we have a natural person representing another natural person
- String eIdentifier = getAttributeValue("eIdentifier", attributeList, false);
- String givenName = getAttributeValue("givenName", attributeList, false);
- String lastName = getAttributeValue("surname", attributeList, false);
- String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false);
-
- // gender attribute is mandatory here because of some legal stuff
- String gender = getAttributeValue("gender", attributeList, false);
-
- if (!StringUtils.isEmpty(dateOfBirth))
- dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth);
-
- identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier,
- givenName, lastName, dateOfBirth, gender, citizenSignature, null,
- null, mandate, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
- }
- }
- // - according to stork spec
- else if(hasAttribute("mandateContent", attributeList) || hasAttribute("representative", attributeList) || hasAttribute("represented", attributeList)) {
- // we have a representation case
- String representative = getAttributeValue("representative", attributeList, false);
- String represented = getAttributeValue("represented", attributeList, false);
- String mandate = getAttributeValue("mandateContent", attributeList, false);
-
- if(!hasAttribute("dateOfBirth", attributeList)) {
- // if we get here, we have a natural person representing a legal person
- String organizationAddress = getAttributeValue("canonicalRegisteredAddress", attributeList, false);
- String organizationType = getAttributeValue("translateableType", attributeList, false);
-
- identityLinkResponse = SZRGWClientUtils.getIdentityLink(citizenSignature, representative, represented, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
- } else {
- // if we get here, we have a natural person representing another natural person
- String eIdentifier = getAttributeValue("eIdentifier", attributeList, false);
- String givenName = getAttributeValue("givenName", attributeList, false);
- String lastName = getAttributeValue("surname", attributeList, false);
- String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false);
-
- // gender attribute is mandatory here because of some legal stuff
- String gender = getAttributeValue("gender", attributeList, false);
-
- if (!StringUtils.isEmpty(dateOfBirth))
- dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth);
-
- identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier,
- givenName, lastName, dateOfBirth, gender, citizenSignature, representative,
- represented, mandate, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
- }
- } else {
- // we do not have a representation case
- String eIdentifier = getAttributeValue("eIdentifier", attributeList, false);
- String givenName = getAttributeValue("givenName", attributeList, false);
- String lastName = getAttributeValue("surname", attributeList, false);
- String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false);
- if (!StringUtils.isEmpty(dateOfBirth))
- dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth);
- identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, citizenSignature, fiscalNumber);
- }
-
- if (null != identityLinkResponse.getErrorResponse()){
- throw new SZRGWClientException("service.08", (String)identityLinkResponse.getErrorResponse().getErrorCode(),
- (String)identityLinkResponse.getErrorResponse().getInfo());
- }
- else {
- IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream(identityLinkResponse.getIdentityLink()));
- identityLink = ilParser.parseIdentityLink();
-
- Logger.debug("Received Identity Link from SZR Gateway");
- //TODO: is this ok?
-// if (StringUtils.isEmpty(identityLink.getDateOfBirth())) {
-// identityLink.setDateOfBirth("9999-12-31");
-// }
-
- }
-
- } catch (ParseException e) {
- Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
- throw new MOAIDException("auth.25", null, e);
- } catch (ApiUtilsException e) {
- Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
- throw new MOAIDException("auth.25", null, e);
- } catch (IllegalArgumentException e) {
- Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
- throw new MOAIDException("auth.25", null, e);
- } catch (TransformerConfigurationException e) {
- Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
- throw new MOAIDException("auth.25", null, e);
- } catch (UtilsException e) {
- Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
- throw new MOAIDException("auth.25", null, e);
- } catch (TransformerException e) {
- Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
- throw new MOAIDException("auth.25", null, e);
- } catch (TransformerFactoryConfigurationError e) {
- Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
- throw new MOAIDException("auth.25", null, e);
- } catch (IOException e) {
- Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
- throw new MOAIDException("auth.25", null, e);
- }
-
- return identityLink;
-
- }
-
- private static String getCitizienSignatureFromSignResponse(SignResponse dssSignResponse) throws IllegalArgumentException, TransformerConfigurationException, UtilsException, TransformerException, TransformerFactoryConfigurationError, IOException, ApiUtilsException
- {
- // fetch signed doc
- DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse);
- if(ds == null){
- throw new ApiUtilsException("No datasource found in response");
- }
-
- InputStream incoming = ds.getInputStream();
- String citizenSignature = IOUtils.toString(incoming);
- incoming.close();
-
- return citizenSignature;
- }
-
-}