From b166ec2361980aeb9f288125afd5716099a21f7c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 10 Jul 2014 12:42:05 +0200 Subject: solve TrustManagerRevocationCheck problem with legacy config import --- .../at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java index 864be253a..1240ed8f3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java @@ -151,6 +151,8 @@ public class BuildFromLegacyConfig { if (genericConfiguration.containsKey(ConfigurationProvider.TRUST_MANAGER_REVOCATION_CHECKING)) authGeneral.setTrustManagerRevocationChecking( Boolean.valueOf((String)genericConfiguration.get(ConfigurationProvider.TRUST_MANAGER_REVOCATION_CHECKING))); + else + authGeneral.setTrustManagerRevocationChecking(true); if (genericConfiguration.containsKey(ConfigurationProvider.DIRECTORY_CERTSTORE_PARAMETER_PROPERTY)) authGeneral.setCertStoreDirectory( -- cgit v1.2.3 From 96407baacd66fef7f3581a5377180a152795bd78 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 14 Jul 2014 09:02:30 +0200 Subject: add additionl trustmanagerrevoationchecking default value --- .../java/at/gv/egovernment/moa/id/config/ConfigurationProvider.java | 2 +- .../gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProvider.java index 88ed7885f..24def1e02 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProvider.java @@ -124,7 +124,7 @@ public class ConfigurationProvider { protected String certstoreDirectory; - protected boolean trustmanagerrevoationchecking; + protected boolean trustmanagerrevoationchecking = true; /** * Returns the main configuration file directory used to configure MOA-ID diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index 6fc1d28c1..32625ca03 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -1038,10 +1038,11 @@ public class AuthConfigurationProvider extends ConfigurationProvider { private void setTrustManagerRevocationChecking() throws ConfigurationException { AuthComponentGeneral auth = getAuthComponentGeneral(); - if (auth.getGeneralConfiguration() != null) + if (auth.getGeneralConfiguration() != null && + auth.getGeneralConfiguration().isTrustManagerRevocationChecking() != null) trustmanagerrevoationchecking = auth.getGeneralConfiguration().isTrustManagerRevocationChecking(); else { - Logger.warn("Error in MOA-ID Configuration. No CertStoreDirectory defined."); + Logger.warn("No TrustMangerRevoationChecking defined. Use default value = TRUE"); throw new ConfigurationException("config.02", null); } } -- cgit v1.2.3 From a777e9ba26db80ca30ed97a4910e3003aaae8b46 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 07:30:10 +0100 Subject: add metadata schema validation filters --- .../moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java | 4 ++++ .../verification/metadata/InterfederatedIDPPublicServiceFilter.java | 1 - 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java index cba64e080..12afa14bc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java @@ -57,6 +57,7 @@ import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.InterfederatedIDPPublicServiceFilter; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.MetadataFilterChain; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.SchemaValidationFilter; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -324,6 +325,7 @@ public class MOAMetadataProvider implements MetadataProvider { private MetadataFilterChain buildMetadataFilterChain(OnlineApplication oa, String metadataURL, byte[] certificate) throws CertificateException { MetadataFilterChain filterChain = new MetadataFilterChain(metadataURL, certificate); + filterChain.getFilters().add(new SchemaValidationFilter()); if (oa.isIsInterfederationIDP() != null && oa.isIsInterfederationIDP()) { Logger.info("Online-Application is an interfederated IDP. Add addional Metadata policies"); @@ -374,6 +376,8 @@ public class MOAMetadataProvider implements MetadataProvider { httpProvider.setMetadataFilter(filter); httpProvider.initialize(); + httpProvider.setRequireValidMetadata(true); + return httpProvider; } catch (Throwable e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/InterfederatedIDPPublicServiceFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/InterfederatedIDPPublicServiceFilter.java index 3d608fd6d..4d9b97a52 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/InterfederatedIDPPublicServiceFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/InterfederatedIDPPublicServiceFilter.java @@ -26,7 +26,6 @@ import org.opensaml.saml2.metadata.provider.FilterException; import org.opensaml.saml2.metadata.provider.MetadataFilter; import org.opensaml.xml.XMLObject; -import at.gv.egovernment.moa.id.commons.db.dao.config.InterfederationIDPType; import at.gv.egovernment.moa.id.commons.validation.ValidationHelper; import at.gv.egovernment.moa.logging.Logger; -- cgit v1.2.3 From 599cec1e0536be584c6d2d4d383b7b54637cd2ea Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 07:56:46 +0100 Subject: add PVP2 request and response schema validation --- .../exceptions/SchemaValidationException.java | 52 +++++++++++ .../pvp2x/verification/SAMLVerificationEngine.java | 86 ++++++++++++++--- .../metadata/SchemaValidationFilter.java | 103 +++++++++++++++++++++ 3 files changed, 227 insertions(+), 14 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SchemaValidationException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SchemaValidationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SchemaValidationException.java new file mode 100644 index 000000000..fc4ed1f28 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SchemaValidationException.java @@ -0,0 +1,52 @@ +/* + * 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.protocols.pvp2x.exceptions; + +/** + * @author tlenz + * + */ +public class SchemaValidationException extends PVP2Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * @param messageId + * @param parameters + */ + public SchemaValidationException(String messageId, Object[] parameters) { + super(messageId, parameters); + } + + /** + * @param messageId + * @param parameters + */ + public SchemaValidationException(String messageId, Object[] parameters, Throwable e) { + super(messageId, parameters, e); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index 4ba93f8fe..bb59e4cc1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -25,14 +25,20 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.verification; import java.util.ArrayList; import java.util.List; +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; + import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.common.xml.SAMLSchemaBuilder; import org.opensaml.saml2.core.Conditions; import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.StatusCode; import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.saml2.core.validator.AuthnRequestSchemaValidator; import org.opensaml.saml2.encryption.Decrypter; import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.saml2.metadata.IDPSSODescriptor; @@ -51,11 +57,14 @@ import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver; import org.opensaml.xml.security.x509.X509Credential; import org.opensaml.xml.signature.SignatureTrustEngine; import org.opensaml.xml.validation.ValidationException; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; @@ -81,9 +90,15 @@ public class SAMLVerificationEngine { SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); try { profileValidator.validate(samlObj.getSignature()); + performSchemaValidation(samlObj.getDOM()); + } catch (ValidationException e) { - // Indicates signature did not conform to SAML Signature profile - e.printStackTrace(); + Logger.warn("Signature is not conform to SAML signature profile", e); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (SchemaValidationException e) { + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + } CriteriaSet criteriaSet = new CriteriaSet(); @@ -103,12 +118,17 @@ public class SAMLVerificationEngine { public void verifyRequest(RequestAbstractType samlObj, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); + profileValidator.validate(samlObj.getSignature()); + performSchemaValidation(samlObj.getDOM()); + } catch (ValidationException e) { - // Indicates signature did not conform to SAML Signature profile - e.printStackTrace(); + Logger.warn("Signature is not conform to SAML signature profile", e); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (SchemaValidationException e) { + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + } CriteriaSet criteriaSet = new CriteriaSet(); @@ -173,16 +193,23 @@ public class SAMLVerificationEngine { List validatedassertions = new ArrayList(); for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { - Conditions conditions = saml2assertion.getConditions(); - DateTime notbefore = conditions.getNotBefore(); - DateTime notafter = conditions.getNotOnOrAfter(); - if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { - Logger.warn("PVP2 Assertion is out of Date"); + try { + performSchemaValidation(saml2assertion.getDOM()); - } else { - validatedassertions.add(saml2assertion); + Conditions conditions = saml2assertion.getConditions(); + DateTime notbefore = conditions.getNotBefore(); + DateTime notafter = conditions.getNotOnOrAfter(); + if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { + Logger.warn("PVP2 Assertion is out of Date"); + + } else { + validatedassertions.add(saml2assertion); + + } + + } catch (SchemaValidationException e) { - } + } } if (validatedassertions.isEmpty()) { @@ -213,4 +240,35 @@ public class SAMLVerificationEngine { throw new AssertionValidationExeption("pvp.12", null, e); } } + + private static void performSchemaValidation(Element source) throws SchemaValidationException { + + String err = null; + try { + Schema test = SAMLSchemaBuilder.getSAML11Schema(); + Validator val = test.newValidator(); + val.validate(new DOMSource(source)); + Logger.debug("Schema validation check done OK"); + return; + + } catch (SAXException e) { + err = e.getMessage(); + if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) + Logger.warn("Schema validation FAILED with exception:", e); + else + Logger.warn("Schema validation FAILED with message: "+ e.getMessage()); + + } catch (Exception e) { + err = e.getMessage(); + if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) + Logger.warn("Schema validation FAILED with exception:", e); + else + Logger.warn("Schema validation FAILED with message: "+ e.getMessage()); + + } + + throw new SchemaValidationException("pvp2.22", new Object[]{err}); + + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java new file mode 100644 index 000000000..403b68524 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java @@ -0,0 +1,103 @@ +/* + * 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.protocols.pvp2x.verification.metadata; + +import java.io.IOException; + +import org.opensaml.saml2.metadata.provider.FilterException; +import org.opensaml.saml2.metadata.provider.MetadataFilter; +import org.opensaml.xml.XMLObject; + +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; + +import org.opensaml.common.xml.SAMLSchemaBuilder; + +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public class SchemaValidationFilter implements MetadataFilter { + + private boolean isActive = true; + + public SchemaValidationFilter() { + + } + + /** + * + */ + public SchemaValidationFilter(boolean useSchemaValidation) { + this.isActive = useSchemaValidation; + } + + + /* (non-Javadoc) + * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) + */ + @Override + public void doFilter(XMLObject arg0) throws FilterException { + + String errString = null; + + if (isActive) { + try { + Schema test = SAMLSchemaBuilder.getSAML11Schema(); + Validator val = test.newValidator(); + DOMSource source = new DOMSource(arg0.getDOM()); + val.validate(source); + Logger.info("Metadata Schema validation check done OK"); + return; + + } catch (SAXException e) { + if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) + Logger.warn("Metadata Schema validation FAILED with exception:", e); + else + Logger.warn("Metadata Schema validation FAILED with message: "+ e.getMessage()); + + errString = e.getMessage(); + + } catch (Exception e) { + if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) + Logger.warn("Metadata Schema validation FAILED with exception:", e); + else + Logger.warn("Metadata Schema validation FAILED with message: "+ e.getMessage()); + + errString = e.getMessage(); + + } + + throw new FilterException("Metadata Schema validation FAILED with message: "+ errString); + + } else + Logger.info("Metadata Schema validation check is DEACTIVATED!"); + + } + +} -- cgit v1.2.3 From 6f70c39d276b3758da06e3121208e2f1ed0009a3 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 10:03:08 +0100 Subject: remove subject->nameID from AuthnRequest --- .../at/gv/egovernment/moa/id/moduls/AuthenticationManager.java | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index a4d63b144..dab89b7c3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -422,16 +422,10 @@ public class AuthenticationManager extends AuthServlet { authReq.setAssertionConsumerServiceIndex(0); authReq.setIssueInstant(new DateTime()); - Subject subject = SAML2Utils.createSAMLObject(Subject.class); - NameID name = SAML2Utils.createSAMLObject(NameID.class); - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - + Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); String serviceURL = PVPConfiguration.getInstance().getIDPPublicPath(); - name.setValue(serviceURL); issuer.setValue(serviceURL); - subject.setNameID(name); - authReq.setSubject(subject); issuer.setFormat(NameIDType.ENTITY); authReq.setIssuer(issuer); NameIDPolicy policy = SAML2Utils -- cgit v1.2.3 From 99b46131e3ef3753af9f1d17516cf900fd095b4d Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 10:43:51 +0100 Subject: add STORK-QAA to PVP SecClass mapping --- .../id/auth/builder/AuthenticationDataBuilder.java | 2 +- .../moa/id/moduls/AuthenticationManager.java | 58 +++++++++++++++++++--- .../egovernment/moa/id/util/PVPtoSTORKMapper.java | 22 +++++++- 3 files changed, 74 insertions(+), 8 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 52488c3cb..7aa4cd1f7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -536,7 +536,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { } else { Logger.debug("Found PVP QAA level. QAA mapping process starts ... "); - String mappedQAA = PVPtoSTORKMapper.getInstance().mapQAALevel(qaaLevel); + String mappedQAA = PVPtoSTORKMapper.getInstance().mapToQAALevel(qaaLevel); if (MiscUtil.isNotEmpty(mappedQAA)) authData.setQAALevel(mappedQAA); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index dab89b7c3..333bd35f1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -77,6 +77,7 @@ import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.SLOInformationContainer; import at.gv.egovernment.moa.id.data.SLOInformationImpl; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; @@ -87,9 +88,11 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; import at.gv.egovernment.moa.id.storage.AssertionStorage; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; @@ -381,6 +384,7 @@ public class AuthenticationManager extends AuthServlet { //get IDP metadata try { OAAuthParameter idp = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(target.getRequestedIDP()); + OAAuthParameter sp = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(target.getOAURL()); if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { Logger.info("Requested interfederation IDP " + target.getRequestedIDP() + " is not valid for interfederation."); @@ -389,7 +393,7 @@ public class AuthenticationManager extends AuthServlet { return; } - + EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). getEntityDescriptor(target.getRequestedIDP()); @@ -409,7 +413,7 @@ public class AuthenticationManager extends AuthServlet { redirectEndpoint == null ) redirectEndpoint = sss; } - + if (redirectEndpoint != null) { AuthnRequest authReq = SAML2Utils @@ -440,13 +444,55 @@ public class AuthenticationManager extends AuthServlet { SAML2Utils.createSAMLObject(RequestedAuthnContext.class); AuthnContextClassRef authnClassRef = - SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4"); + SAML2Utils.createSAMLObject(AuthnContextClassRef.class); + + if (sp != null && sp.isSTORKPVPGateway()){ + //use PVP SecClass instead of STORK QAA level + String secClass = null; + if (target instanceof MOASTORKRequest) { + + try { + MOASTORKRequest storkReq = (MOASTORKRequest) target; + secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( + PVPConstants.STORK_QAA_PREFIX + storkReq.getStorkAuthnRequest().getQaa()); + + } catch (Exception e) { + Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); + + } + } + + if (MiscUtil.isNotEmpty(secClass)) + authnClassRef.setAuthnContextClassRef(secClass); + else + authnClassRef.setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"); + + } else { + if (target instanceof MOASTORKRequest) { + //use requested QAA level from STORK request + try { + MOASTORKRequest storkReq = (MOASTORKRequest) target; + authnClassRef.setAuthnContextClassRef( + PVPConstants.STORK_QAA_PREFIX + storkReq.getStorkAuthnRequest().getQaa()); + Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef() + + " from STORK request"); + + } catch (Exception e) { + Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); + + } + + } + + if (MiscUtil.isEmpty(authnClassRef.getAuthnContextClassRef())) + authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4"); + + } + reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); authReq.setRequestedAuthnContext(reqAuthContext); - - + IEncoder binding = null; if (redirectEndpoint.getBinding().equals( SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java index 0ea03e29d..fe3b780fb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java @@ -36,6 +36,7 @@ import at.gv.egovernment.moa.util.MiscUtil; public class PVPtoSTORKMapper { private static final String PVP_SECCLASS_PREFIX = "http://www.ref.gv.at/ns/names/agiz/pvp/"; + private static final String STORK_QAA_PREFIX = "http://www.stork.gov.eu/1.0/"; private static final String MAPPING_RESOURCE = "resources/properties/pvp-stork_mapping.properties"; @@ -67,12 +68,31 @@ public class PVPtoSTORKMapper { } + /**Map a STORK QAA level to PVP SecClass + * + * @param STORK-QAA level + * @return PVP SecClass pvpQAALevel + */ + public String mapToSecClass(String storkQAALevel) { + if (mapping != null) { + String input = storkQAALevel.substring(STORK_QAA_PREFIX.length()); + String mappedQAA = mapping.getProperty(input); + if (MiscUtil.isNotEmpty(mappedQAA)) { + Logger.info("Map STORK-QAA " + storkQAALevel + " to PVP SecClass " + mappedQAA); + return mappedQAA; + + } + } + Logger.warn("No mapping for STORK-QAA " + storkQAALevel +" !"); + return null; + } + /**Map a PVP SecClass to STORK QAA level * * @param PVP SecClass pvpQAALevel * @return STORK-QAA level */ - public String mapQAALevel(String pvpQAALevel) { + public String mapToQAALevel(String pvpQAALevel) { if (mapping != null) { String input = pvpQAALevel.substring(PVP_SECCLASS_PREFIX.length()); String mappedQAA = mapping.getProperty(input); -- cgit v1.2.3 From 3e3109fbf3f93f52919f0ba6089b5488f598c149 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 11:40:33 +0100 Subject: add clock screw to assertion time validation --- .../id/protocols/pvp2x/verification/SAMLVerificationEngine.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index 4ba93f8fe..2247ad227 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -174,10 +174,14 @@ public class SAMLVerificationEngine { for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { Conditions conditions = saml2assertion.getConditions(); - DateTime notbefore = conditions.getNotBefore(); + DateTime notbefore = conditions.getNotBefore().minusMinutes(5); DateTime notafter = conditions.getNotOnOrAfter(); if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { - Logger.warn("PVP2 Assertion is out of Date"); + Logger.warn("PVP2 Assertion is out of Date. " + + "{ Current : " + new DateTime() + + " NotBefore: " + notbefore + + " NotAfter : " + notafter + + " }"); } else { validatedassertions.add(saml2assertion); -- cgit v1.2.3 From b8ce6db7bdc9576ae8daef6ea2b1a8da45a2a735 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 12:11:21 +0100 Subject: update minimal required attribute set for interfederated assertions --- .../protocols/pvp2x/utils/AssertionAttributeExtractor.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java index f0373e214..26b3bfbd1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java @@ -54,8 +54,7 @@ public class AssertionAttributeExtractor { private final List minimalAttributeNameList = Arrays.asList( PVPConstants.PRINCIPAL_NAME_NAME, - PVPConstants.GIVEN_NAME_NAME, - PVPConstants.BIRTHDATE_NAME); + PVPConstants.GIVEN_NAME_NAME); public AssertionAttributeExtractor(StatusResponseType samlResponse) throws AssertionAttributeExtractorExeption { @@ -119,16 +118,21 @@ public class AssertionAttributeExtractor { //first check if a bPK or an encrypted bPK is available if (attributs.containsKey(PVPConstants.ENC_BPK_LIST_NAME) || - (attributs.containsKey(PVPConstants.BPK_NAME) && attributs.containsKey(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME))) { + (attributs.containsKey(PVPConstants.BPK_NAME))) { boolean flag = true; for (String attr : attributeNameList) { - if (!attributs.containsKey(attr)) + if (!attributs.containsKey(attr)) { flag = false; + Logger.debug("Assertion contains no Attribute " + attr); + + } + } return flag; - } + } + Logger.debug("Assertion contains no bPK or encryptedbPK."); return false; } -- cgit v1.2.3 From 0acb196f1a070ae31ca9cdb888dbf966460441c6 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 12:12:11 +0100 Subject: fix sessionTimeOut extraction from interfederated session --- .../id/auth/builder/AuthenticationDataBuilder.java | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 7aa4cd1f7..d5a6a1b70 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -43,6 +43,7 @@ import javax.xml.bind.Marshaller; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeQuery; +import org.opensaml.saml2.core.AuthnStatement; import org.opensaml.saml2.core.Response; import org.opensaml.ws.soap.common.SOAPException; import org.opensaml.xml.XMLObject; @@ -271,12 +272,13 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(intfResp); - if (!extractor.containsAllRequiredAttributes()) { + if (!extractor.containsAllRequiredAttributes()) { + Logger.info("Received assertion does no contain a minimum set of attributes. Starting AttributeQuery process ..."); //collect attributes by using BackChannel communication String endpoint = idp.getIDPAttributQueryServiceURL(); if (MiscUtil.isEmpty(endpoint)) { - Logger.error("No AttributeQueryURL for interfederationIDP " + oaParam.getPublicURLPrefix()); - throw new ConfigurationException("No AttributeQueryURL for interfederationIDP " + oaParam.getPublicURLPrefix(), null); + Logger.error("No AttributeQueryURL for interfederationIDP " + idp.getPublicURLPrefix()); + throw new ConfigurationException("No AttributeQueryURL for interfederationIDP " + idp.getPublicURLPrefix(), null); } //build attributQuery request @@ -761,8 +763,19 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { authData.setSsoSession(true); authData.setInterfederatedSSOSession(true); - if (extractor.getFullAssertion().getConditions() != null && extractor.getFullAssertion().getConditions().getNotOnOrAfter() != null) + if (extractor.getFullAssertion().getAuthnStatements() != null + && extractor.getFullAssertion().getAuthnStatements().size() > 0) { + for (AuthnStatement el : extractor.getFullAssertion().getAuthnStatements()) { + if (el.getSessionNotOnOrAfter() != null) { + authData.setSsoSessionValidTo(el.getSessionNotOnOrAfter().toDate()); + break; + } + } + + } else { authData.setSsoSessionValidTo(extractor.getFullAssertion().getConditions().getNotOnOrAfter().toDate()); + + } //only for SAML1 if (PVPConstants.STORK_QAA_1_4.equals(authData.getQAALevel())) -- cgit v1.2.3 From 37384244fd52e2ee22608f1504aee825a1966113 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 12:32:23 +0100 Subject: remove a not standardize prefix from PVP BPK attribute value. - this is a workaround for LFRZ Stammportal interfederation --- .../moa/id/auth/builder/AuthenticationDataBuilder.java | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index d5a6a1b70..d19080c25 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -368,6 +368,14 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { if (extractor.containsAttribute(PVPConstants.BPK_NAME)) { String pvpbPK = extractor.getSingleAttributeValue(PVPConstants.BPK_NAME); + + if (pvpbPK.startsWith("bPK:")) { + Logger.warn("Attribute " + PVPConstants.BPK_NAME + + " contains a not standardize prefix! Staring attribute value correction process ..."); + pvpbPK = pvpbPK.substring("bPK:".length()); + + } + String[] spitted = pvpbPK.split(":"); authData.setBPK(spitted[1]); if (MiscUtil.isEmpty(authData.getBPKType())) { -- cgit v1.2.3 From 6865934e3b6e20dd145025703e51af8b4b259e1b Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 14:45:38 +0100 Subject: add fix to correct invalid encoded EID_SECTOR_FOR_IDENTIFIER PVP attribute values --- .../moa/id/auth/builder/AuthenticationDataBuilder.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index d19080c25..bae5bb1f6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -360,12 +360,25 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { authData.setFamilyName(extractor.getSingleAttributeValue(PVPConstants.PRINCIPAL_NAME_NAME)); authData.setGivenName(extractor.getSingleAttributeValue(PVPConstants.GIVEN_NAME_NAME)); authData.setDateOfBirth(extractor.getSingleAttributeValue(PVPConstants.BIRTHDATE_NAME)); - authData.setBPKType(extractor.getSingleAttributeValue(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME)); authData.setCcc(extractor.getSingleAttributeValue(PVPConstants.EID_ISSUING_NATION_NAME)); authData.setBkuURL(extractor.getSingleAttributeValue(PVPConstants.EID_CCS_URL_NAME)); authData.setIdentificationValue(extractor.getSingleAttributeValue(PVPConstants.EID_SOURCE_PIN_NAME)); authData.setIdentificationType(extractor.getSingleAttributeValue(PVPConstants.EID_SOURCE_PIN_TYPE_NAME)); + + if (extractor.containsAttribute(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME)) { + String bpkType = extractor.getSingleAttributeValue(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME); + if (bpkType.startsWith(Constants.URN_PREFIX_CDID) && + !bpkType.substring(Constants.URN_PREFIX_CDID.length(), + Constants.URN_PREFIX_CDID.length() + 1).equals("+")) { + Logger.warn("Receive uncorrect encoded bBKType attribute " + bpkType + " Starting attribute value correction ... "); + bpkType = Constants.URN_PREFIX_CDID + "+" + bpkType.substring(Constants.URN_PREFIX_CDID.length() + 1); + + } + + authData.setBPKType(bpkType); + } + if (extractor.containsAttribute(PVPConstants.BPK_NAME)) { String pvpbPK = extractor.getSingleAttributeValue(PVPConstants.BPK_NAME); -- cgit v1.2.3 From 9a859b2e6f94042ef0665eb4f63248e48978a059 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 4 Nov 2014 14:46:07 +0100 Subject: update STORK attribute provider implementation --- .../id/protocols/stork2/AttributeCollector.java | 31 ++++++++----- .../id/protocols/stork2/MOAAttributeProvider.java | 2 +- .../PVPAuthenticationProvider.java | 53 +++++++++++----------- 3 files changed, 48 insertions(+), 38 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java index e3b9992aa..192f139eb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java @@ -121,7 +121,7 @@ public class AttributeCollector implements IAction { if (authnResponse.getPersonalAttributeList().size() > 0) { Logger.info("Response from external attribute provider contains " + authnResponse.getPersonalAttributeList().size() + " attributes."); - addOrUpdateAll(container.getResponse().getPersonalAttributeList(), authnResponse.getPersonalAttributeList()); + container.getResponse().setPersonalAttributeList(addOrUpdateAll(container.getResponse().getPersonalAttributeList(), authnResponse.getPersonalAttributeList())); } } @@ -157,7 +157,7 @@ public class AttributeCollector implements IAction { // - insert the embedded attribute(s) into the container if (null != newAttributes) - addOrUpdateAll(container.getResponse().getPersonalAttributeList(), newAttributes); + container.getResponse().setPersonalAttributeList(addOrUpdateAll(container.getResponse().getPersonalAttributeList(), newAttributes)); // see if we need some more attributes SLOInformationImpl sloInfo = (SLOInformationImpl) processRequest(container, httpReq, httpResp, authData, oaParam); @@ -203,7 +203,8 @@ public class AttributeCollector implements IAction { IPersonalAttributeList aquiredAttributes = new PersonalAttributeList(); currentAttribute.setStatus(AttributeStatusType.NOT_AVAILABLE.value()); aquiredAttributes.add((PersonalAttribute) currentAttribute.clone()); - addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes); + container.getResponse().setPersonalAttributeList( + addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes)); // - check if we can find a suitable AttributeProvider Plugin Iterator attibuteProvidersInterator = AttributeProviderFactory.getConfiguredPlugins(oaParam.getStorkAPs()); @@ -247,7 +248,7 @@ public class AttributeCollector implements IAction { Logger.error("We have no suitable plugin for obtaining the attribute '" + currentAttribute.getName() + "'"); } else // else, update any existing attributes - addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes); + container.getResponse().setPersonalAttributeList(addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes)); } Logger.info("collecting attributes done"); @@ -296,15 +297,21 @@ public class AttributeCollector implements IAction { * * @param target the target * @param source the source + * @return * @throws MOAIDException */ - private void addOrUpdateAll(IPersonalAttributeList target, IPersonalAttributeList source) throws MOAIDException { + private PersonalAttributeList addOrUpdateAll(IPersonalAttributeList target, IPersonalAttributeList source) throws MOAIDException { + + PersonalAttributeList updatedList = new PersonalAttributeList(); + for (PersonalAttribute el : target) + updatedList.add(el); + Logger.debug("Updating " + source.size() + " attributes..."); for (PersonalAttribute current : source) { Logger.debug("treating " + current.getName()); // check if we need to update the current pa - if (target.containsKey(current.getName())) { + if (updatedList.containsKey(current.getName())) { PersonalAttribute existing = target.get(current.getName()); if(!(existing.isEmptyValue() && existing.isEmptyComplexValue())) if(!(existing.getValue().equals(current.getValue()) || existing.getComplexValue().equals(current.getComplexValue()))) { @@ -312,14 +319,16 @@ public class AttributeCollector implements IAction { throw new MOAIDException("stork.16", new Object[] {existing.getName()}); } - target.get(current.getName()).setStatus(current.getStatus()); - target.get(current.getName()).setValue(current.getValue()); - target.get(current.getName()).setComplexValue(current.getComplexValue()); + updatedList.get(current.getName()).setStatus(current.getStatus()); + updatedList.get(current.getName()).setValue(current.getValue()); + updatedList.get(current.getName()).setComplexValue(current.getComplexValue()); } else - target.add(current); + updatedList.add(current); - Logger.debug("...successfully treated " + current.getName()); + Logger.debug("...successfully treated " + current.getName()); } + + return updatedList; } /* (non-Javadoc) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java index 993514ec7..755102bf3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java @@ -71,7 +71,7 @@ public class MOAAttributeProvider { public MOAAttributeProvider(IAuthData authData, MOASTORKRequest moastorkRequest) { this.authData = authData; this.moastorkRequest = moastorkRequest; - Logger.debug("identity " + authData.getIdentificationType() + " " + authData.getIdentificationValue()); + } public void populateAttribute(PersonalAttributeList attributeList, PersonalAttribute requestedAttribute ) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java index 96aa55bcf..a026bac81 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java @@ -193,33 +193,34 @@ public class PVPAuthenticationProvider extends AttributeProvider { public IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException { - Logger.info(this.getClass().getSimpleName() + " tries to extract SAMLResponse out of HTTP Request"); + throw new UnsupportedAttributeException(); - //extract STORK Response from HTTP Request - //Decodes SAML Response - byte[] decSamlToken; - try { - decSamlToken = PEPSUtil.decodeSAMLToken(httpReq.getParameter("SAMLResponse")); - } catch(NullPointerException e) { - throw new UnsupportedAttributeException(); - } - - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - - STORKAuthnResponse authnResponse = null; - try { - //validate SAML Token - Logger.debug("Starting validation of SAML response"); - authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) httpReq.getRemoteHost()); - Logger.info("SAML response successfully verified!"); - - }catch(STORKSAMLEngineException e){ - Logger.error("Failed to verify STORK SAML Response", e); - throw new MOAIDException("stork.05", null); - } - - return authnResponse.getPersonalAttributeList(); +// Logger.info(this.getClass().getSimpleName() + " tries to extract SAMLResponse out of HTTP Request"); +// //extract STORK Response from HTTP Request +// //Decodes SAML Response +// byte[] decSamlToken; +// try { +// decSamlToken = PEPSUtil.decodeSAMLToken(httpReq.getParameter("SAMLResponse")); +// } catch(NullPointerException e) { +// throw new UnsupportedAttributeException(); +// } +// +// //Get SAMLEngine instance +// STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); +// +// STORKAuthnResponse authnResponse = null; +// try { +// //validate SAML Token +// Logger.debug("Starting validation of SAML response"); +// authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) httpReq.getRemoteHost()); +// Logger.info("SAML response successfully verified!"); +// +// }catch(STORKSAMLEngineException e){ +// Logger.error("Failed to verify STORK SAML Response", e); +// throw new MOAIDException("stork.05", null); +// } +// +// return authnResponse.getPersonalAttributeList(); } -- cgit v1.2.3 From b39bc0239d1e4a4d4a8b0fe708ee24c7709b9454 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 24 Nov 2014 08:14:16 +0100 Subject: add MSOrganisation attribute for ISA 1.18 --- .../id/auth/builder/AuthenticationDataBuilder.java | 6 +++++ .../moa/id/data/AuthenticationData.java | 28 ++++++++++++++-------- .../at/gv/egovernment/moa/id/data/IAuthData.java | 7 ++++-- .../id/protocols/stork2/MOAAttributeProvider.java | 8 +++++-- .../moa/id/protocols/stork2/STORKPVPUtilits.java | 2 +- 5 files changed, 36 insertions(+), 15 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index bae5bb1f6..731925c1b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -767,6 +767,12 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { } } + //set PVP OU attribute + if (extractor.containsAttribute(PVPConstants.OU_NAME)) { + authData.setPvpAttribute_OU(extractor.getSingleAttributeValue(PVPConstants.OU_NAME)); + Logger.debug("Found PVP 'OU' attribute in response -> " + authData.getPvpAttribute_OU()); + + } //set STORK attributes if (extractor.containsAttribute(PVPConstants.EID_STORK_TOKEN_NAME)) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java index 65c413ef9..05b008515 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java @@ -133,7 +133,9 @@ public class AuthenticationData implements IAuthData, Serializable { private String authBlock = null; private List encbPKList = null; + //ISA 1.18 attributes private List roles = null; + private String pvpAttribute_OU = null; private boolean useMandate = false; private MISMandate mandate = null; @@ -707,6 +709,7 @@ public class AuthenticationData implements IAuthData, Serializable { return roles; } + //ISA 1.18 attributes /** * @param roles the roles to set */ @@ -716,26 +719,31 @@ public class AuthenticationData implements IAuthData, Serializable { this.roles.add(role); } + + /** + * @return the pvpAttribute_OU + */ + public String getPvpAttribute_OU() { + return pvpAttribute_OU; + } + + /** + * @param pvpAttribute_OU the pvpAttribute_OU to set + */ + public void setPvpAttribute_OU(String pvpAttribute_OU) { + this.pvpAttribute_OU = pvpAttribute_OU; + } /* (non-Javadoc) * @see at.gv.egovernment.moa.id.data.IAuthData#isBusinessService() */ @Override public boolean isBusinessService() { - // TODO Auto-generated method stub return this.businessService; } public void setIsBusinessService(boolean flag) { this.businessService = flag; - } - - - - - - - - + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java index ebbf62ce7..ccc90a031 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java @@ -69,7 +69,9 @@ public interface IAuthData { IdentityLink getIdentityLink(); byte[] getSignerCertificate(); String getAuthBlock(); - + + //ISA 1.18 attributes + String getPvpAttribute_OU(); List getAuthenticationRoles(); boolean isPublicAuthority(); @@ -90,5 +92,6 @@ public interface IAuthData { String getCcc(); STORKAuthnRequest getStorkAuthnRequest(); String getStorkAuthnResponse(); - IPersonalAttributeList getStorkAttributes(); + IPersonalAttributeList getStorkAttributes(); + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java index 755102bf3..499265319 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java @@ -59,13 +59,17 @@ public class MOAAttributeProvider { static { Map tempSimpleMap = new HashMap(); tempSimpleMap.put("givenName", "getGivenName"); - tempSimpleMap.put("surname", "getFamilyName"); + tempSimpleMap.put("surname", "getFamilyName"); + tempSimpleMap.put("MSOrganization", "getPvpAttribute_OU"); storkAttributeSimpleMapping = Collections.unmodifiableMap(tempSimpleMap); + Map tempFunctionMap = new HashMap(); tempFunctionMap.put("eIdentifier", "geteIdentifier"); tempFunctionMap.put("ECApplicationRole","getECApplicationRole"); tempFunctionMap.put("dateOfBirth", "getFormatedDateOfBirth"); + tempFunctionMap.put("MSOrganization", "getMSOrganization"); storkAttributeFunctionMapping = Collections.unmodifiableMap(tempFunctionMap); + } public MOAAttributeProvider(IAuthData authData, MOASTORKRequest moastorkRequest) { @@ -129,7 +133,7 @@ public class MOAAttributeProvider { } return storkRoles; } - + private String getFormatedDateOfBirth() { if (authData.getDateOfBirth() != null) { DateFormat fmt = new SimpleDateFormat("yyyyMMdd"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java index d923eccde..123d32af4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java @@ -32,7 +32,7 @@ import java.util.List; public class STORKPVPUtilits { public static final List attributesRequirePVPAuthentication = - Arrays.asList("ECApplicationRole"); + Arrays.asList("ECApplicationRole", "MSOrganization"); -- cgit v1.2.3 From 50416e97cfe3c633cf3e146b85856bc0b418bfd0 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 24 Nov 2014 08:15:53 +0100 Subject: use OA target from request, if SAML1 is used. for legacy applications --- .../id/auth/parser/StartAuthentificationParameterParser.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java index 1bc3702e4..a123569d5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java @@ -132,12 +132,13 @@ public class StartAuthentificationParameterParser implements MOAIDAuthConstants{ String targetFriendlyNameConfig = oaParam.getTargetFriendlyName(); if (StringUtils.isEmpty(targetConfig) -// || (module.equals(SAML1Protocol.PATH) && -// !StringUtils.isEmpty(target)) + || (module.equals(SAML1Protocol.PATH) && + !StringUtils.isEmpty(target)) ) { - // no target attribut is given in OA config - // target is used from request - // check parameter + //INFO: ONLY SAML1 legacy mode + // if SAML1 is used and target attribute is given in request + // use requested target + // check target parameter if (!ParamValidatorUtils.isValidTarget(target)) { Logger.error("Selected target is invalid. Using target: " + target); throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12"); -- cgit v1.2.3 From 720477bf5951aa4a307e1150e8a34d373f66e62b Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 24 Nov 2014 09:29:51 +0100 Subject: fix problem with SLO and interfederation --- .../pvp2x/builder/SingleLogOutBuilder.java | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java index 01139d95c..50f42d928 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java @@ -43,6 +43,7 @@ import org.opensaml.saml2.core.StatusCode; import org.opensaml.saml2.core.StatusMessage; import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.saml2.metadata.SSODescriptor; import org.opensaml.saml2.metadata.SingleLogoutService; @@ -348,17 +349,29 @@ public class SingleLogOutBuilder { public static SingleLogoutService getResponseSLODescriptor(PVPTargetConfiguration spRequest) throws NoMetadataInformationException, NOSLOServiceDescriptorException { MOARequest moaReq = (MOARequest) spRequest.getRequest(); EntityDescriptor metadata = moaReq.getEntityMetadata(); - SPSSODescriptor spsso = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + SSODescriptor ssodesc = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); + + if (ssodesc == null) { + Logger.debug("No PVP SPSSO descriptor found --> search IDPSSO descriptor"); + ssodesc = metadata.getIDPSSODescriptor(SAMLConstants.SAML20P_NS); + + } + + if (ssodesc == null) { + Logger.error("Found no SLO ServiceDescriptor in Metadata"); + throw new NOSLOServiceDescriptorException("NO SLO ServiceDescriptor", null); + } + SingleLogoutService sloService = null; - for (SingleLogoutService el : spsso.getSingleLogoutServices()) { + for (SingleLogoutService el : ssodesc.getSingleLogoutServices()) { if (el.getBinding().equals(spRequest.getBinding())) sloService = el; } if (sloService == null) { - if (spsso.getSingleLogoutServices().size() != 0) - sloService = spsso.getSingleLogoutServices().get(0); + if (ssodesc.getSingleLogoutServices().size() != 0) + sloService = ssodesc.getSingleLogoutServices().get(0); else { Logger.error("Found no SLO ServiceDescriptor in Metadata"); -- cgit v1.2.3 From 539feb77b1244e691f1735403a5c040cf11ebd9f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 24 Nov 2014 09:54:56 +0100 Subject: send SLO success statuscode if no active SSO session is found - no SSO session cookie - no SP information in session database for requested nameID --- .../egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java index b22941216..aa154b84b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java @@ -135,8 +135,10 @@ public class SingleLogOutAction implements IAction { if (MiscUtil.isEmpty(ssoID)) { Logger.warn("Can not find active Session. Single LogOut not possible!"); SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); + //LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, null); + Logger.info("Sending SLO success message to requester ..."); + SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); return null; } else { @@ -147,7 +149,9 @@ public class SingleLogOutAction implements IAction { } catch (MOADatabaseException e) { Logger.warn("Can not find active Session. Single LogOut not possible!"); SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + //LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, null); + Logger.info("Sending SLO success message to requester ..."); SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); return null; -- cgit v1.2.3 From a904d1ef6313a7d510882ada132f7e90b39a0c64 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 24 Nov 2014 14:33:54 +0100 Subject: fix possible problems with PVP roles and role parameters --- .../moa/id/data/AuthenticationRoleFactory.java | 35 +++++++++++++--------- .../egovernment/moa/id/util/PVPtoSTORKMapper.java | 9 ++++-- 2 files changed, 27 insertions(+), 17 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationRoleFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationRoleFactory.java index 8915b2442..b3b29f6c5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationRoleFactory.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationRoleFactory.java @@ -26,6 +26,7 @@ import java.util.Arrays; import java.util.List; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -51,23 +52,29 @@ public class AuthenticationRoleFactory { List param = Arrays.asList(params.split(",")); String test = new String(); for (String el : param) { - test = test.concat(el); - if (!test.endsWith("\\") || - (test.endsWith("\\\\") && !test.endsWith("\\\\\\")) ) { - String[] keyValue = test.split("="); - if (keyValue.length < 2) { - role.addParameter(keyValue[0].trim(), ""); - Logger.debug("Add authentication roleparameter with key=" + keyValue[0].trim()); + if (MiscUtil.isNotEmpty(el)) { + test = test.concat(el); + if (!test.endsWith("\\") || + (test.endsWith("\\\\") && !test.endsWith("\\\\\\")) ) { + String[] keyValue = test.split("="); + if (keyValue.length < 2) { + role.addParameter(keyValue[0].trim(), ""); + Logger.debug("Add authentication roleparameter with key=" + keyValue[0].trim()); - } else { - role.addParameter(keyValue[0].trim(), keyValue[1].trim()); - Logger.debug("Add authentication roleparameter with key=" + keyValue[0].trim() - + " value=" + keyValue[1].trim()); + } else { + role.addParameter(keyValue[0].trim(), keyValue[1].trim()); + Logger.debug("Add authentication roleparameter with key=" + keyValue[0].trim() + + " value=" + keyValue[1].trim()); - } + } - test = new String(); - } + test = new String(); + + } else { + test = test.substring(0, test.length()-1).concat(","); + + } + } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java index fe3b780fb..5ef9494f4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java @@ -113,13 +113,16 @@ public class PVPtoSTORKMapper { */ public String map(AuthenticationRole el) { if (mapping != null) { - String ecRole = mapping.getProperty(el.getRawRoleString()); + //String ecRole = mapping.getProperty(el.getRawRoleString()); + String ecRole = mapping.getProperty(el.getRoleName()); if (MiscUtil.isNotEmpty(ecRole)) { - Logger.info("Map PVPRole " + el.getRawRoleString() + " to ECRole " + ecRole); + //Logger.info("Map PVPRole " + el.getRawRoleString() + " to ECRole " + ecRole); + Logger.info("Map PVPRole " + el.getRoleName() + " to ECRole " + ecRole); return ecRole; } } - Logger.warn("NO mapping for PVPRole "+ el.getRawRoleString() + " !"); + //Logger.warn("NO mapping for PVPRole "+ el.getRawRoleString() + " !"); + Logger.warn("NO mapping for PVPRole "+ el.getRoleName() + " !"); return null; } } -- cgit v1.2.3 From f02943b7b4257bb9f16bd2e9f9d9dfb5a2f17944 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 24 Nov 2014 17:17:41 +0100 Subject: change interfederation with short SAML1 assertion: insert baseID if it is requested and available --- .../moa/id/protocols/saml1/SAML1AuthenticationServer.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java index 65e520cc3..c8a480cac 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java @@ -64,6 +64,7 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.StringUtils; import at.gv.util.xsd.persondata.IdentificationType; import at.gv.util.xsd.persondata.IdentificationType.Value; @@ -222,8 +223,14 @@ public class SAML1AuthenticationServer extends AuthenticationServer { Value value = new Value(); id.setValue(value ); - id.setType(Constants.URN_PREFIX_BASEID); - value.setValue(""); + id.setType(authData.getIdentificationType()); + //add baseID if it is requested and available + if ( MiscUtil.isNotEmpty(authData.getIdentificationValue()) && + saml1parameter.isProvideIdentityLink() ) + value.setValue(authData.getIdentificationValue()); + else + value.setValue(""); + familyName.setValue(authData.getFamilyName()); familyName.setPrimary("undefined"); name.getGivenName().add(authData.getGivenName()); -- cgit v1.2.3 From 9ebec8cfa0e56467314bbd983d87640411b12ce3 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 24 Nov 2014 17:19:27 +0100 Subject: rebuild SAML1 target parameter functionality for legacy applications --- .../id/auth/builder/AuthenticationDataBuilder.java | 27 ++++++++++++++-------- .../servlet/GenerateIFrameTemplateServlet.java | 17 ++++++++++---- .../moa/id/protocols/saml1/GetArtifactAction.java | 4 ++-- .../moa/id/protocols/saml1/SAML1Protocol.java | 11 ++++++--- 4 files changed, 39 insertions(+), 20 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 731925c1b..5fb4d6be8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -215,7 +215,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { } else { //build AuthenticationData from MOASession - buildAuthDataFormMOASession(authdata, session, oaParam); + buildAuthDataFormMOASession(authdata, session, oaParam, protocolRequest); } @@ -323,7 +323,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { } //parse response information to authData - buildAuthDataFormInterfederationResponse(authdata, session, extractor, oaParam); + buildAuthDataFormInterfederationResponse(authdata, session, extractor, oaParam, req); } catch (SOAPException e) { throw new BuildException("builder.06", null, e); @@ -350,7 +350,8 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { AuthenticationData authData, AuthenticationSession session, AssertionAttributeExtractor extractor, - IOAAuthParameters oaParam) + IOAAuthParameters oaParam, + IRequest req) throws BuildException, AssertionAttributeExtractorExeption { Logger.debug("Build AuthData from assertion starts ...."); @@ -536,7 +537,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { } //build OA specific bPK/wbPK information - buildOAspecificbPK(oaParam, authData, + buildOAspecificbPK(req, oaParam, authData, authData.getIdentificationValue(), authData.getIdentificationType()); @@ -544,7 +545,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { if (MiscUtil.isEmpty(authData.getBPK())) { Logger.debug("Calcutlate bPK from baseID"); - buildOAspecificbPK(oaParam, authData, + buildOAspecificbPK(req, oaParam, authData, authData.getIdentificationValue(), authData.getIdentificationType()); @@ -845,7 +846,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { } private static void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, - IOAAuthParameters oaParam) throws BuildException, ConfigurationException { + IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { IdentityLink identityLink = session.getIdentityLink(); @@ -959,7 +960,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); } else { - buildOAspecificbPK(oaParam, authData, + buildOAspecificbPK(protocolRequest, oaParam, authData, identityLink.getIdentificationValue(), identityLink.getIdentificationType()); @@ -1003,7 +1004,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { } - private static void buildOAspecificbPK(IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { + private static void buildOAspecificbPK(IRequest protocolRequest, IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { if (oaParam.getBusinessService()) { //since we have foreigner, wbPK is not calculated in BKU @@ -1024,9 +1025,15 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { if (baseIDType.equals(Constants.URN_PREFIX_BASEID)) { // only compute bPK if online application is a public service and we have the Stammzahl - String bpkBase64 = new BPKBuilder().buildBPK(baseID, oaParam.getTarget()); + String target = null; + if (protocolRequest instanceof SAML1RequestImpl) + target = protocolRequest.getTarget(); + else + target = oaParam.getTarget(); + + String bpkBase64 = new BPKBuilder().buildBPK(baseID, target); authData.setBPK(bpkBase64); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget()); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + target); } Logger.trace("Authenticate user with bPK " + authData.getBPK()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index 2ef8ab5ec..99a7dce89 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -45,6 +45,9 @@ import at.gv.egovernment.moa.id.commons.db.dao.config.TemplateType; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.moduls.RequestStorage; +import at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; @@ -116,11 +119,15 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { else { - //load Parameters from config - String target = oaParam.getTarget(); - - - + //get Target from config or from request in case of SAML 1 + String target = null; + IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID); + if (MiscUtil.isNotEmpty(pendingReq.getTarget()) && + pendingReq.requestedModule().equals(SAML1Protocol.PATH)) + target = pendingReq.getTarget(); + else + target = oaParam.getTarget(); + String bkuURL = oaParam.getBKUURL(bkuid); if (MiscUtil.isEmpty(bkuURL)) { Logger.info("No OA specific BKU defined. Use BKU from default configuration"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java index 67f780b3a..4cdd1db01 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java @@ -83,7 +83,7 @@ public class GetArtifactAction implements IAction { String url = AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/RedirectServlet"; url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(oaURL, "UTF-8")); if (!oaParam.getBusinessService()) - url = addURLParameter(url, PARAM_TARGET, URLEncoder.encode(oaParam.getTarget(), "UTF-8")); + url = addURLParameter(url, PARAM_TARGET, URLEncoder.encode(req.getTarget(), "UTF-8")); url = addURLParameter(url, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); url = httpResp.encodeRedirectURL(url); @@ -95,7 +95,7 @@ public class GetArtifactAction implements IAction { String redirectURL = oaURL; if (!oaParam.getBusinessService()) { redirectURL = addURLParameter(redirectURL, PARAM_TARGET, - URLEncoder.encode(oaParam.getTarget(), "UTF-8")); + URLEncoder.encode(req.getTarget(), "UTF-8")); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java index 8f7f17e2e..9934c339d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java @@ -132,7 +132,7 @@ public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { if (!ParamValidatorUtils.isValidOA(oaURL)) throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); - + config.setOAURL(oaURL); Logger.info("Dispatch SAML1 Request: OAURL=" + oaURL); @@ -156,8 +156,13 @@ public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { new Object[] { null }); } - config.setSourceID(sourceID); - config.setTarget(oaParam.getTarget()); + config.setSourceID(sourceID); + if (MiscUtil.isNotEmpty(target)) + config.setTarget(target); + + else + config.setTarget(oaParam.getTarget()); + return config; } -- cgit v1.2.3 From d222f975e7ad212264dab7cb7a0c39ec40478222 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 4 Dec 2014 09:57:17 +0100 Subject: STORK<->PVP AttributeProvider : fix problem with more then one attribute in configuration --- .../protocols/stork2/attributeproviders/PVPAuthenticationProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java index a026bac81..7f06c604b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java @@ -80,7 +80,7 @@ public class PVPAuthenticationProvider extends AttributeProvider { this.moastorkRequest = moastorkRequest; // break if we cannot handle the requested attribute - if (!attributes.contains(attribute.getName())) { + if (!getSupportedAttributeNames().contains(attribute.getName())) { Logger.info("Attribute " + attribute.getName() + " not supported by the provider: " + getAttrProviderName()); throw new UnsupportedAttributeException(); -- cgit v1.2.3 From b0bc9154341c873038f701033ceafb326f7ecbc5 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Wed, 17 Dec 2014 11:02:35 +0100 Subject: configuration --- .../id/config/auth/AuthConfigurationProvider.java | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index 23369fecc..6e85a8847 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -53,6 +53,7 @@ import java.io.IOException; import java.math.BigInteger; import java.net.MalformedURLException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -1007,6 +1008,39 @@ public class AuthConfigurationProvider extends ConfigurationProvider { return null; } + /** + * Checks if is fakeIdL is activated. + * + * @return true, if fake IdLs are available for stork + */ + public boolean isStorkFakeIdLActive() { + String prop = props.getProperty("stork.fakeIdL.active", "false"); + return Boolean.valueOf(prop); + } + + /** + * Gets the countries which will receive a fake IdL + * + * @return the countries + */ + public List getStorkFakeIdLCountries() { + String prop = props.getProperty("stork.fakeIdL.countries", ""); + return Arrays.asList(prop.replaceAll(" ", "").split(",")); + } + + /** + * Gets the resigning key (group) for the stork fake IdL. + * + * @return the resigning key + */ + public String getStorkFakeIdLResigningKey() { + String prop = props.getProperty("stork.fakeIdL.keygroup"); + if (MiscUtil.isNotEmpty(prop)) + return prop; + else + return null; + } + public boolean isMonitoringActive() { String prop = props.getProperty("configuration.monitoring.active", "false"); return Boolean.valueOf(prop); -- cgit v1.2.3 From beb1673375bda5c9d768b7140439cbd0f05f7ed0 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Wed, 17 Dec 2014 11:12:11 +0100 Subject: use config to decide whether to do fakeIdL or SZRGW --- .../egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index 4cd192070..4d6d3e538 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -360,14 +360,19 @@ public class PEPSConnectorServlet extends AuthServlet { targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); } - Logger.debug("Starting connecting SZR Gateway"); - //contact SZR Gateway IdentityLink identityLink = null; try { - identityLink = STORKResponseProcessor.connectToSZRGateway(authnResponse.getPersonalAttributeList(), + AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); + if(config.isStorkFakeIdLActive() && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) { + // create fake IdL + } else { + //contact SZR Gateway + Logger.debug("Starting connecting SZR Gateway"); + identityLink = STORKResponseProcessor.connectToSZRGateway(authnResponse.getPersonalAttributeList(), 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 -- cgit v1.2.3 From 939821e31d2ad1dff38b87a56582bfeb9f1a5c93 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Thu, 18 Dec 2014 11:14:19 +0100 Subject: loaded fakeIdL template --- .../at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index 4d6d3e538..3b086a991 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -48,6 +48,7 @@ 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 at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; @@ -66,6 +67,7 @@ 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.DOMUtils; import at.gv.egovernment.moa.util.StringUtils; import at.gv.util.xsd.xmldsig.SignatureType; import at.gv.util.xsd.xmldsig.X509DataType; @@ -365,6 +367,9 @@ public class PEPSConnectorServlet extends AuthServlet { AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); if(config.isStorkFakeIdLActive() && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) { // create fake IdL + // - fetch IdL template from resources + InputStream s = PEPSConnectorServlet.class.getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); + Element idlTemplate = DOMUtils.parseXmlValidating(s); } else { //contact SZR Gateway Logger.debug("Starting connecting SZR Gateway"); -- cgit v1.2.3 From 3afb02f1dddd13244e1a9a456f129d6c759faf80 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Thu, 18 Dec 2014 14:00:42 +0100 Subject: filled the template idl with data --- .../auth/parser/IdentityLinkAssertionParser.java | 6 ++-- .../moa/id/auth/servlet/PEPSConnectorServlet.java | 40 +++++++++++++++++++++- .../moa/id/auth/stork/STORKResponseProcessor.java | 2 +- 3 files changed, 43 insertions(+), 5 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParser.java index e2802c1d2..a5783bfb7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParser.java @@ -106,7 +106,7 @@ public class IdentityLinkAssertionParser { + PDATA + "Person"; /** Xpath expression to the PersonData GivenName element */ - private static final String PERSON_GIVEN_NAME_XPATH = + public static final String PERSON_GIVEN_NAME_XPATH = PERSON_XPATH + "/" + PDATA @@ -114,7 +114,7 @@ public class IdentityLinkAssertionParser { + PDATA + "GivenName"; /** Xpath expression to the PersonData FamilyName element */ - private static final String PERSON_FAMILY_NAME_XPATH = + public static final String PERSON_FAMILY_NAME_XPATH = PERSON_XPATH + "/" + PDATA @@ -122,7 +122,7 @@ public class IdentityLinkAssertionParser { + PDATA + "FamilyName"; /** Xpath expression to the PersonData DateOfBirth element */ - private static final String PERSON_DATE_OF_BIRTH_XPATH = + public static final String PERSON_DATE_OF_BIRTH_XPATH = PERSON_XPATH + "/" + PDATA diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index 3b086a991..0a8f0db6f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -49,6 +49,7 @@ 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.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; @@ -56,6 +57,7 @@ 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.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.commons.db.ConfigurationDBUtils; @@ -65,10 +67,12 @@ import at.gv.egovernment.moa.id.moduls.ModulUtils; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.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.oasisdss.api.ApiUtils; @@ -369,7 +373,41 @@ public class PEPSConnectorServlet extends AuthServlet { // create fake IdL // - fetch IdL template from resources InputStream s = PEPSConnectorServlet.class.getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); - Element idlTemplate = DOMUtils.parseXmlValidating(s); + 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); + prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth); + + identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink(); } else { //contact SZR Gateway Logger.debug("Starting connecting SZR Gateway"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java index 7113dcf70..ea1526ff0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java @@ -102,7 +102,7 @@ public class STORKResponseProcessor { private static String getAttributeValue(String attributeName, IPersonalAttributeList attributeList) throws STORKException { return getAttributeValue(attributeName, attributeList, true); } - private static String getAttributeValue(String attributeName, IPersonalAttributeList attributeList, boolean throwException) throws STORKException { + 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); -- cgit v1.2.3 From 81f8e1dc93570ff15f122f1c30fe6cb90e3158f0 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Thu, 18 Dec 2014 17:10:45 +0100 Subject: signed the new fake idl --- .../moa/id/auth/builder/AuthenticationDataBuilder.java | 8 +++++++- .../egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java | 5 +++++ .../at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java | 10 +--------- 3 files changed, 13 insertions(+), 10 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 52488c3cb..4d84ce0a5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -951,7 +951,13 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { //resign IDL IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); Element resignedilAssertion; - resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion()); + + AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); + if (config.isIdentityLinkResigning()) { + resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), config.getIdentityLinkResigningKey()); + } else { + resignedilAssertion = businessServiceIdl.getSamlAssertion(); + } IdentityLinkAssertionParser resignedIDLParser = new IdentityLinkAssertionParser(resignedilAssertion); IdentityLink resignedIDL = resignedIDLParser.parseIdentityLink(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index 0a8f0db6f..10d0ddbc4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -408,6 +408,11 @@ public class PEPSConnectorServlet extends AuthServlet { 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"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java index 090bea486..520b81b17 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java @@ -71,13 +71,9 @@ public class IdentityLinkReSigner { return instance; } - public Element resignIdentityLink(Element idl) throws MOAIDException { + public Element resignIdentityLink(Element idl, String keyGroupId) throws MOAIDException { try { - AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); - - if (config.isIdentityLinkResigning()) { - if (idl == null) { Logger.warn("IdentityLink is empty"); return null; @@ -91,7 +87,6 @@ public class IdentityLinkReSigner { SPSSFactory spssFac = SPSSFactory.getInstance(); - String keyGroupId = config.getIdentityLinkResigningKey(); if (MiscUtil.isEmpty(keyGroupId)) { Logger.warn("No IdentityLink reSigning-Key definded"); throw new MOAIDException("config.19", new Object[]{}); @@ -166,9 +161,6 @@ public class IdentityLinkReSigner { Logger.warn("Allgemeiner Fehler beim Aufruf von MOA-SS: Unbekannter ResponseType von MOA-SS"); throw new MOAIDException("builder.05", new Object[]{}); } - - } else - return idl; } catch (ConfigurationException e) { Logger.warn("Configuration can not be loaded", e); -- cgit v1.2.3 From 0ed0a7702850b2001aaa8d5b194708a96e90dea3 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Fri, 9 Jan 2015 11:25:10 +0100 Subject: Apply several fixes. - Disable erroneous IAIK PKI logger initialization (should be addressed by. - Remove redundant maven-dependency version declarations. - Fix maven/eclipse lifecyle warning problem. --- .../main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java | 3 +++ 1 file changed, 3 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index db36356c0..c3575470f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -148,12 +148,15 @@ public class MOAIDAuthInitializer { } } + // FIXME[@tlenz]: iaik.prod:iaik_X509TrustManager requires iaik.IAIKRuntimeException (should have been moved from iaik.server.modules (iaik.prod:iaik_moa:1.51)) // Initializes IAIKX509TrustManager logging + /* String log4jConfigURL = System.getProperty("log4j.configuration"); Logger.info("Log4J Configuration: " + log4jConfigURL); if (log4jConfigURL != null) { IAIKX509TrustManager.initLog(new LoggerConfigImpl(log4jConfigURL)); } + */ // Initializes the Axis secure socket factory for use in calling the // MOA-SP web service -- cgit v1.2.3 From 33a37cce841e6c48ab044cd153aa7ed7cfffc6cc Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Wed, 14 Jan 2015 12:41:54 +0100 Subject: Apply some minor fixes. - Add some FIXMEs. - Fix moa-id-auth web.xml and switch to Servlet 3.0. - Fix moa-id-auth logging (replace commons-logging with commons-logging-slf4j bridge, use log4j native binding). - Adjust logging of periodical tasks (no more logging at info level). --- .../main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java | 2 +- .../java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index c3575470f..d4ce8670e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -148,7 +148,7 @@ public class MOAIDAuthInitializer { } } - // FIXME[@tlenz]: iaik.prod:iaik_X509TrustManager requires iaik.IAIKRuntimeException (should have been moved from iaik.server.modules (iaik.prod:iaik_moa:1.51)) + // FIXME[@tlenz]: iaik.prod:iaik_X509TrustManager requires iaik.IAIKRuntimeException which might have been moved to iaik.server.modules (iaik.prod:iaik_moa:1.51)) // Initializes IAIKX509TrustManager logging /* String log4jConfigURL = System.getProperty("log4j.configuration"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java index b02c0946c..593b72658 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java @@ -40,7 +40,7 @@ public class AuthConfigLoader implements Runnable { try { Thread.sleep(INTERVAL * 1000); - Logger.info("check for new config."); + Logger.trace("check for new config."); MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); if (moaidconfig != null) { -- cgit v1.2.3 From 92717efaa56e3d0f7c271b91483507cf981b417b Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Fri, 16 Jan 2015 10:19:44 +0100 Subject: Add minor fixes and updates. - Fix moa-id-auth web.xml and upgrade to servlet 3.0. - Reformat loginFormFull.html in order to enhance readability. - Add some TODOs and FIXMEs. - Adding some comments to DispatcherServlet in order to ease understanding the process. --- .../id/auth/servlet/GetMISSessionIDServlet.java | 2 ++ .../PEPSConnectorWithLocalSigningServlet.java | 1 + .../moa/id/entrypoints/DispatcherServlet.java | 27 ++++++++++++++++++---- 3 files changed, 25 insertions(+), 5 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java index 9e2e845b5..20c32a3ec 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java @@ -197,6 +197,7 @@ public class GetMISSessionIDServlet extends AuthServlet { // for now: list contains only one element MISMandate mandate = (MISMandate) list.get(0); + // TODO[tlenz]: UTF-8 ? String sMandate = new String(mandate.getMandate()); if (sMandate == null || sMandate.compareToIgnoreCase("") == 0) { Logger.error("Mandate is empty."); @@ -206,6 +207,7 @@ public class GetMISSessionIDServlet extends AuthServlet { //check if it is a parsable XML byte[] byteMandate = mandate.getMandate(); + // TODO[tlenz]: UTF-8 ? String stringMandate = new String(byteMandate); DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java index 3bc79f8bd..165445ea5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java @@ -473,6 +473,7 @@ public class PEPSConnectorWithLocalSigningServlet extends AuthServlet { Logger.info("Found AttributeProviderPlugin attribute:"+ap.getAttributes()); if(ap.getAttributes().equalsIgnoreCase("signedDoc")) { + // FIXME[tlenz]: A servlet's class field is not thread safe. oasisDssWebFormURL = ap.getUrl(); found = true; Logger.info("Loaded signedDoc attribute provider url from config:"+oasisDssWebFormURL); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index 03cb6c1c4..a4c5c938f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -23,7 +23,6 @@ package at.gv.egovernment.moa.id.entrypoints; import java.io.IOException; - import java.util.Iterator; import javax.servlet.ServletConfig; @@ -97,10 +96,13 @@ public class DispatcherServlet extends AuthServlet{ boolean useSSOOA = false; String protocolRequestID = null; - try { Logger.info("REQUEST: " + req.getRequestURI()); Logger.info("QUERY : " + req.getQueryString()); + + +// *** start of error handling *** + String errorid = req.getParameter(ERROR_CODE_PARAM); if (errorid != null) { @@ -117,7 +119,7 @@ public class DispatcherServlet extends AuthServlet{ pendingRequestID = (String) idObject; } - if (throwable != null) { + if (throwable != null) { IRequest errorRequest = null; if (pendingRequestID != null) { @@ -173,6 +175,11 @@ public class DispatcherServlet extends AuthServlet{ return; } +// *** end of error handling *** + + +// *** start of protocol specific stuff *** + Object moduleObject = req.getParameter(PARAM_TARGET_MODULE); String module = null; if (moduleObject != null && (moduleObject instanceof String)) { @@ -357,7 +364,11 @@ public class DispatcherServlet extends AuthServlet{ } } - + +// *** end of protocol specific stuff *** + +// *** start handling authentication *** + AuthenticationManager authmanager = AuthenticationManager.getInstance(); String moasessionID = null; @@ -473,7 +484,11 @@ public class DispatcherServlet extends AuthServlet{ //build authenticationdata from session information and OA configuration authData = AuthenticationDataBuilder.buildAuthenticationData(protocolRequest, moasession); } - + +// *** end handling authentication *** + +// *** start finalizing authentication (SSO, final redirects, statistic logging etc) *** + SLOInformationInterface assertionID = moduleAction.processRequest(protocolRequest, req, resp, authData); RequestStorage.removePendingRequest(protocolRequestID); @@ -506,6 +521,8 @@ public class DispatcherServlet extends AuthServlet{ } +// *** end finalizing authentication *** + } catch (Throwable e) { Logger.warn("An authentication error occured: ", e);; // Try handle module specific, if not possible rethrow -- cgit v1.2.3 From 098357d27cab4a43aa8bd911960e16a1cf69726a Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 16 Jan 2015 11:00:58 +0100 Subject: add HTTP Proxy support to MIS and SZR-GW webservice request methods --- .../moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java | 3 ++- .../gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java index e1cd59c26..61b26b59a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java @@ -65,6 +65,7 @@ import org.w3c.dom.NodeList; import org.w3c.dom.Text; import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; +import at.gv.egovernment.moa.id.commons.utils.HttpClientWithProxySupport; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DOMUtils; @@ -137,7 +138,7 @@ public class SZRGWClient { if (address == null) { throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null."); } - HttpClient client = new HttpClient(); + HttpClient client = HttpClientWithProxySupport.getHttpClient(); PostMethod method = new PostMethod(address); method.setRequestHeader("SOAPAction", ""); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java index ab8d19803..24c96a78f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java @@ -71,6 +71,7 @@ import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWSecureSocketFactory; +import at.gv.egovernment.moa.id.commons.utils.HttpClientWithProxySupport; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.StringUtils; @@ -301,7 +302,7 @@ public class MISSimpleClient { throw new NullPointerException("Argument request must not be null."); } try { - HttpClient httpclient = new HttpClient(); + HttpClient httpclient = HttpClientWithProxySupport.getHttpClient(); PostMethod post = new PostMethod(webServiceURL); StringRequestEntity re = new StringRequestEntity(DOMUtils.serializeNode(packIntoSOAP(request)),"text/xml", "UTF-8"); post.setRequestEntity(re); -- cgit v1.2.3 From 3c795bdf9d27eadb48dc8d55573128f6b1edb030 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 16 Jan 2015 11:15:38 +0100 Subject: add configuration parameter to deactivate PVP metadata schema validation --- .../moa/id/config/auth/AuthConfigurationProvider.java | 5 +++++ .../pvp2x/verification/metadata/SchemaValidationFilter.java | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index a67badf49..43ec87b12 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -1047,6 +1047,11 @@ public class AuthConfigurationProvider extends ConfigurationProvider { return !Boolean.valueOf(prop); } + public boolean isPVPSchemaValidationActive() { + String prop = props.getProperty("protocols.pvp2.schemavalidation", "true"); + return !Boolean.valueOf(prop); + } + /** * Retruns the STORK Configuration * @return STORK Configuration diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java index 403b68524..382adb108 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java @@ -36,6 +36,8 @@ import org.opensaml.common.xml.SAMLSchemaBuilder; import org.xml.sax.SAXException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.logging.Logger; /** @@ -47,7 +49,12 @@ public class SchemaValidationFilter implements MetadataFilter { private boolean isActive = true; public SchemaValidationFilter() { - + try { + isActive = AuthConfigurationProvider.getInstance().isPVPSchemaValidationActive(); + + } catch (ConfigurationException e) { + e.printStackTrace(); + } } /** -- cgit v1.2.3 From e6e2bbf9a6e4df5e714ab10babae013317bf8422 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Fri, 16 Jan 2015 15:11:48 +0100 Subject: Add dti-process-engine support. --- .../main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java index e5b2c598c..eb480e37c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java @@ -67,6 +67,8 @@ import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; +import com.datentechnik.process_engine.springweb.AbstractAuthSourceServlet; + import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; @@ -88,7 +90,7 @@ import at.gv.egovernment.moa.util.URLDecoder; * @author Paul Ivancsics * @version $Id$ */ -public class AuthServlet extends HttpServlet implements MOAIDAuthConstants { +public class AuthServlet extends AbstractAuthSourceServlet implements MOAIDAuthConstants { /** * -- cgit v1.2.3 From 27ad3fcb9c078e74b3c183d5aa197d1e95eae2ee Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Mon, 19 Jan 2015 08:27:34 +0100 Subject: Fix wrong usage of servlet-api method. --- .../java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index a4c5c938f..e3b7524ae 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -279,7 +279,7 @@ public class DispatcherServlet extends AuthServlet{ //create interfederated MOASession String sessionID = AuthenticationSessionStoreage.createInterfederatedSession(protocolRequest, true, ssoId); - req.getParameterMap().put(PARAM_SESSIONID, sessionID); + req.getParameterMap().put(PARAM_SESSIONID, new String[]{ sessionID }); Logger.info("PreProcessing of SSO interfederation response complete. "); -- cgit v1.2.3 From ff3495293eff7c1a6eebd105bf79d23879d8d830 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 19 Jan 2015 12:07:32 +0100 Subject: Fix problem with PVP schemavalidation flag --- .../at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index 43ec87b12..dae5ffcef 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -1049,7 +1049,7 @@ public class AuthConfigurationProvider extends ConfigurationProvider { public boolean isPVPSchemaValidationActive() { String prop = props.getProperty("protocols.pvp2.schemavalidation", "true"); - return !Boolean.valueOf(prop); + return Boolean.valueOf(prop); } /** -- cgit v1.2.3 From a1bb34634bf4f30fc565109358eb51bd1111dc21 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Wed, 21 Jan 2015 08:50:58 +0100 Subject: Add "DefaultAuthentication" process (AT, no mandates, no stork) (MOAID-59). - Fix oa web.xml, switch to servlet 3.0. - moa-id-auth web.xml -- Add CharacterEncodingFilter for UTF-8 encoding. -- Add ProcessEngineSignalServlet. - Fix invalid template_*.html. - Add TODO[branch] annotations in order to indicates potential process flow branches. - Add some missing Javadoc. - Add property processInstandId to AuthenticationSession. - Add process engine support. - Fix HttpServlet init issues. - Set VerifyAuthenticationBlockServlet and VerifyIdentityLinkServlet deprecated. --- .../moa/id/auth/AuthenticationServer.java | 5 + .../auth/builder/StartAuthenticationBuilder.java | 11 + .../moa/id/auth/data/AuthenticationSession.java | 20 +- .../moa/id/auth/servlet/AuthServlet.java | 43 ++- .../servlet/GenerateIFrameTemplateServlet.java | 60 ++- .../auth/servlet/ProcessEngineSignalServlet.java | 60 +++ .../servlet/VerifyAuthenticationBlockServlet.java | 8 + .../id/auth/servlet/VerifyIdentityLinkServlet.java | 6 + .../moa/id/auth/tasks/AbstractAuthServletTask.java | 402 +++++++++++++++++++++ .../id/auth/tasks/CreateIdentityLinkFormTask.java | 85 +++++ .../auth/tasks/VerifyAuthenticationBlockTask.java | 255 +++++++++++++ .../moa/id/auth/tasks/VerifyIdentityLinkTask.java | 203 +++++++++++ .../moa/id/moduls/AuthenticationManager.java | 177 ++++----- 13 files changed, 1216 insertions(+), 119 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index a33c4fdf4..0b4b6b4af 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -1790,6 +1790,8 @@ public class AuthenticationServer implements MOAIDAuthConstants { "application/xhtml+xml", moasession.getCcc())); newAttribute.setValue(value); attributeList.add(newAttribute); + + // TODO[branch]: STORK AuthReq CPEPS acsURL "/PEPSConnector" } else//Process SignRequest locally with MOCCA { @@ -1805,6 +1807,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { moasession.setSignedDoc(signedDoc); acsURL = issuerValue + PEPSConnectorWithLocalSigningServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; + // TODO[branch]: STORK AuthReq acsURL "/PEPSConnectorWithLocalSigning" try { AuthenticationSessionStoreage.storeSession(moasession); } catch (MOADatabaseException e) { @@ -1897,6 +1900,8 @@ public class AuthenticationServer implements MOAIDAuthConstants { 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")); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java index 484fe1f9e..a92d3f678 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java @@ -47,6 +47,16 @@ public class StartAuthenticationBuilder { } + /** + * Depending on the selected citizen's country ({@code moasession.ccc}): + *
    + *
  • Either creates an "IdentityLinkForm" with embedded {@code InfoBoxReadRequest} to be submitted to a citizen card + * environment for reading the subject's IdentityLink
  • + *
  • or creates a STORK auth request and redirects to a CPEPS.
  • + *
+ * + * @return The "IdentityLinkForm" or an empty String in case of STORK. + */ public String build(AuthenticationSession moasession, HttpServletRequest req, HttpServletResponse resp) throws WrongParametersException, MOAIDException { @@ -58,6 +68,7 @@ public class StartAuthenticationBuilder { Logger.info("Starting authentication for a citizen of country: " + (StringUtils.isEmpty(moasession.getCcc()) ? "AT" : moasession.getCcc())); // STORK or normal authentication + // TODO[branch]: STORK if (storkConfig.isSTORKAuthentication(moasession.getCcc())) { //STORK authentication Logger.trace("Found C-PEPS configuration for citizen of country: " + moasession.getCcc()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 26c22fb4a..76bf93249 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java @@ -304,6 +304,8 @@ public class AuthenticationSession implements Serializable { private String authnContextClassRef; // private String requestedProtocolURL = null; + private String processInstanceId; + public String getAuthnContextClassRef() { return authnContextClassRef; } @@ -1110,6 +1112,22 @@ public class AuthenticationSession implements Serializable { */ public Date getSessionCreated() { return sessionCreated; - } + } + + /** + * Returns the identifier of the process instance associated with this moaid session. + * @return The process instance id (may be {@code null} if no process has been created yet). + */ + public String getProcessInstanceId() { + return processInstanceId; + } + + /** + * Sets the process instance identifier in order to associate a certain process instance with this moaid session. + * @param processInstanceId The process instance id. + */ + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java index eb480e37c..404dc68af 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java @@ -66,8 +66,11 @@ import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; - -import com.datentechnik.process_engine.springweb.AbstractAuthSourceServlet; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.NoUniqueBeanDefinitionException; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; @@ -83,6 +86,8 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLDecoder; +import com.datentechnik.process_engine.ProcessEngine; + /** * Base class for MOA-ID Auth Servlets, providing standard error handling and * constant names. @@ -90,7 +95,7 @@ import at.gv.egovernment.moa.util.URLDecoder; * @author Paul Ivancsics * @version $Id$ */ -public class AuthServlet extends AbstractAuthSourceServlet implements MOAIDAuthConstants { +public class AuthServlet extends HttpServlet implements MOAIDAuthConstants { /** * @@ -99,6 +104,11 @@ public class AuthServlet extends AbstractAuthSourceServlet implements MOAIDAuthC protected static final String ERROR_CODE_PARAM = "errorid"; + /** + * The process engine. + */ + private ProcessEngine processEngine; + @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { @@ -456,4 +466,31 @@ public class AuthServlet extends AbstractAuthSourceServlet implements MOAIDAuthC } + + /** + * Returns the underlying process engine instance. + * + * @return The process engine (never {@code null}). + * @throws NoSuchBeanDefinitionException + * if no {@link ProcessEngine} bean was found. + * @throws NoUniqueBeanDefinitionException + * if more than one {@link ProcessEngine} bean was found. + * @throws BeansException + * if a problem getting the {@link ProcessEngine} bean occurred. + * @throws IllegalStateException + * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a + * Spring web environment. + */ + public synchronized ProcessEngine getProcessEngine() { + if (processEngine == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); + if (ctx == null) { + throw new IllegalStateException( + "Unable to find Spring WebApplicationContext. Servlet needs to be executed within a Spring web environment."); + } + processEngine = ctx.getBean(ProcessEngine.class); + } + return processEngine; + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index 2ef8ab5ec..430936e97 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -23,18 +23,14 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; -import java.io.PrintWriter; import java.util.List; -import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; -import at.gv.egovernment.moa.id.auth.MOAIDAuthInitializer; -import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; 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; @@ -46,29 +42,16 @@ import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.egovernment.moa.util.StringUtils; + +import com.datentechnik.process_engine.ProcessInstance; public class GenerateIFrameTemplateServlet extends AuthServlet { private static final long serialVersionUID = 1L; - public void init(ServletConfig servletConfig) throws ServletException { -// try { -// super.init(servletConfig); -// MOAIDAuthInitializer.initialize(); -// Logger.debug("default platform file.encoding: " + System.getProperty("file.encoding")); -// Logger.info(MOAIDMessageProvider.getInstance().getMessage("init.00", null)); -// } -// catch (Exception ex) { -// Logger.fatal(MOAIDMessageProvider.getInstance().getMessage("init.02", null), ex); -// throw new ServletException(ex); -// } - } - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Logger.info("Receive " + GenerateIFrameTemplateServlet.class + " Request"); @@ -95,7 +78,7 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { moasession = AuthenticationSessionStoreage.getSession(moasessionid); - AuthenticationSessionStoreage.changeSessionID(moasession); +// AuthenticationSessionStoreage.changeSessionID(moasession); } catch (MOADatabaseException e) { Logger.info("MOASession with SessionID="+ moasessionid + " is not found in Database"); @@ -162,26 +145,28 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { req); } - StartAuthenticationBuilder startauth = StartAuthenticationBuilder.getInstance(); - String getIdentityLinkForm = startauth.build(moasession, req, resp); - - //store MOASession + // select and create process instance + // TODO[MOAID-49]: Automatically selection of process + ProcessInstance pi = getProcessEngine().createProcessInstance("DefaultAuthentication"); + // keep process instance id in moa session + moasession.setProcessInstanceId(pi.getId()); + // set execution context + pi.getExecutionContext().put("ccc", moasession.getCcc()); + pi.getExecutionContext().put("useMandate", moasession.getUseMandate()); + pi.getExecutionContext().put("bkuURL", moasession.getBkuURL()); + + // make sure moa session has been persisted before running the process try { AuthenticationSessionStoreage.storeSession(moasession); - } catch (MOADatabaseException e) { Logger.error("Database Error! MOASession is not stored!"); throw new MOAIDException("init.04", new Object[] { moasession.getSessionID()}); } - - if (!StringUtils.isEmpty(getIdentityLinkForm)) { - resp.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(resp.getOutputStream()); - out.print(getIdentityLinkForm); - out.flush(); - Logger.debug("Finished GET "+GenerateIFrameTemplateServlet.class); - } + + // start process + getProcessEngine().start(pi); + } catch (WrongParametersException ex) { handleWrongParameters(ex, req, resp); @@ -199,4 +184,13 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { ConfigurationDBUtils.closeSession(); } } + + + + + + + + + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java new file mode 100644 index 000000000..1ea8631c6 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -0,0 +1,60 @@ +package at.gv.egovernment.moa.id.auth.servlet; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; + +import com.datentechnik.process_engine.ProcessInstance; + +public class ProcessEngineSignalServlet extends AuthServlet { + + private static final long serialVersionUID = 1L; + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + try { + + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("ProcessEngineSignal", PARAM_SESSIONID, "auth.12"); + } + + // retrieve moa session + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + // process instance is mandatory + if (session.getProcessInstanceId() == null) { + throw new IllegalStateException("MOA session does not provide process instance id."); + } + + // wake up next task + ProcessInstance pi = getProcessEngine().getProcessInstance(session.getProcessInstanceId()); + getProcessEngine().signal(pi); + + } catch (Exception ex) { + handleError(null, ex, req, resp, null); + } finally { + MOASessionDBUtils.closeSession(); + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java index e7fa9cbd7..dc350bfb7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java @@ -71,6 +71,7 @@ import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; 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.tasks.VerifyAuthenticationBlockTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConnectionParameter; @@ -92,6 +93,7 @@ import at.gv.egovernment.moa.util.DOMUtils; * * @author Paul Ivancsics * @version $Id$ + * @deprecated Use {@link VerifyAuthenticationBlockTask} instead. */ public class VerifyAuthenticationBlockServlet extends AuthServlet { @@ -151,6 +153,9 @@ public class VerifyAuthenticationBlockServlet extends AuthServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (System.currentTimeMillis() > 0) { + throw new IllegalStateException(getClass().getName() + " should not be called any more."); + } Logger.debug("POST VerifyAuthenticationBlock"); resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); @@ -158,6 +163,9 @@ public class VerifyAuthenticationBlockServlet extends AuthServlet { resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + if (System.currentTimeMillis() > 0) { + throw new IllegalStateException(getClass().getName() + " should not be called any more."); + } String pendingRequestID = null; Map parameters; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java index 3b503f07b..3fcdfe150 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java @@ -65,6 +65,7 @@ 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.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.auth.tasks.VerifyIdentityLinkTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; @@ -82,6 +83,7 @@ import at.gv.egovernment.moa.logging.Logger; * * @author Paul Ivancsics * @version $Id$ + * @deprecated Use {@link VerifyIdentityLinkTask} instead. */ public class VerifyIdentityLinkServlet extends AuthServlet { @@ -134,6 +136,10 @@ public class VerifyIdentityLinkServlet extends AuthServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (System.currentTimeMillis() > 0) { + throw new IllegalStateException(getClass().getName() + " should not be called any more."); + } + Logger.debug("POST VerifyIdentityLink"); Map parameters; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java new file mode 100644 index 000000000..d43e8cf68 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java @@ -0,0 +1,402 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.lang3.ArrayUtils; + +import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +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.config.ConfigurationException; +import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; +import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; +import at.gv.egovernment.moa.id.storage.IExceptionStore; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import at.gv.egovernment.moa.util.URLDecoder; + +import com.datentechnik.process_engine.springweb.AbstractSpringWebSupportedTask; + +public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask implements MOAIDAuthConstants { + + protected static final String ERROR_CODE_PARAM = "errorid"; + + protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp) { + + if (null != errorMessage) { + Logger.error(errorMessage); + req.setAttribute("ErrorMessage", errorMessage); + } + + if (null != exceptionThrown) { + if (null == errorMessage) + errorMessage = exceptionThrown.getMessage(); + Logger.error(errorMessage, exceptionThrown); + req.setAttribute("ExceptionThrown", exceptionThrown); + } + + if (Logger.isDebugEnabled()) { + req.setAttribute("LogLevel", "debug"); + } + + + StatisticLogger logger = StatisticLogger.getInstance(); + logger.logErrorOperation(exceptionThrown); + + + // forward this to errorpage-auth.jsp where the HTML error page is + // generated + ServletContext context = req.getServletContext(); + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, + MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, + MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + dispatcher.forward(req, resp); + } catch (ServletException e) { + Logger.error(e); + } catch (IOException e) { + Logger.error(e); + } + } + + /** + * Handles an error.
> + *
    + *
  • Logs the error
  • + *
  • Places error message and exception thrown into the request as request + * attributes (to be used by "/errorpage-auth.jsp")
  • + *
  • Sets HTTP status 500 (internal server error)
  • + *
+ * + * @param errorMessage + * error message + * @param exceptionThrown + * exception thrown + * @param req + * servlet request + * @param resp + * servlet response + */ + protected void handleError(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { + + if (null != errorMessage) { + Logger.error(errorMessage); + req.setAttribute("ErrorMessage", errorMessage); + } + + if (null != exceptionThrown) { + if (null == errorMessage) + errorMessage = exceptionThrown.getMessage(); + Logger.error(errorMessage, exceptionThrown); + req.setAttribute("ExceptionThrown", exceptionThrown); + } + + if (Logger.isDebugEnabled()) { + req.setAttribute("LogLevel", "debug"); + } + + if (!(exceptionThrown instanceof MOAIDException)) { + Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown); + + } + + IExceptionStore store = DBExceptionStoreImpl.getStore(); + String id = store.storeException(exceptionThrown); + + if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { + + String redirectURL = null; + + redirectURL = ServletUtils.getBaseUrl(req); + redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id + + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + return; + + } else { + + //Exception can not be stored in database + handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); + } + } + + /** + * Handles a WrongParametersException. + * + * @param req + * servlet request + * @param resp + * servlet response + */ + protected void handleWrongParameters(WrongParametersException ex, + HttpServletRequest req, HttpServletResponse resp) { + Logger.error(ex.toString()); + req.setAttribute("WrongParameters", ex.getMessage()); + + // forward this to errorpage-auth.jsp where the HTML error page is + // generated + ServletContext context = req.getServletContext(); + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, + MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, + MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + dispatcher.forward(req, resp); + } catch (ServletException e) { + Logger.error(e); + } catch (IOException e) { + Logger.error(e); + } + } + + /** + * Logs all servlet parameters for debugging purposes. + */ + protected void logParameters(HttpServletRequest req) { + for (Enumeration params = req.getParameterNames(); params + .hasMoreElements();) { + String parname = (String) params.nextElement(); + Logger.debug("Parameter " + parname + req.getParameter(parname)); + } + } + + /** + * Parses the request input stream for parameters, assuming parameters are + * encoded UTF-8 (no standard exists how browsers should encode them). + * + * @param req + * servlet request + * + * @return mapping parameter name -> value + * + * @throws IOException + * if parsing request parameters fails. + * + * @throws FileUploadException + * if parsing request parameters fails. + */ + protected Map getParameters(HttpServletRequest req) throws IOException, + FileUploadException { + + Map parameters = new HashMap(); + + if (ServletFileUpload.isMultipartContent(req)) { + // request is encoded as mulitpart/form-data + FileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload upload = null; + upload = new ServletFileUpload(factory); + List items = null; + items = upload.parseRequest(req); + for (int i = 0; i < items.size(); i++) { + FileItem item = (FileItem) items.get(i); + if (item.isFormField()) { + // Process only form fields - no file upload items + String logString = item.getString("UTF-8"); + + // TODO use RegExp + String startS = ""; + String endS = "urn:publicid:gv.at:baseid"; + String logWithMaskedBaseid = logString; + int start = logString.indexOf(startS); + if (start > -1) { + int end = logString.indexOf(endS); + if (end > -1) { + logWithMaskedBaseid = logString.substring(0, start); + logWithMaskedBaseid += startS; + logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; + logWithMaskedBaseid += logString.substring(end, + logString.length()); + } + } + parameters + .put(item.getFieldName(), item.getString("UTF-8")); + Logger.debug("Processed multipart/form-data request parameter: \nName: " + + item.getFieldName() + + "\nValue: " + + logWithMaskedBaseid); + } + } + } + + else { + // request is encoded as application/x-www-urlencoded + // [tknall]: we must not consume request body input stream once servlet-api request parameters have been accessed + + /* + InputStream in = req.getInputStream(); + + String paramName; + String paramValueURLEncoded; + do { + paramName = new String(readBytesUpTo(in, '=')); + if (paramName.length() > 0) { + paramValueURLEncoded = readBytesUpTo(in, '&'); + String paramValue = URLDecoder.decode(paramValueURLEncoded, + "UTF-8"); + parameters.put(paramName, paramValue); + } + } while (paramName.length() > 0); + in.close(); + */ + + Iterator> requestParamIt = req.getParameterMap().entrySet().iterator(); + while (requestParamIt.hasNext()) { + Entry entry = requestParamIt.next(); + String key = entry.getKey(); + String[] values = entry.getValue(); + // take the last value from the value array since the legacy code above also does it this way + parameters.put(key, ArrayUtils.isEmpty(values) ? null : values[values.length-1]); + } + + } + + return parameters; + } + + /** + * Reads bytes up to a delimiter, consuming the delimiter. + * + * @param in + * input stream + * @param delimiter + * delimiter character + * @return String constructed from the read bytes + * @throws IOException + */ + protected String readBytesUpTo(InputStream in, char delimiter) + throws IOException { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + boolean done = false; + int b; + while (!done && (b = in.read()) >= 0) { + if (b == delimiter) + done = true; + else + bout.write(b); + } + return bout.toString(); + } + + + +// public void contextDestroyed(ServletContextEvent arg0) { +// Security.removeProvider((new IAIK()).getName()); +// Security.removeProvider((new ECCProvider()).getName()); +// } + + /** + * Set response headers to avoid caching + * + * @param request + * HttpServletRequest + * @param response + * HttpServletResponse + */ + protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, + HttpServletResponse response) { + response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, + MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, + MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, + MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + } + + /** + * Adds a parameter to a URL. + * + * @param url + * the URL + * @param paramname + * parameter name + * @param paramvalue + * parameter value + * @return the URL with parameter added + */ + protected static String addURLParameter(String url, String paramname, + String paramvalue) { + String param = paramname + "=" + paramvalue; + if (url.indexOf("?") < 0) + return url + "?" + param; + else + return url + "&" + param; + } + + /** + * Checks if HTTP requests are allowed + * + * @param authURL + * requestURL + * @throws AuthenticationException + * if HTTP requests are not allowed + * @throws ConfigurationException + */ + protected void checkIfHTTPisAllowed(String authURL) + throws AuthenticationException, ConfigurationException { + // check if HTTP Connection may be allowed (through + // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) + + //Removed from MOA-ID 2.0 config +// String boolStr = AuthConfigurationProvider +// .getInstance() +// .getGenericConfigurationParameter( +// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); + if ((!authURL.startsWith("https:")) + //&& (false == BoolUtils.valueOf(boolStr)) + ) + throw new AuthenticationException("auth.07", new Object[] { authURL + + "*" }); + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java new file mode 100644 index 000000000..4c87bb689 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java @@ -0,0 +1,85 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import java.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.ObjectUtils; + +import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +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.servlet.GenerateIFrameTemplateServlet; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import at.gv.egovernment.moa.util.StringUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + String pendingRequestID = null; + String moasessionid = StringEscapeUtils.escapeHtml(ObjectUtils.defaultIfNull(req.getParameter(PARAM_SESSIONID), (String) executionContext.get(PARAM_SESSIONID))); + AuthenticationSession moasession = null; + try { + + if (MiscUtil.isEmpty(moasessionid)) { + Logger.warn("MOASessionID is empty."); + throw new MOAIDException("auth.18", new Object[] {}); + } + + try { + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); + moasession = AuthenticationSessionStoreage.getSession(moasessionid); + AuthenticationSessionStoreage.changeSessionID(moasession); + executionContext.remove(PARAM_SESSIONID); + + } catch (MOADatabaseException e) { + Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { moasessionid }); + + } catch (Throwable e) { + Logger.info("No HTTP Session found!"); + throw new MOAIDException("auth.18", new Object[] {}); + } + + StartAuthenticationBuilder startauth = StartAuthenticationBuilder.getInstance(); + String getIdentityLinkForm = startauth.build(moasession, req, resp); + + if (!StringUtils.isEmpty(getIdentityLinkForm)) { + resp.setContentType("text/html;charset=UTF-8"); + PrintWriter out = new PrintWriter(resp.getOutputStream()); + out.print(getIdentityLinkForm); + out.flush(); + Logger.debug("Finished GET " + GenerateIFrameTemplateServlet.class); + } + + } catch (WrongParametersException ex) { + handleWrongParameters(ex, req, resp); + } + + catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("CreateIdentityLinkFormTask has an interal Error.", e); + + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java new file mode 100644 index 000000000..ff1bc8cd1 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java @@ -0,0 +1,255 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import iaik.pki.PKIException; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.SSLSocketFactory; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.transform.TransformerException; + +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.lang.StringEscapeUtils; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.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.MISSimpleClientException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.ConnectionParameter; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.SSLUtils; +import at.gv.egovernment.moa.id.util.client.mis.simple.MISSessionId; +import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { + + /** + * Verifies the signed authentication block and redirects the browser + * to the online application requested, adding a parameter needed for + * retrieving the authentication data. + *
+ * Request parameters: + *
    + *
  • MOASessionID: ID of associated authentication session
  • + *
  • XMLResponse: <CreateXMLSignatureResponse>
  • + *
+ * Response: + *
    + *
  • Status: 302
  • + *
  • Header "Location": URL of the online application requested, with + * parameters "Target"(only if the online application is + * a public service) and "SAMLArtifact" added
  • + *
  • Error status: 500 + *
+ * @see AuthenticationServer#verifyAuthenticationBlock + * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet + + Logger.debug("POST VerifyAuthenticationBlock"); + + String pendingRequestID = null; + + Map parameters; + try + { + parameters = getParameters(req); + } catch (FileUploadException e) + { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + + } + String sessionID = req.getParameter(PARAM_SESSIONID); + String createXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); + + // escape parameter strings + sessionID = StringEscapeUtils.escapeHtml(sessionID); + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + String redirectURL = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); + if (!ParamValidatorUtils.isValidXMLDocument(createXMLSignatureResponse)) + throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_XMLRESPONSE, "auth.12"); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + String samlArtifactBase64 = AuthenticationServer.getInstance().verifyAuthenticationBlock(session, createXMLSignatureResponse); + + + + if (samlArtifactBase64 == null) { + //mandate Mode + + AuthConfigurationProvider authConf= AuthConfigurationProvider.getInstance(); + ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter(); + SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters); + + // get identitity link as byte[] + Element elem = session.getIdentityLink().getSamlAssertion(); + String s = DOMUtils.serializeNode(elem); + + //System.out.println("IDL: " + s); + + byte[] idl = s.getBytes("UTF-8"); + + // redirect url + // build redirect(to the GetMISSessionIdSerlvet) + + //change MOASessionID before MIS request + String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + + redirectURL = + new DataURLBuilder().buildDataURL( + session.getAuthURL(), + GET_MIS_SESSIONID, + newMOASessionID); + + String oaURL = session.getOAURLRequested(); + OAAuthParameter oaParam = authConf.getOnlineApplicationParameter(oaURL); + List profiles = oaParam.getMandateProfiles(); + + if (profiles == null) { + Logger.error("No Mandate/Profile for OA configured."); + throw new AuthenticationException("config.21", new Object[] { GET_MIS_SESSIONID}); + } + +// String profilesArray[] = profiles.split(","); +// for(int i = 0; i < profilesArray.length; i++) { +// profilesArray[i] = profilesArray[i].trim(); +// } + + String oaFriendlyName = oaParam.getFriendlyName(); + String mandateReferenceValue = session.getMandateReferenceValue(); + byte[] cert = session.getEncodedSignerCertificate(); + byte[] authBlock = session.getAuthBlock().getBytes("UTF-8"); + + //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_+session.getDomainIdentifier(); + + } else { + targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); + } + + MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest( + connectionParameters.getUrl(), + idl, + cert, + oaFriendlyName, + redirectURL, + mandateReferenceValue, + profiles, + targetType, + authBlock, + sslFactory); + + if (misSessionID == null) { + Logger.error("Fehler bei Anfrage an Vollmachten Service. MIS Session ID ist null."); + throw new MISSimpleClientException("Fehler bei Anfrage an Vollmachten Service."); + } + + String redirectMISGUI = misSessionID.getRedirectURL(); + session.setMISSessionID(misSessionID.getSessiondId()); + + try { + AuthenticationSessionStoreage.storeSession(session); + } catch (MOADatabaseException e) { + throw new MOAIDException("Session store error", null); + } + + // TODO[branch]: Mandate; redirect to MIS website; website redirects back to "/GetMISSessionID" + + resp.setStatus(302); + resp.addHeader("Location", redirectMISGUI); + Logger.debug("REDIRECT TO: " + redirectURL); + } + else { + if (!samlArtifactBase64.equals("Redirect to Input Processor")) { + /*redirectURL = session.getOAURLRequested(); + if (!session.getBusinessService()) { + redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8")); + + } + redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); + redirectURL = resp.encodeRedirectURL(redirectURL);*/ + + // TODO[branch]: Final step back to /dispatcher + + redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), samlArtifactBase64); + + } else { + // TODO[tlenz]: Should not be needed any more (respective code in AuthenticationServer has been disabled) + redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, session.getSessionID()); + } + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + } + + } + + catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (GeneralSecurityException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (PKIException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (TransformerException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("AuthBlockValidation has an interal Error.", e); + } + + + finally { + ConfigurationDBUtils.closeSession(); + } + + + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java new file mode 100644 index 000000000..ec12643ec --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java @@ -0,0 +1,203 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import java.io.IOException; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; +import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; +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.ParseException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +public class VerifyIdentityLinkTask extends AbstractAuthServletTask { + + /** + * Verifies the identity link and responds with a new + * CreateXMLSignatureRequest or a new + * InfoboxReadRequest (in case of a foreign eID card). + *
+ * Request parameters: + *
    + *
  • MOASessionID: ID of associated authentication session
  • + *
  • XMLResponse: <InfoboxReadResponse>
  • + *
+ * Response: + *
    + *
  • Content type: "text/xml"
  • + *
  • Content: see return value of {@link AuthenticationServer#verifyIdentityLink}
  • + *
  • Error status: 500 + *
+ * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet + + Logger.debug("POST VerifyIdentityLink"); + + Map parameters; + String pendingRequestID = null; + + try + { + parameters = getParameters(req); + + } catch (Exception e) + { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + } + String sessionID = req.getParameter(PARAM_SESSIONID); + + // escape parameter strings + sessionID = StringEscapeUtils.escapeHtml(sessionID); + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); + + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters); + + Logger.debug(createXMLSignatureRequestOrRedirect); + + + if (createXMLSignatureRequestOrRedirect == null) { + // no identity link found + + boolean useMandate = session.getUseMandate(); + if (useMandate) { + Logger.error("Online-Mandate Mode for foreign citizencs not supported."); + throw new AuthenticationException("auth.13", null); + } + // TODO[branch]: Foreign citizen; respond with IRR for certificates, dataURL = "/VerifyCertificate" + + try { + + Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); + + // create the InfoboxReadRequest to get the certificate + String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); + + // build dataurl (to the VerifyCertificateSerlvet) + String dataurl = + new DataURLBuilder().buildDataURL( + session.getAuthURL(), + REQ_VERIFY_CERTIFICATE, + session.getSessionID()); + + ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + + + } + catch(Exception e) { + handleError(null, e, req, resp, pendingRequestID); + } + + } + else { + boolean useMandate = session.getUseMandate(); + + if (useMandate) { // Mandate modus + + // TODO[branch]: Mandate; respond with IRR for certificates, dataURL = "/VerifyCertificate" + + // read certificate and set dataurl to + Logger.debug("Send InfoboxReadRequest to BKU to get signer certificate."); + + + String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); + + // build dataurl (to the GetForeignIDSerlvet) + String dataurl = + new DataURLBuilder().buildDataURL( + session.getAuthURL(), + REQ_VERIFY_CERTIFICATE, + session.getSessionID()); + + //Logger.debug("ContentType set to: application/x-www-form-urlencoded (ServletUtils)"); + //ServletUtils.writeCreateXMLSignatureRequestURLEncoded(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + + Logger.debug("ContentType set to: text/xml;charset=UTF-8 (ServletUtils)"); + ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + + } + else { + Logger.info("Normal"); + + // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance() + .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, + authConf, oaParam); + + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink"); + } + } + + try { + AuthenticationSessionStoreage.storeSession(session); + + } catch (MOADatabaseException e) { + Logger.info("No valid MOA session found. Authentification process is abourted."); + throw new AuthenticationException("auth.20", null); + } + } + catch (ParseException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("IdentityLinkValidation has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index a4d63b144..0c481d94e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -59,17 +59,16 @@ import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.ws.soap.common.SOAPException; import org.opensaml.xml.XMLObject; import org.opensaml.xml.security.SecurityException; +import org.springframework.beans.factory.annotation.Autowired; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; import at.gv.egovernment.moa.id.auth.builder.SendAssertionFormBuilder; -import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; 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.BuildException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser; -import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; @@ -94,25 +93,28 @@ import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.egovernment.moa.util.StringUtils; -public class AuthenticationManager extends AuthServlet { +import com.datentechnik.process_engine.ProcessEngine; +import com.datentechnik.process_engine.ProcessExecutionException; +import com.datentechnik.process_engine.ProcessInstance; - private static AuthenticationManager instance = null; - - private static final long serialVersionUID = 1L; +public class AuthenticationManager implements MOAIDAuthConstants { + + private static final AuthenticationManager INSTANCE = new AuthenticationManager(); public static final String MOA_SESSION = "MoaAuthenticationSession"; public static final String MOA_AUTHENTICATED = "MoaAuthenticated"; public static final int SLOTIMEOUT = 30 * 1000; //30 sec + @Autowired + private ProcessEngine processEngine; + + private AuthenticationManager() { + } + public static AuthenticationManager getInstance() { - if (instance == null) { - instance = new AuthenticationManager(); - } - - return instance; + return INSTANCE; } /** @@ -508,7 +510,10 @@ public class AuthenticationManager extends AuthServlet { throws ServletException, IOException, MOAIDException { Logger.debug("Starting authentication on this IDP ..."); - setNoCachingHeadersInHttpRespone(request, response); + response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); List legacyallowed_prot = AuthConfigurationProvider.getInstance().getLegacyAllowedProtocols(); @@ -529,79 +534,87 @@ public class AuthenticationManager extends AuthServlet { throw new MOAIDException("init.04", new Object[] {}); } - - if (legacyallowed && legacyparamavail) { - - //parse request parameter into MOASession - StartAuthentificationParameterParser.parse(request, response, moasession, target); - - Logger.info("Start Authentication Module: " + moasession.getModul() - + " Action: " + moasession.getAction()); - - StartAuthenticationBuilder startauth = StartAuthenticationBuilder.getInstance(); - - String getIdentityLinkForm = startauth.build(moasession, request, response); - - //store MOASession - try { - AuthenticationSessionStoreage.storeSession(moasession, target.getRequestID()); - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { - moasession.getSessionID()}); - } - - if (!StringUtils.isEmpty(getIdentityLinkForm)) { - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(getIdentityLinkForm); - out.flush(); - Logger.debug("Finished GET StartAuthentication"); - } - - } else { - //load Parameters from OnlineApplicationConfiguration - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(target.getOAURL()); + try { - if (oaParam == null) { - throw new AuthenticationException("auth.00", new Object[] { target.getOAURL() }); - } + if (legacyallowed && legacyparamavail) { + + //parse request parameter into MOASession + StartAuthentificationParameterParser.parse(request, response, moasession, target); + + Logger.info("Start Authentication Module: " + moasession.getModul() + + " Action: " + moasession.getAction()); + + + // create process instance + // TODO[MOAID-49]: Automatically selection of process + ProcessInstance pi = processEngine.createProcessInstance("DefaultAuthentication"); + // keep process instance id in moa session + moasession.setProcessInstanceId(pi.getId()); + + // make sure moa session has been persisted before running the process + try { + AuthenticationSessionStoreage.storeSession(moasession); + } catch (MOADatabaseException e) { + Logger.error("Database Error! MOASession is not stored!"); + throw new MOAIDException("init.04", new Object[] { + moasession.getSessionID()}); + } + + // set execution context + pi.getExecutionContext().put("ccc", moasession.getCcc()); + pi.getExecutionContext().put("useMandate", moasession.getUseMandate()); + pi.getExecutionContext().put("bkuURL", moasession.getBkuURL()); + pi.getExecutionContext().put(PARAM_SESSIONID, moasession.getSessionID()); + + // start process + processEngine.start(pi); + + } else { + //load Parameters from OnlineApplicationConfiguration + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(target.getOAURL()); + + if (oaParam == null) { + throw new AuthenticationException("auth.00", new Object[] { target.getOAURL() }); + } + + else { + + //check if an MOASession exists and if not create an new MOASession + //moasession = getORCreateMOASession(request); + + //set OnlineApplication configuration in Session + moasession.setOAURLRequested(target.getOAURL()); + moasession.setAction(target.requestedAction()); + moasession.setModul(target.requestedModule()); + } - else { + //Build authentication form - //check if an MOASession exists and if not create an new MOASession - //moasession = getORCreateMOASession(request); - - //set OnlineApplication configuration in Session - moasession.setOAURLRequested(target.getOAURL()); - moasession.setAction(target.requestedAction()); - moasession.setModul(target.requestedModule()); - } - - //Build authentication form - - - String publicURLPreFix = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); - String loginForm = LoginFormBuilder.buildLoginForm(target.requestedModule(), - target.requestedAction(), oaParam, publicURLPreFix, moasession.getSessionID()); - - //store MOASession - try { - AuthenticationSessionStoreage.storeSession(moasession, target.getRequestID()); - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { - moasession.getSessionID()}); + + String publicURLPreFix = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); + String loginForm = LoginFormBuilder.buildLoginForm(target.requestedModule(), + target.requestedAction(), oaParam, publicURLPreFix, moasession.getSessionID()); + + //store MOASession + try { + AuthenticationSessionStoreage.storeSession(moasession, target.getRequestID()); + } catch (MOADatabaseException e) { + Logger.error("Database Error! MOASession is not stored!"); + throw new MOAIDException("init.04", new Object[] { + moasession.getSessionID()}); + } + + //set MOAIDSession + //request.getSession().setAttribute(MOA_SESSION, moasession.getSessionID()); + + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.print(loginForm); + out.flush(); } - - //set MOAIDSession - //request.getSession().setAttribute(MOA_SESSION, moasession.getSessionID()); - - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(loginForm); - out.flush(); + } catch (ProcessExecutionException e) { + throw new MOAIDException("process.01", new Object[] { moasession.getProcessInstanceId(), moasession }, e); } } } -- cgit v1.2.3 From ad40ae9233c5f2a32c983962d655e686af546677 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Thu, 22 Jan 2015 12:13:07 +0100 Subject: Add mandate process support (MOAID-60). - Refactor moa-id auth web.xml -- Group the servlets with their corresponding mappings. -- Replace servlets for mappings "/GetMISSessionID", "/VerifyAuthBlock", "/VerifyCertificate" and "/VerifyIdentityLink". -- Remove disabled declarations. - Replace link http://jigsaw.w3.org/css-validator/images/vcss-blue with https://... within the internal templates (loginFormFull.html, sendAssertionFormFull.html, ...). - Set classes deprecated: GetMISSessionIDServlet, VerifyCertificateServlet - ProcessEngineSignalServlet: make GET delegate to PUT - Replace some "implements MOAIDAuthConstants" with "import static MOAIDAuthConstants.*". - Add detailed Javadoc to *Task.java. - Update DefaultAuthentication.process.xml for mandate - Add GetMISSessionIDTask and VerifyCertificateTask. - Add adapter class for iaik.IAIKRuntimeException in order to satisfy some library's bogus dependendies. --- .../id/auth/servlet/GetMISSessionIDServlet.java | 7 +- .../auth/servlet/ProcessEngineSignalServlet.java | 39 ++- .../id/auth/servlet/VerifyCertificateServlet.java | 9 +- .../moa/id/auth/tasks/AbstractAuthServletTask.java | 68 ++--- .../id/auth/tasks/CreateIdentityLinkFormTask.java | 36 +++ .../moa/id/auth/tasks/GetMISSessionIDTask.java | 182 ++++++++++++ .../auth/tasks/VerifyAuthenticationBlockTask.java | 56 ++-- .../moa/id/auth/tasks/VerifyCertificateTask.java | 166 +++++++++++ .../moa/id/auth/tasks/VerifyIdentityLinkTask.java | 319 +++++++++++---------- .../protocols/pvp2x/exceptions/loginFormFull.html | 2 +- 10 files changed, 652 insertions(+), 232 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java index 20c32a3ec..dd5253e77 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java @@ -67,6 +67,7 @@ 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.tasks.GetMISSessionIDTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; @@ -83,7 +84,7 @@ import at.gv.egovernment.moa.util.DOMUtils; /** * Servlet requested for getting the foreign eID provided by the security layer * implementation. Utilizes the {@link AuthenticationServer}. - * + * @deprecated Use {@link GetMISSessionIDTask} instead. */ public class GetMISSessionIDServlet extends AuthServlet { @@ -136,6 +137,10 @@ public class GetMISSessionIDServlet extends AuthServlet { Logger.debug("POST GetMISSessionIDServlet"); + if (System.currentTimeMillis() > 0) { + throw new IllegalStateException(getClass().getName() + " should not be called any more."); + } + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java index 1ea8631c6..849ccf5db 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -17,19 +17,46 @@ import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import com.datentechnik.process_engine.ProcessInstance; +/** + * Servlet that resumes a suspended process (in case of asynchronous tasks). + * + * @author tknall + * + */ public class ProcessEngineSignalServlet extends AuthServlet { private static final long serialVersionUID = 1L; + /** + * Sets response headers that prevent caching (code taken from {@link AuthServlet}). + * + * @param resp + * The HttpServletResponse. + */ + private void setNoCachingHeaders(HttpServletResponse resp) { + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); + } + + /** + * Processes a GET request, delegating the call to {@link #doPost(HttpServletRequest, HttpServletResponse)}. + */ + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + this.doPost(req, resp); + } + + /** + * Resumes the current process instance that has been suspended due to an asynchronous task. The process instance is + * retrieved from the MOA session referred to by the request parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}. + */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - + setNoCachingHeaders(resp); try { // check parameter @@ -44,7 +71,7 @@ public class ProcessEngineSignalServlet extends AuthServlet { if (session.getProcessInstanceId() == null) { throw new IllegalStateException("MOA session does not provide process instance id."); } - + // wake up next task ProcessInstance pi = getProcessEngine().getProcessInstance(session.getProcessInstanceId()); getProcessEngine().signal(pi); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java index a3397f561..36e219a97 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java @@ -65,6 +65,7 @@ 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.tasks.VerifyCertificateTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; @@ -77,6 +78,7 @@ import at.gv.egovernment.moa.spss.util.CertificateUtils; * Servlet requested for getting the foreign eID * provided by the security layer implementation. * Utilizes the {@link AuthenticationServer}. + * @deprecated Use {@link VerifyCertificateTask} instead. * */ public class VerifyCertificateServlet extends AuthServlet { @@ -124,6 +126,9 @@ public class VerifyCertificateServlet extends AuthServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + if (System.currentTimeMillis() > 0) { + throw new IllegalStateException(getClass().getName() + " should not be called any more."); + } Logger.debug("POST VerifyCertificateServlet"); resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); @@ -180,7 +185,8 @@ public class VerifyCertificateServlet extends AuthServlet { throw new MOAIDException("session store error", null); } - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); + } else { @@ -210,7 +216,6 @@ public class VerifyCertificateServlet extends AuthServlet { ServletUtils.writeCreateXMLSignatureRequest(resp, session, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); - Logger.debug("Send CreateXMLSignatureRequest to BKU"); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java index d43e8cf68..d5b869777 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java @@ -1,5 +1,7 @@ package at.gv.egovernment.moa.id.auth.tasks; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -9,7 +11,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Set; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; @@ -25,10 +26,10 @@ import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang3.ArrayUtils; import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; 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.servlet.AuthServlet; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; @@ -36,11 +37,17 @@ import at.gv.egovernment.moa.id.storage.IExceptionStore; import at.gv.egovernment.moa.id.util.ServletUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.egovernment.moa.util.URLDecoder; import com.datentechnik.process_engine.springweb.AbstractSpringWebSupportedTask; -public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask implements MOAIDAuthConstants { +/** + * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing + * etc.).

The code has been taken from {@link AuthServlet}. + * + * @author tknall + * + */ +public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask { protected static final String ERROR_CODE_PARAM = "errorid"; @@ -75,14 +82,10 @@ public abstract class AbstractAuthServletTask extends AbstractSpringWebSupported .getRequestDispatcher("/errorpage-auth.jsp"); try { - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); dispatcher.forward(req, resp); } catch (ServletException e) { @@ -179,15 +182,7 @@ public abstract class AbstractAuthServletTask extends AbstractSpringWebSupported RequestDispatcher dispatcher = context .getRequestDispatcher("/errorpage-auth.jsp"); try { - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - + setNoCachingHeaders(resp); dispatcher.forward(req, resp); } catch (ServletException e) { Logger.error(e); @@ -324,32 +319,17 @@ public abstract class AbstractAuthServletTask extends AbstractSpringWebSupported return bout.toString(); } - - -// public void contextDestroyed(ServletContextEvent arg0) { -// Security.removeProvider((new IAIK()).getName()); -// Security.removeProvider((new ECCProvider()).getName()); -// } - /** - * Set response headers to avoid caching + * Sets response headers that prevent caching (code taken from {@link AuthServlet}). * - * @param request - * HttpServletRequest - * @param response - * HttpServletResponse + * @param resp + * The HttpServletResponse. */ - protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, - HttpServletResponse response) { - response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - + private void setNoCachingHeaders(HttpServletResponse resp) { + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); } /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java index 4c87bb689..70afd477d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java @@ -1,5 +1,7 @@ package at.gv.egovernment.moa.id.auth.tasks; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; @@ -8,6 +10,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.ObjectUtils; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -22,6 +25,39 @@ import at.gv.egovernment.moa.util.StringUtils; import com.datentechnik.process_engine.api.ExecutionContext; +/** + * Creates a http form including an embedded {@code InfoBoxReadRequest} for reading the identity link.

+ * In detail: + *

    + *
  • Renames the moa session id.
  • + *
  • Removes ExecutionContext property {@link MOAIDAuthConstants#PARAM_SESSIONID}.
  • + *
  • Creates the http form mentioned above.
  • + *
  • Returns the http form via HttpServletResponse.
  • + *
+ * Expects: + *
    + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID} or
  • + *
  • ExecutionContext property {@link MOAIDAuthConstants#PARAM_SESSIONID} (in case of legacy authentication without CCE selection, where the moa session is not provided by request parameter).
  • + *
+ * Result: + *
    + *
  • The identity link form via HttpServletResponse.
  • + *
+ * Possible branches: + *
    + *
  • In case of STORK authentication + *
      + *
    • Creates STORK auth SAML request.
    • + *
    • Creates and returns a form for submitting the SAML request to the CPEPS (post binding).
    • + *
    • Returns the form via HttpServletResponse.
    • + *
    + *
  • + *
+ * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GenerateIFrameTemplateServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { @Override diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java new file mode 100644 index 000000000..40e33ae43 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java @@ -0,0 +1,182 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import iaik.pki.PKIException; + +import java.security.GeneralSecurityException; +import java.util.List; + +import javax.net.ssl.SSLSocketFactory; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.lang.StringEscapeUtils; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +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.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.ConnectionParameter; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.SSLUtils; +import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; +import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Retrieves a mandate from the online mandate issuing service.

+ * In detail: + *

    + *
  • Renames the moa session id.
  • + *
  • Retrieves the mandate referenced within the moa session from the online (external) mandate issuing service.
  • + *
  • Verifies the mandate.
  • + *
  • Puts mandate into moa session.
  • + *
  • Redirects back to {@code /dispatcher} in order to finalize the authentication.
  • + *
+ * Expects: + *
    + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
  • + *
+ * Result: + *
    + *
  • Mandate put into moa session.
  • + *
  • Redirect to {@code /dispatcher}.
  • + *
+ * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GetMISSessionIDServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class GetMISSessionIDTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + Logger.debug("POST GetMISSessionIDServlet"); + + String sessionID = req.getParameter(PARAM_SESSIONID); + + // escape parameter strings + sessionID = StringEscapeUtils.escapeHtml(sessionID); + + AuthenticationSession session = null; + String pendingRequestID = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyCertificate", + PARAM_SESSIONID, "auth.12"); + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + session = AuthenticationServer.getSession(sessionID); + + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + String misSessionID = session.getMISSessionID(); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + ConnectionParameter connectionParameters = authConf + .getOnlineMandatesConnectionParameter(); + SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory( + AuthConfigurationProvider.getInstance(), + connectionParameters); + + List list = MISSimpleClient.sendGetMandatesRequest( + connectionParameters.getUrl(), misSessionID, sslFactory); + + if (list == null || list.size() == 0) { + Logger.error("Keine Vollmacht gefunden."); + throw new AuthenticationException("auth.15", null); + } + + // for now: list contains only one element + MISMandate mandate = (MISMandate) list.get(0); + + // TODO[tlenz]: UTF-8 ? + String sMandate = new String(mandate.getMandate()); + if (sMandate == null || sMandate.compareToIgnoreCase("") == 0) { + Logger.error("Mandate is empty."); + throw new AuthenticationException("auth.15", + new Object[] { GET_MIS_SESSIONID }); + } + + //check if it is a parsable XML + byte[] byteMandate = mandate.getMandate(); + // TODO[tlenz]: UTF-8 ? + String stringMandate = new String(byteMandate); + DOMUtils.parseDocument(stringMandate, false, + null, null).getDocumentElement(); + + // extract RepresentationType + AuthenticationServer.getInstance().verifyMandate(session, mandate); + + session.setMISMandate(mandate); + session.setAuthenticatedUsed(false); + session.setAuthenticated(true); + + //set QAA Level four in case of card authentifcation + session.setQAALevel(PVPConstants.STORK_QAA_1_4); + + String oldsessionID = session.getSessionID(); + + //Session is implicite stored in changeSessionID!!! + String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); + Logger.info("Daten angelegt zu MOASession " + newMOASessionID); + + String redirectURL = new DataURLBuilder().buildDataURL( + session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), + session.getAction(), pendingRequestID), newMOASessionID); + redirectURL = resp.encodeRedirectURL(redirectURL); + + // TODO[branch]: Final step back to /dispatcher + + resp.setContentType("text/html"); + resp.setStatus(302); + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (GeneralSecurityException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (PKIException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (SAXException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (ParserConfigurationException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("MISMandateValidation has an interal Error.", e); + + } + finally { + ConfigurationDBUtils.closeSession(); + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java index ff1bc8cd1..24fea05c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java @@ -38,30 +38,44 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; import com.datentechnik.process_engine.api.ExecutionContext; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +/** + * Verifies the signed authentication block (provided as {@code CreateXMLSignatureResponse}).

+ * In detail: + *

    + *
  • Renames the moa session id.
  • + *
  • Takes the {@code CreateXMLSignatureResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
  • + *
  • Verifies the {@code CreateXMLSignatureResponse}.
  • + *
  • Updates moa session.
  • + *
  • Redirects back to {@code /dispatcher} in order to finalize the authentication.
  • + *
+ * Expects: + *
    + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
  • + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
  • + *
+ * Result: + *
    + *
  • Authentication data put into moa session.
  • + *
  • Redirect to {@code /dispatcher}.
  • + *
+ * Possible branches: + *
    + *
  • In case of mandate mode + *
      + *
    • Creates a mandate session at the external mandate issuing service.
    • + *
    • Redirects the user's browser to the online mandate issuing service GUI.
    • + *
    + *
  • + *
+ * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { - /** - * Verifies the signed authentication block and redirects the browser - * to the online application requested, adding a parameter needed for - * retrieving the authentication data. - *
- * Request parameters: - *
    - *
  • MOASessionID: ID of associated authentication session
  • - *
  • XMLResponse: <CreateXMLSignatureResponse>
  • - *
- * Response: - *
    - *
  • Status: 302
  • - *
  • Header "Location": URL of the online application requested, with - * parameters "Target"(only if the online application is - * a public service) and "SAMLArtifact" added
  • - *
  • Error status: 500 - *
- * @see AuthenticationServer#verifyAuthenticationBlock - * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) - */ @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws Exception { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java new file mode 100644 index 000000000..979e64888 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java @@ -0,0 +1,166 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import iaik.x509.X509Certificate; + +import java.io.IOException; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.lang.StringEscapeUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +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.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.spss.util.CertificateUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Parses the certificate from {@code InfoBoxReadResponse} (via POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}), creates the auth block to be signed and returns a {@code CreateXMLSignatureRequest} for auth block signature.

+ * In detail: + *

    + *
  • Renames the moa session id.
  • + *
  • Retrieves the certificate via {@code InfoBoxReadResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
  • + *
  • Verifies the certificate.
  • + *
  • Creates the auth block to be signed using information from the certificate (Organwalter, foreign citizen.
  • + *
  • Puts it in a {@code CreateXMLSignatureRequest}.
  • + *
  • Updates moa session.
  • + *
  • Responds with {@code CreateXMLSignatureRequest}.
  • + *
+ * Expects: + *
    + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
  • + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE} containing a {@code InfoBoxReadResponse}.
  • + *
+ * Result: + *
    + *
  • {@code CreateXMLSignatureRequest} send as HttpServletResponse (for CCE).
  • + *
+ * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class VerifyCertificateTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet + + Logger.debug("POST VerifyCertificateServlet"); + + String pendingRequestID = null; + + Map parameters; + try + { + parameters = getParameters(req); + } catch (FileUploadException e) + { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + } + String sessionID = req.getParameter(PARAM_SESSIONID); + + // escape parameter strings + sessionID = StringEscapeUtils.escapeHtml(sessionID); + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + AuthenticationSession session = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12"); + + session = AuthenticationServer.getSession(sessionID); + + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + X509Certificate cert = AuthenticationServer.getInstance().getCertificate(sessionID, parameters); + if (cert == null) { + Logger.error("Certificate could not be read."); + throw new AuthenticationException("auth.14", null); + } + + boolean useMandate = session.getUseMandate(); + + + if (useMandate) { + + // verify certificate for OrganWalter + String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyCertificate(session, cert); + + try { + AuthenticationSessionStoreage.storeSession(session); + } catch (MOADatabaseException e) { + throw new MOAIDException("session store error", null); + } + + // TODO[branch]: Mandate; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); + + } + else { + + + String countrycode = CertificateUtils.getIssuerCountry(cert); + if (countrycode != null) { + if (countrycode.compareToIgnoreCase("AT") == 0) { + Logger.error("Certificate issuer country code is \"AT\". Login not support in foreign identities mode."); + throw new AuthenticationException("auth.22", null); + } + } + + // Foreign Identities Modus + String createXMLSignatureRequest = AuthenticationServer.getInstance().createXMLSignatureRequestForeignID(session, cert); + // build dataurl (to the GetForeignIDSerlvet) + String dataurl = + new DataURLBuilder().buildDataURL( + session.getAuthURL(), + REQ_GET_FOREIGN_ID, + session.getSessionID()); + + try { + AuthenticationSessionStoreage.storeSession(session); + } catch (MOADatabaseException e) { + throw new MOAIDException("session store error", null); + } + + // TODO[branch]: Foreign citizen; respond with CXSR for authblock signature, dataURL "/GetForeignID" + ServletUtils.writeCreateXMLSignatureRequest(resp, session, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); + + Logger.debug("Send CreateXMLSignatureRequest to BKU"); + } + } + catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("CertificateValidation has an interal Error.", e); + } + + + finally { + ConfigurationDBUtils.closeSession(); + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java index ec12643ec..c24e42b3a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java @@ -1,5 +1,7 @@ package at.gv.egovernment.moa.id.auth.tasks; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + import java.io.IOException; import java.util.Map; @@ -28,176 +30,179 @@ import at.gv.egovernment.moa.logging.Logger; import com.datentechnik.process_engine.api.ExecutionContext; +/** + * Verifies the identity link and prepares auth block signature if identity link provided, or triggers reading the subject's certificate if not provided.

+ * In detail: + *

    + *
  • Renames the moa session id.
  • + *
  • Parses the identity link retrieves as {@code InfoBoxReadResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
  • + *
  • Verifies the identity link.
  • + *
  • Creates the auth block to be signed.
  • + *
  • Updates moa session.
  • + *
  • Creates and returns a {@code CreateXMLSignatureRequest} via HttpServletResponse.
  • + *
+ * Expects: + *
    + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
  • + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE} containing a {@code InfoBoxReadResponse}.
  • + *
+ * Result: + *
    + *
  • Identity link put into moa session.
  • + *
  • Returns {@code CreateXMLSignatureRequest} via HttpServletResponse (for CCE).
  • + *
+ * Possible branches: + *
    + *
  • In case of foreign citizen or in case of mandate + *
      + *
    • Create {@code InfoBoxReadRequest} for reading the subjects certificate.
    • + *
    • Set DataURL {@code /VerifyCertificate}.
    • + *
    • Respond with {@code InfoBoxReadRequest}.
    • + *
    + *
  • + *
+ * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { - /** - * Verifies the identity link and responds with a new - * CreateXMLSignatureRequest or a new - * InfoboxReadRequest (in case of a foreign eID card). - *
- * Request parameters: - *
    - *
  • MOASessionID: ID of associated authentication session
  • - *
  • XMLResponse: <InfoboxReadResponse>
  • - *
- * Response: - *
    - *
  • Content type: "text/xml"
  • - *
  • Content: see return value of {@link AuthenticationServer#verifyIdentityLink}
  • - *
  • Error status: 500 - *
- * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) - */ @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws Exception { - + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet - Logger.debug("POST VerifyIdentityLink"); - - Map parameters; - String pendingRequestID = null; - - try - { - parameters = getParameters(req); - - } catch (Exception e) - { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - } - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings + Logger.debug("POST VerifyIdentityLink"); + + Map parameters; + String pendingRequestID = null; + + try { + parameters = getParameters(req); + } catch (Exception e) { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + } + String sessionID = req.getParameter(PARAM_SESSIONID); + + // escape parameter strings sessionID = StringEscapeUtils.escapeHtml(sessionID); - + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); - - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters); - - Logger.debug(createXMLSignatureRequestOrRedirect); - - - if (createXMLSignatureRequestOrRedirect == null) { - // no identity link found - - boolean useMandate = session.getUseMandate(); - if (useMandate) { - Logger.error("Online-Mandate Mode for foreign citizencs not supported."); - throw new AuthenticationException("auth.13", null); - } - // TODO[branch]: Foreign citizen; respond with IRR for certificates, dataURL = "/VerifyCertificate" - - try { - - Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); - - // create the InfoboxReadRequest to get the certificate - String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); - - // build dataurl (to the VerifyCertificateSerlvet) - String dataurl = - new DataURLBuilder().buildDataURL( - session.getAuthURL(), - REQ_VERIFY_CERTIFICATE, - session.getSessionID()); - - ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); - - - } - catch(Exception e) { - handleError(null, e, req, resp, pendingRequestID); - } - - } - else { - boolean useMandate = session.getUseMandate(); - - if (useMandate) { // Mandate modus - - // TODO[branch]: Mandate; respond with IRR for certificates, dataURL = "/VerifyCertificate" - - // read certificate and set dataurl to - Logger.debug("Send InfoboxReadRequest to BKU to get signer certificate."); - - - String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); - - // build dataurl (to the GetForeignIDSerlvet) - String dataurl = - new DataURLBuilder().buildDataURL( - session.getAuthURL(), - REQ_VERIFY_CERTIFICATE, - session.getSessionID()); - - //Logger.debug("ContentType set to: application/x-www-form-urlencoded (ServletUtils)"); - //ServletUtils.writeCreateXMLSignatureRequestURLEncoded(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); - - Logger.debug("ContentType set to: text/xml;charset=UTF-8 (ServletUtils)"); - ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); - - } - else { - Logger.info("Normal"); - - // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance() - .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, - authConf, oaParam); - - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink"); - } - } - + + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); + + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + // change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyIdentityLink(session, + parameters); + + Logger.debug(createXMLSignatureRequestOrRedirect); + + if (createXMLSignatureRequestOrRedirect == null) { + // no identity link found + + boolean useMandate = session.getUseMandate(); + if (useMandate) { + Logger.error("Online-Mandate Mode for foreign citizencs not supported."); + throw new AuthenticationException("auth.13", null); + } + // TODO[branch]: Foreign citizen; respond with IRR for certificates, dataURL = "/VerifyCertificate" + + try { + + Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); + + // create the InfoboxReadRequest to get the certificate + String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); + + // build dataurl (to the VerifyCertificateSerlvet) + String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, + session.getSessionID()); + + ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, + AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + + } catch (Exception e) { + handleError(null, e, req, resp, pendingRequestID); + } + + } else { + boolean useMandate = session.getUseMandate(); + + if (useMandate) { // Mandate modus + + // TODO[branch]: Mandate; respond with IRR for certificates, dataURL = "/VerifyCertificate" + + // read certificate and set dataurl to + Logger.debug("Send InfoboxReadRequest to BKU to get signer certificate."); + + String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); + + // build dataurl (to the GetForeignIDSerlvet) + String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, + session.getSessionID()); + + // Logger.debug("ContentType set to: application/x-www-form-urlencoded (ServletUtils)"); + // ServletUtils.writeCreateXMLSignatureRequestURLEncoded(resp, session, infoboxReadRequest, + // AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + + Logger.debug("ContentType set to: text/xml;charset=UTF-8 (ServletUtils)"); + ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, + AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + + } else { + Logger.info("Normal"); + + // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL + // "/VerifyAuthBlock" + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + + createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance() + .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); + + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, + createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, + "VerifyIdentityLink"); + } + } + try { AuthenticationSessionStoreage.storeSession(session); - + } catch (MOADatabaseException e) { Logger.info("No valid MOA session found. Authentification process is abourted."); throw new AuthenticationException("auth.20", null); } - } - catch (ParseException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("IdentityLinkValidation has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - - - + } catch (ParseException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("IdentityLinkValidation has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/loginFormFull.html b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/loginFormFull.html index 3eff06daf..5ae76ed96 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/loginFormFull.html +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/loginFormFull.html @@ -842,7 +842,7 @@ input { src="#CONTEXTPATH#/img/valid-html5-blue.png" alt="HTML5 ist valide!" /> CSS ist valide! -- cgit v1.2.3 From 3a00ce9f1f9589f1e97ecd78154f024146ef83d0 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Thu, 22 Jan 2015 15:18:51 +0100 Subject: Refactor VerifyIdentityLinkTask. - Prevent redundant code. - Store moa session before sending response. - Update javadoc for AuthenticationServer --- .../moa/id/auth/AuthenticationServer.java | 27 +++-- .../moa/id/auth/tasks/VerifyIdentityLinkTask.java | 134 ++++++++------------- 2 files changed, 61 insertions(+), 100 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index 0b4b6b4af..b412b9964 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -311,27 +311,28 @@ public class AuthenticationServer implements MOAIDAuthConstants { } /** - * Processes an <InfoboxReadResponse> sent by the - * security layer implementation.
+ * Processes an <InfoboxReadResponse> sent by the security layer implementation.
*
    *
  • Validates given <InfoboxReadResponse>
  • - *
  • Parses identity link enclosed in - * <InfoboxReadResponse>
  • + *
  • Parses identity link enclosed in <InfoboxReadResponse>
  • *
  • Verifies identity link by calling the MOA SP component
  • *
  • Checks certificate authority of identity link
  • *
  • Stores identity link in the session
  • *
  • Verifies all additional infoboxes returned from the BKU
  • *
  • Creates an authentication block to be signed by the user
  • - *
  • Creates and returns a <CreateXMLSignatureRequest> - * containg the authentication block, meant to be returned to the security - * layer implementation
  • + *
  • Creates and returns a <CreateXMLSignatureRequest> containg the authentication block, meant + * to be returned to the security layer implementation
  • *
- * - * @param sessionID ID of associated authentication session data - * @param infoboxReadResponseParameters The parameters from the response returned from the BKU - * including the <InfoboxReadResponse> - * @return String representation of the - * <CreateXMLSignatureRequest> + * + * @param sessionID + * ID of associated authentication session data + * @param infoboxReadResponseParameters + * The parameters from the response returned from the BKU including the + * <InfoboxReadResponse> + * @return String "found!" in case the identity link could be retrieved and successfully validated, {@code null} in + * case the identity link could not be retrieved (indicates that the card did not contain an identity link + * which might indicate a foreign identity). Note that failing to parse or failing to validate the identity + * link results in an Exception being thrown. * @throws BKUException */ public String verifyIdentityLink(AuthenticationSession session, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java index c24e42b3a..09dd9e1f7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java @@ -20,7 +20,6 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; @@ -76,6 +75,11 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { Logger.debug("POST VerifyIdentityLink"); + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); + Map parameters; String pendingRequestID = null; @@ -85,111 +89,67 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); throw new IOException(e.getMessage()); } - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); - resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); - resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); - + try { + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); + } + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); AuthenticationSession session = AuthenticationServer.getSession(sessionID); // change MOASessionID sessionID = AuthenticationSessionStoreage.changeSessionID(session); - String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyIdentityLink(session, - parameters); - - Logger.debug(createXMLSignatureRequestOrRedirect); - - if (createXMLSignatureRequestOrRedirect == null) { - // no identity link found - - boolean useMandate = session.getUseMandate(); - if (useMandate) { - Logger.error("Online-Mandate Mode for foreign citizencs not supported."); - throw new AuthenticationException("auth.13", null); - } - // TODO[branch]: Foreign citizen; respond with IRR for certificates, dataURL = "/VerifyCertificate" - - try { - - Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); - - // create the InfoboxReadRequest to get the certificate - String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); - - // build dataurl (to the VerifyCertificateSerlvet) - String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, - session.getSessionID()); + boolean identityLinkFound = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters) != null; + boolean useMandate = session.getUseMandate(); + + if (!identityLinkFound && useMandate) { + Logger.error("Online-Mandate Mode for foreign citizencs not supported."); + throw new AuthenticationException("auth.13", null); + } + + if (!identityLinkFound || useMandate) { + + // TODO[branch]: Foreign citizen or mandate mode; respond with IRR for certificates, dataURL = "/VerifyCertificate" + Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); - ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, - AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + // create the InfoboxReadRequest to get the certificate + String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); - } catch (Exception e) { - handleError(null, e, req, resp, pendingRequestID); - } + // build dataurl (to the VerifyCertificateSerlvet) + String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, + session.getSessionID()); + AuthenticationSessionStoreage.storeSession(session); + + ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, + AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); } else { - boolean useMandate = session.getUseMandate(); - - if (useMandate) { // Mandate modus - - // TODO[branch]: Mandate; respond with IRR for certificates, dataURL = "/VerifyCertificate" - - // read certificate and set dataurl to - Logger.debug("Send InfoboxReadRequest to BKU to get signer certificate."); - - String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); + + Logger.info("Normal"); - // build dataurl (to the GetForeignIDSerlvet) - String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, - session.getSessionID()); + // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" - // Logger.debug("ContentType set to: application/x-www-form-urlencoded (ServletUtils)"); - // ServletUtils.writeCreateXMLSignatureRequestURLEncoded(resp, session, infoboxReadRequest, - // AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); - Logger.debug("ContentType set to: text/xml;charset=UTF-8 (ServletUtils)"); - ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, - AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + String createXMLSignatureRequest = AuthenticationServer.getInstance() + .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); - } else { - Logger.info("Normal"); - - // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL - // "/VerifyAuthBlock" - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); - - createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance() - .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); - - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, - createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, - "VerifyIdentityLink"); - } - } - - try { AuthenticationSessionStoreage.storeSession(session); - - } catch (MOADatabaseException e) { - Logger.info("No valid MOA session found. Authentification process is abourted."); - throw new AuthenticationException("auth.20", null); + + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, + createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, + "VerifyIdentityLink"); } + } catch (ParseException ex) { handleError(null, ex, req, resp, pendingRequestID); -- cgit v1.2.3 From 745272fe66f04fee6976e6a187e308bb7a5987a1 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Fri, 23 Jan 2015 11:22:07 +0100 Subject: Add foreign identity process support (MOAID-61). - moa-id auth web.xml: Replace servlet mapping "/GetForeignID". - Fix some javadoc of AuthenticationServer. - Set GetForeignIDServlet deprecated. - Remove redundant code across several classes. - VerifyIdentityLinkTask: Separate identity link verification from subsequent (a) creation of CreateXMLSignatureRequest (ProcessIdentityLinkTask) and (b) creation of InfoBoxReadRequest (CertificateReadRequestTask). --- .../moa/id/auth/AuthenticationServer.java | 47 +----- .../moa/id/auth/servlet/GetForeignIDServlet.java | 6 + .../id/auth/servlet/VerifyCertificateServlet.java | 2 +- .../id/auth/servlet/VerifyIdentityLinkServlet.java | 6 +- .../moa/id/auth/tasks/AbstractAuthServletTask.java | 2 +- .../id/auth/tasks/CertificateReadRequestTask.java | 102 ++++++++++++ .../moa/id/auth/tasks/GetForeignIDTask.java | 183 +++++++++++++++++++++ .../moa/id/auth/tasks/ProcessIdentityLinkTask.java | 103 ++++++++++++ .../moa/id/auth/tasks/VerifyCertificateTask.java | 3 +- .../moa/id/auth/tasks/VerifyIdentityLinkTask.java | 80 +-------- .../gv/egovernment/moa/id/util/ServletUtils.java | 3 +- 11 files changed, 411 insertions(+), 126 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/ProcessIdentityLinkTask.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index b412b9964..fb67d078e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -1363,17 +1363,16 @@ public class AuthenticationServer implements MOAIDAuthConstants { /** * Gets the foreign authentication data.
*
    - *
  • Creates authentication data
  • + *
  • Creates authentication data
  • *
  • Creates a corresponding SAML artifact
  • *
  • Stores authentication data in the authentication data store indexed * by the SAML artifact
  • *
  • Deletes authentication session
  • - *
  • Returns the SAML artifact, encoded BASE64
  • + *
  • Returns the SAML artifact, encoded BASE64
  • *
* * @param sessionID session ID of the running authentication session - * @return SAML artifact needed for retrieving authentication data, encoded - * BASE64 + * @return String "new Session" */ public String getForeignAuthenticationData(AuthenticationSession session) throws AuthenticationException, BuildException, ParseException, @@ -1382,46 +1381,6 @@ public class AuthenticationServer implements MOAIDAuthConstants { if (session == null) throw new AuthenticationException("auth.10", new Object[]{ REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID}); - - // // post processing of the infoboxes - // Iterator iter = session.getInfoboxValidatorIterator(); - // boolean formpending = false; - // if (iter != null) { - // while (!formpending && iter.hasNext()) { - // Vector infoboxValidatorVector = (Vector) iter.next(); - // String identifier = (String) infoboxValidatorVector.get(0); - // String friendlyName = (String) infoboxValidatorVector.get(1); - // InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector - // .get(2); - // InfoboxValidationResult infoboxValidationResult = null; - // try { - // infoboxValidationResult = infoboxvalidator.validate(session - // .getIdentityLink().getSamlAssertion()); - // } catch (ValidateException e) { - // Logger.error("Error validating " + identifier + " infobox:" - // + e.getMessage()); - // throw new ValidateException("validator.44", - // new Object[]{friendlyName}); - // } - // if (!infoboxValidationResult.isValid()) { - // Logger.info("Validation of " + identifier - // + " infobox failed."); - // throw new ValidateException("validator.40", new Object[]{ - // friendlyName, - // infoboxValidationResult.getErrorMessage()}); - // } - // String form = infoboxvalidator.getForm(); - // if (ParepUtils.isEmpty(form)) { - // AddAdditionalSAMLAttributes( - // session, - // infoboxValidationResult.getExtendedSamlAttributes(), - // identifier, friendlyName); - // } else { - // return "Redirect to Input Processor"; - // } - // } - // } - VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponse(); X509Certificate cert = session.getSignerCertificate(); vsresp.setX509certificate(cert); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java index bbc704f22..f8b0dbdab 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java @@ -71,6 +71,7 @@ import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; +import at.gv.egovernment.moa.id.auth.tasks.GetForeignIDTask; import at.gv.egovernment.moa.id.client.SZRGWClientException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.moduls.ModulUtils; @@ -85,6 +86,7 @@ import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; * Servlet requested for getting the foreign eID * provided by the security layer implementation. * Utilizes the {@link AuthenticationServer}. + * @deprecated Use {@link GetForeignIDTask} instead. * */ public class GetForeignIDServlet extends AuthServlet { @@ -134,6 +136,10 @@ public class GetForeignIDServlet extends AuthServlet { Logger.debug("POST GetForeignIDServlet"); + if (System.currentTimeMillis() > 0) { + throw new IllegalStateException(getClass().getName() + " should not be called any more."); + } + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java index 36e219a97..77e401899 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java @@ -214,7 +214,7 @@ public class VerifyCertificateServlet extends AuthServlet { throw new MOAIDException("session store error", null); } - ServletUtils.writeCreateXMLSignatureRequest(resp, session, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); + ServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); Logger.debug("Send CreateXMLSignatureRequest to BKU"); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java index 3fcdfe150..e94273881 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java @@ -53,7 +53,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.lang.StringEscapeUtils; import at.gv.egovernment.moa.id.auth.AuthenticationServer; @@ -67,7 +66,6 @@ import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.tasks.VerifyIdentityLinkTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; @@ -207,7 +205,7 @@ public class VerifyIdentityLinkServlet extends AuthServlet { session.getSessionID()); - ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + ServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); } @@ -237,7 +235,7 @@ public class VerifyIdentityLinkServlet extends AuthServlet { //ServletUtils.writeCreateXMLSignatureRequestURLEncoded(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); Logger.debug("ContentType set to: text/xml;charset=UTF-8 (ServletUtils)"); - ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + ServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); } else { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java index d5b869777..7351933c1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java @@ -325,7 +325,7 @@ public abstract class AbstractAuthServletTask extends AbstractSpringWebSupported * @param resp * The HttpServletResponse. */ - private void setNoCachingHeaders(HttpServletResponse resp) { + public void setNoCachingHeaders(HttpServletResponse resp) { resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java new file mode 100644 index 000000000..da8a3d997 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java @@ -0,0 +1,102 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.BooleanUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; +import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; +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.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.

+ * In detail: + *

    + *
  • Renames the moa session id.
  • + *
  • Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.
  • + *
  • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code {/VerifyCertificate}
  • + *
+ * Expects: + *
    + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
  • + *
+ * Result: + *
    + *
  • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code {/VerifyCertificate}
  • + *
+ * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class CertificateReadRequestTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + // TODO[branch]: Foreign citizen or mandate mode; respond with IRR for certificates, dataURL = "/VerifyCertificate" + Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); + + setNoCachingHeaders(resp); + + String pendingRequestID = null; + + try { + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("CertificateReadRequestTask", PARAM_SESSIONID, "auth.12"); + } + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + boolean useMandate = session.getUseMandate(); + boolean identityLinkFound = BooleanUtils.isTrue((Boolean) executionContext.get("identityLinkFound")); + + if (!identityLinkFound && useMandate) { + Logger.error("Online-Mandate Mode for foreign citizencs not supported."); + throw new AuthenticationException("auth.13", null); + } + + // change MOASessionID + AuthenticationSessionStoreage.changeSessionID(session); + + // create the InfoboxReadRequest to get the certificate + String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); + + // build dataurl (to the VerifyCertificateSerlvet) + String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, + session.getSessionID()); + + ServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest, + AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + } finally { + ConfigurationDBUtils.closeSession(); + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java new file mode 100644 index 000000000..602ad527b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java @@ -0,0 +1,183 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.cert.CertificateException; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.transform.TransformerException; + +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.lang.StringEscapeUtils; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse; +import at.gv.egovernment.moa.id.auth.data.IdentityLink; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.ParseException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; +import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; +import at.gv.egovernment.moa.id.client.SZRGWClientException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Evaluates the {@code CreateXMLSignatureResponse}, extracts signature and certificate and asks the SZR Gateway for an identity link.

+ * In detail: + *

    + *
  • Renames the moa session id.
  • + *
  • Parses the CreateXMLSignatureResponse retrieved from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
  • + *
  • Extracts signature and signer certificate.
  • + *
  • Send request to SZR Gateway in order to get an identity link.
  • + *
  • Updates moa session (sets identity link, QAA level 4, authentication data and foreigner flag).
  • + *
  • Redirects back to {@code /dispatcher} in order to finalize authentication.
  • + *
+ * Expects: + *
    + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
  • + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
  • + *
+ * Result: + *
    + *
  • Identity link, QAA level 4 and foreigner flag put into moa session.
  • + *
  • Redirect to {@code /dispatcher}.
  • + *
+ * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class GetForeignIDTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + Logger.debug("POST GetForeignIDServlet"); + + setNoCachingHeaders(resp); + + Map parameters; + + try { + parameters = getParameters(req); + } catch (FileUploadException e) { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + } + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + String pendingRequestID = null; + String redirectURL = null; + AuthenticationSession session = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12"); + } + String xmlCreateXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE); + if (!ParamValidatorUtils.isValidXMLDocument(xmlCreateXMLSignatureResponse)) { + throw new WrongParametersException("GetForeignID", PARAM_XMLRESPONSE, "auth.12"); + } + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + session = AuthenticationServer.getSession(sessionID); + + // change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.debug(xmlCreateXMLSignatureResponse); + + CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse) + .parseResponseDsig(); + + try { + String serializedAssertion = DOMUtils.serializeNode(csresp.getDsigSignature()); + session.setAuthBlock(serializedAssertion); + + } catch (TransformerException e) { + throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); + + } catch (IOException e) { + throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); + + } + + Element signature = csresp.getDsigSignature(); + + try { + session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature)); + } catch (CertificateException e) { + Logger.error("Could not extract certificate from CreateXMLSignatureResponse"); + throw new MOAIDException("auth.14", null); + } + + // make SZR request to the identity link + CreateIdentityLinkResponse response = AuthenticationServer.getInstance().getIdentityLink(signature); + + if (null != response.getErrorResponse()) { + // TODO fix exception parameter + throw new SZRGWClientException("service.08", (String) response.getErrorResponse().getErrorCode(), + (String) response.getErrorResponse().getInfo()); + } else { + IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream( + response.getIdentityLink())); + IdentityLink identitylink = ilParser.parseIdentityLink(); + session.setIdentityLink(identitylink); + + // set QAA Level four in case of card authentifcation + session.setQAALevel(PVPConstants.STORK_QAA_1_4); + + AuthenticationServer.getInstance().getForeignAuthenticationData(session); + + // session is implicit stored in changeSessionID!!!! + String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID); + Logger.info("Daten angelegt zu MOASession " + newMOASessionID); + + redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), + newMOASessionID); + redirectURL = resp.encodeRedirectURL(redirectURL); + + // TODO[branch]: Final step back to /dispatcher + + try { + AuthenticationSessionStoreage.storeSession(session); + } catch (MOADatabaseException e) { + throw new MOAIDException("Session store error", null); + } + + resp.setContentType("text/html"); + resp.setStatus(302); + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + } + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("GetForeignIDServlet has an interal Error.", e); + + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/ProcessIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/ProcessIdentityLinkTask.java new file mode 100644 index 000000000..34ef9b134 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/ProcessIdentityLinkTask.java @@ -0,0 +1,103 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Creates {@code CreateXMLSignatureRequest} for auth block signature.

+ * In detail: + *

    + *
  • Renames the moa session id.
  • + *
  • Creates {@code CreateXMLSignatureRequest} for auth block signature.
  • + *
  • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
  • + *
+ * Expects: + *
    + *
  • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
  • + *
+ * Result: + *
    + *
  • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
  • + *
+ * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class ProcessIdentityLinkTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet + + Logger.debug("Process IdentityLink"); + + setNoCachingHeaders(resp); + + String pendingRequestID = null; + + try { + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); + } + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + // change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Normal"); + + // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + + String createXMLSignatureRequest = AuthenticationServer.getInstance() + .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); + + AuthenticationSessionStoreage.storeSession(session); + + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, + createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, + "VerifyIdentityLink"); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("IdentityLinkValidation has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java index 979e64888..ddea4c414 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java @@ -101,7 +101,6 @@ public class VerifyCertificateTask extends AbstractAuthServletTask { boolean useMandate = session.getUseMandate(); - if (useMandate) { // verify certificate for OrganWalter @@ -144,7 +143,7 @@ public class VerifyCertificateTask extends AbstractAuthServletTask { } // TODO[branch]: Foreign citizen; respond with CXSR for authblock signature, dataURL "/GetForeignID" - ServletUtils.writeCreateXMLSignatureRequest(resp, session, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); + ServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); Logger.debug("Send CreateXMLSignatureRequest to BKU"); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java index 09dd9e1f7..5b21cd29c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java @@ -12,33 +12,26 @@ import org.apache.commons.lang.StringEscapeUtils; import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; 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.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.ServletUtils; import at.gv.egovernment.moa.logging.Logger; import com.datentechnik.process_engine.api.ExecutionContext; /** - * Verifies the identity link and prepares auth block signature if identity link provided, or triggers reading the subject's certificate if not provided.

+ * Verifies the identity link.

* In detail: *

    *
  • Renames the moa session id.
  • - *
  • Parses the identity link retrieves as {@code InfoBoxReadResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
  • + *
  • Parses the identity link retrieved as {@code InfoBoxReadResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
  • *
  • Verifies the identity link.
  • - *
  • Creates the auth block to be signed.
  • *
  • Updates moa session.
  • - *
  • Creates and returns a {@code CreateXMLSignatureRequest} via HttpServletResponse.
  • + *
  • Puts boolean flag {@code identityLinkFound} into {@code ExecutionContext}.
  • *
* Expects: *
    @@ -48,17 +41,7 @@ import com.datentechnik.process_engine.api.ExecutionContext; * Result: *
      *
    • Identity link put into moa session.
    • - *
    • Returns {@code CreateXMLSignatureRequest} via HttpServletResponse (for CCE).
    • - *
    - * Possible branches: - *
      - *
    • In case of foreign citizen or in case of mandate - *
        - *
      • Create {@code InfoBoxReadRequest} for reading the subjects certificate.
      • - *
      • Set DataURL {@code /VerifyCertificate}.
      • - *
      • Respond with {@code InfoBoxReadRequest}.
      • - *
      - *
    • + *
    • Boolean flag {@code identityLinkFound} into {@code ExecutionContext}.
    • *
    * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. * @author tknall @@ -75,10 +58,7 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { Logger.debug("POST VerifyIdentityLink"); - resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); - resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); - resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); + setNoCachingHeaders(resp); Map parameters; String pendingRequestID = null; @@ -93,62 +73,18 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { try { String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - // check parameter if (!ParamValidatorUtils.isValidSessionID(sessionID)) { throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); } - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); AuthenticationSession session = AuthenticationServer.getSession(sessionID); - // change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - boolean identityLinkFound = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters) != null; - boolean useMandate = session.getUseMandate(); - - if (!identityLinkFound && useMandate) { - Logger.error("Online-Mandate Mode for foreign citizencs not supported."); - throw new AuthenticationException("auth.13", null); - } - - if (!identityLinkFound || useMandate) { - - // TODO[branch]: Foreign citizen or mandate mode; respond with IRR for certificates, dataURL = "/VerifyCertificate" - Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); - - // create the InfoboxReadRequest to get the certificate - String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); - - // build dataurl (to the VerifyCertificateSerlvet) - String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, - session.getSessionID()); - - AuthenticationSessionStoreage.storeSession(session); - - ServletUtils.writeCreateXMLSignatureRequest(resp, session, infoboxReadRequest, - AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); - } else { - - Logger.info("Normal"); - - // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); - - String createXMLSignatureRequest = AuthenticationServer.getInstance() - .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); - - AuthenticationSessionStoreage.storeSession(session); - - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, - createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, - "VerifyIdentityLink"); - } + AuthenticationSessionStoreage.storeSession(session); + + executionContext.put("identityLinkFound", identityLinkFound); } catch (ParseException ex) { handleError(null, ex, req, resp, pendingRequestID); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java index 56e59a4aa..3dbc0ab7b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java @@ -113,14 +113,13 @@ public class ServletUtils { * depending on the requests starting text. * * @param resp The httpServletResponse - * @param session The current AuthenticationSession * @param createXMLSignatureRequestOrRedirect The request * @param servletGoal The servlet to which the redirect should happen * @param servletName The servlet name for debug purposes * @throws MOAIDException * @throws IOException */ - public static void writeCreateXMLSignatureRequest(HttpServletResponse resp, AuthenticationSession session, String createXMLSignatureRequestOrRedirect, String servletGoal, String servletName, String dataURL) + public static void writeCreateXMLSignatureRequest(HttpServletResponse resp, String createXMLSignatureRequestOrRedirect, String servletGoal, String servletName, String dataURL) throws MOAIDException, IOException { -- cgit v1.2.3 From dcb6d398987af78f3e345f9e3577f2a1e581fdb9 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Mon, 26 Jan 2015 10:10:44 +0100 Subject: Perform refactoring. - Rename ProcessIdentityLinkTask to PrepareAuthBlockSignatureTask. --- .../auth/tasks/PrepareAuthBlockSignatureTask.java | 103 +++++++++++++++++++++ .../moa/id/auth/tasks/ProcessIdentityLinkTask.java | 103 --------------------- 2 files changed, 103 insertions(+), 103 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/ProcessIdentityLinkTask.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java new file mode 100644 index 000000000..30777198c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java @@ -0,0 +1,103 @@ +package at.gv.egovernment.moa.id.auth.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Creates {@code CreateXMLSignatureRequest} for auth block signature.

    + * In detail: + *

      + *
    • Renames the moa session id.
    • + *
    • Creates {@code CreateXMLSignatureRequest} for auth block signature.
    • + *
    • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
    • + *
    + * Expects: + *
      + *
    • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
    • + *
    + * Result: + *
      + *
    • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
    • + *
    + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. + * @author tknall + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class PrepareAuthBlockSignatureTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet + + Logger.debug("Process IdentityLink"); + + setNoCachingHeaders(resp); + + String pendingRequestID = null; + + try { + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); + } + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + // change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Normal"); + + // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + + String createXMLSignatureRequest = AuthenticationServer.getInstance() + .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); + + AuthenticationSessionStoreage.storeSession(session); + + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, + createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, + "VerifyIdentityLink"); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("IdentityLinkValidation has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/ProcessIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/ProcessIdentityLinkTask.java deleted file mode 100644 index 34ef9b134..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/ProcessIdentityLinkTask.java +++ /dev/null @@ -1,103 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * Creates {@code CreateXMLSignatureRequest} for auth block signature.

    - * In detail: - *

      - *
    • Renames the moa session id.
    • - *
    • Creates {@code CreateXMLSignatureRequest} for auth block signature.
    • - *
    • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
    • - *
    - * Expects: - *
      - *
    • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
    • - *
    - * Result: - *
      - *
    • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
    • - *
    - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. - * @author tknall - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class ProcessIdentityLinkTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet - - Logger.debug("Process IdentityLink"); - - setNoCachingHeaders(resp); - - String pendingRequestID = null; - - try { - - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); - } - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - // change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.info("Normal"); - - // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); - - String createXMLSignatureRequest = AuthenticationServer.getInstance() - .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); - - AuthenticationSessionStoreage.storeSession(session); - - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, - createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, - "VerifyIdentityLink"); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("IdentityLinkValidation has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} -- cgit v1.2.3 From 8982f3f9beda6d3ff6926bc2aa43942576ba31dc Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Mon, 26 Jan 2015 13:47:28 +0100 Subject: Fix Javadoc, remove disabled code. - Partly fix javadoc of AuthenticationServer. - Remove disabled code from AuthenticationServer. --- .../moa/id/auth/AuthenticationServer.java | 6 ++-- .../auth/tasks/VerifyAuthenticationBlockTask.java | 32 ++++------------------ 2 files changed, 8 insertions(+), 30 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index fb67d078e..c33e5c735 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -1096,14 +1096,14 @@ public class AuthenticationServer implements MOAIDAuthConstants { *
  • Stores authentication data in the authentication data store indexed * by the SAML artifact
  • *
  • Deletes authentication session
  • - *
  • Returns the SAML artifact, encoded BASE64
  • + *
  • Returns the SAML artifact, encoded BASE64
    New id of the authenticated MOA session or {@code null} in case of mandate mode (???)
  • *
* * @param sessionID session ID of the running authentication session * @param xmlCreateXMLSignatureReadResponse String representation of the * <CreateXMLSignatureResponse> - * @return SAML artifact needed for retrieving authentication data, encoded - * BASE64 + * @return SAML artifact needed for retrieving authentication data, encoded + * BASE64
New id of the authenticated MOA session or {@code null} in case of mandate mode (???) * @throws BKUException */ public String verifyAuthenticationBlock(AuthenticationSession session, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java index 24fea05c9..2bc0bb8ad 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java @@ -116,11 +116,9 @@ public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { //change MOASessionID sessionID = AuthenticationSessionStoreage.changeSessionID(session); - String samlArtifactBase64 = AuthenticationServer.getInstance().verifyAuthenticationBlock(session, createXMLSignatureResponse); + String authenticatedMOASessionId = AuthenticationServer.getInstance().verifyAuthenticationBlock(session, createXMLSignatureResponse); - - - if (samlArtifactBase64 == null) { + if (authenticatedMOASessionId == null) { //mandate Mode AuthConfigurationProvider authConf= AuthConfigurationProvider.getInstance(); @@ -156,11 +154,6 @@ public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { throw new AuthenticationException("config.21", new Object[] { GET_MIS_SESSIONID}); } -// String profilesArray[] = profiles.split(","); -// for(int i = 0; i < profilesArray.length; i++) { -// profilesArray[i] = profilesArray[i].trim(); -// } - String oaFriendlyName = oaParam.getFriendlyName(); String mandateReferenceValue = session.getMandateReferenceValue(); byte[] cert = session.getEncodedSignerCertificate(); @@ -212,24 +205,9 @@ public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { Logger.debug("REDIRECT TO: " + redirectURL); } else { - if (!samlArtifactBase64.equals("Redirect to Input Processor")) { - /*redirectURL = session.getOAURLRequested(); - if (!session.getBusinessService()) { - redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8")); - - } - redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); - redirectURL = resp.encodeRedirectURL(redirectURL);*/ - - // TODO[branch]: Final step back to /dispatcher - - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), samlArtifactBase64); - - } else { - // TODO[tlenz]: Should not be needed any more (respective code in AuthenticationServer has been disabled) - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, session.getSessionID()); - } + // TODO[branch]: Final step back to /dispatcher + redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), authenticatedMOASessionId); resp.setContentType("text/html"); resp.setStatus(302); -- cgit v1.2.3 From 92a879913faceb6f8392048768953846cf7a4e86 Mon Sep 17 00:00:00 2001 From: Gerwin Gsenger Date: Tue, 27 Jan 2015 16:18:00 +0100 Subject: initial version of ModuleRegistry and ModuleAuth --- .../id/moduls/modulregistration/AuthModule.java | 40 ++++++++++++++++++++++ .../modulregistration/ModuleRegistration.java | 29 ++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/AuthModule.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/ModuleRegistration.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/AuthModule.java new file mode 100644 index 000000000..6ee18c0ab --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/AuthModule.java @@ -0,0 +1,40 @@ +package at.gv.egovernment.moa.id.moduls.modulregistration; + +import com.datentechnik.process_engine.api.ExecutionContext; +import com.datentechnik.process_engine.model.ProcessDefinition; + +/** + * Defines the module capabilities. + */ +public interface AuthModule { + + /** + * Returns the priority of the module. The priority defines the place in the + * order of modules. The module with a highest priority is asked first, if + * it has a process which can do an authentication. + * + * @return the priority of the module. + */ + int getPriority(); + + /** + * Checks if the module has a process, which is able to do an authentication + * with the given {@link ExecutionContext}. + * + * @param context + * an ExecutionContext for a process. + * @return the process-ID of a process which is able to work with the given + * ExecutionContext, or {@code null}. + */ + String selectProcess(ExecutionContext context); + + /** + * Returns the an Array of {@link ProcessDefinition}s of the processes + * included in this module. + * + * @return an array of resource uris of the processes included in this + * module. + */ + String[] getProcessDefinitions(); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/ModuleRegistration.java new file mode 100644 index 000000000..fc352742d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/ModuleRegistration.java @@ -0,0 +1,29 @@ +package at.gv.egovernment.moa.id.moduls.modulregistration; + +import com.datentechnik.process_engine.api.ExecutionContext; + +public class ModuleRegistration { + + private static ModuleRegistration instance; + + public static ModuleRegistration getInstance() { + if (instance == null) { + instance = new ModuleRegistration(); + } + return instance; + } + + private ModuleRegistration() { + initRegistry(); + } + + private void initRegistry() { + // TODO: use ServiceLoader and Spring to find all modules + } + + public String selectProcess(ExecutionContext context) { + // TODO: implement + return null; + } + +} -- cgit v1.2.3 From b187c1470167335ad6142b9b8b730e106348a8f8 Mon Sep 17 00:00:00 2001 From: Gerwin Gsenger Date: Wed, 28 Jan 2015 10:31:33 +0100 Subject: implement ModuleRegistry, implement standard moaid process, start ModuleRegistry at moa-id startup, fix typo in package name --- .../id/moduls/moduleregistration/AuthModule.java | 40 ++++++ .../moduls/moduleregistration/AuthModuleImpl.java | 23 ++++ .../moduleregistration/ModuleRegistration.java | 140 +++++++++++++++++++++ .../id/moduls/modulregistration/AuthModule.java | 40 ------ .../modulregistration/ModuleRegistration.java | 29 ----- 5 files changed, 203 insertions(+), 69 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/AuthModule.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/ModuleRegistration.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java new file mode 100644 index 000000000..35273cd2b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java @@ -0,0 +1,40 @@ +package at.gv.egovernment.moa.id.moduls.moduleregistration; + +import com.datentechnik.process_engine.api.ExecutionContext; +import com.datentechnik.process_engine.model.ProcessDefinition; + +/** + * Defines the module capabilities. + */ +public interface AuthModule { + + /** + * Returns the priority of the module. The priority defines the place in the + * order of modules. The module with a highest priority is asked first, if + * it has a process which can do an authentication. + * + * @return the priority of the module. + */ + int getPriority(); + + /** + * Checks if the module has a process, which is able to perform an authentication + * with the given {@link ExecutionContext}. + * + * @param context + * an ExecutionContext for a process. + * @return the process-ID of a process which is able to work with the given + * ExecutionContext, or {@code null}. + */ + String selectProcess(ExecutionContext context); + + /** + * Returns the an Array of {@link ProcessDefinition}s of the processes + * included in this module. + * + * @return an array of resource uris of the processes included in this + * module. + */ + String[] getProcessDefinitions(); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java new file mode 100644 index 000000000..cbe5c5932 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java @@ -0,0 +1,23 @@ +package at.gv.egovernment.moa.id.moduls.moduleregistration; + +import com.datentechnik.process_engine.api.ExecutionContext; + +public class AuthModuleImpl implements AuthModule { + + @Override + public int getPriority() { + // neutral priority between Integer.MIN_VALUE and Integer.MAX_VALUE + return 0; + } + + @Override + public String selectProcess(ExecutionContext context) { + return context.get("ccc") == null ? "DefaultAuthentication" : null; + } + + @Override + public String[] getProcessDefinitions() { + return new String[] { "DefaultAuthentication" }; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java new file mode 100644 index 000000000..522e5c7eb --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java @@ -0,0 +1,140 @@ +package at.gv.egovernment.moa.id.moduls.moduleregistration; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.Resource; + +import com.datentechnik.process_engine.ProcessEngine; +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * This class handles registering modules. The modules are detected either with + * the ServiceLoader mechanism or via Spring. All detected modules are ranked + * according to their priority. + */ +public class ModuleRegistration { + + private static ModuleRegistration instance = new ModuleRegistration(); + + private List orderedModules = new ArrayList<>(); + + @Autowired + private ApplicationContext ctx; + + @Autowired + ProcessEngine processEngine; + + private Logger log = LoggerFactory.getLogger(getClass()); + + public static ModuleRegistration getInstance() { + return instance; + } + + private ModuleRegistration() { + } + + @PostConstruct + private void init() { + // load modules via the ServiceLoader + initServiceLoaderModules(); + + // load modules via Spring + initSpringModules(); + + // order modules according to their priority + orderModules(); + } + + /** + * Discovers modules which use the ServiceLoader mechanism. + */ + private void initServiceLoaderModules() { + log.debug("Discovering modules which use the ServiceLoader mechanism."); + ServiceLoader loader = ServiceLoader.load(AuthModule.class); + Iterator modules = loader.iterator(); + while (modules.hasNext()) { + AuthModule module = modules.next(); + registerResourceUris(module); + orderedModules.add(module); + } + } + + /** + * Discovers modules which use Spring. + */ + private void initSpringModules() { + log.debug("Discovering Spring modules."); + Map modules = ctx.getBeansOfType(AuthModule.class); + for (AuthModule module : modules.values()) { + registerResourceUris(module); + orderedModules.add(module); + } + } + + /** + * Registers the resource uris for the module. + * + * @param module + * the module. + */ + private void registerResourceUris(AuthModule module) { + for (String uri : module.getProcessDefinitions()) { + Resource resource = ctx.getResource(uri); + if (resource.exists()) { + log.debug("Registering process definition resource url: '{}'.", resource); + // TODO: register resource with the process engine + // processEngine.registerResourceUri(resource); + } else { + log.info("Resource url: '{}' does NOT exist.", resource); + } + } + } + + /** + * Order the modules in descending order according to their priority. + */ + private void orderModules() { + Collections.sort(orderedModules, new Comparator() { + @Override + public int compare(AuthModule thisAuthModule, AuthModule otherAuthModule) { + int thisOrder = thisAuthModule.getPriority(); + int otherOrder = otherAuthModule.getPriority(); + return (thisOrder < otherOrder ? -1 : (thisOrder == otherOrder ? 0 : 1)); + } + }); + log.debug("Modules are ordered in descending order, according to their priority."); + } + + /** + * Returns the process id of the first process, in the highest ranked + * module, which is able to work with the given execution context. + * + * @param context + * the {@link ExecutionContext}. + * @return the process id or {@code null} + */ + public String selectProcess(ExecutionContext context) { + for (AuthModule module : orderedModules) { + String id = module.selectProcess(context); + if (StringUtils.isNotEmpty(id)) { + log.debug("Process with id '{}' selected, for context '{}'.", id, context); + return id; + } + } + log.info("No process is able to handle context '{}'.", context); + return null; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/AuthModule.java deleted file mode 100644 index 6ee18c0ab..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/AuthModule.java +++ /dev/null @@ -1,40 +0,0 @@ -package at.gv.egovernment.moa.id.moduls.modulregistration; - -import com.datentechnik.process_engine.api.ExecutionContext; -import com.datentechnik.process_engine.model.ProcessDefinition; - -/** - * Defines the module capabilities. - */ -public interface AuthModule { - - /** - * Returns the priority of the module. The priority defines the place in the - * order of modules. The module with a highest priority is asked first, if - * it has a process which can do an authentication. - * - * @return the priority of the module. - */ - int getPriority(); - - /** - * Checks if the module has a process, which is able to do an authentication - * with the given {@link ExecutionContext}. - * - * @param context - * an ExecutionContext for a process. - * @return the process-ID of a process which is able to work with the given - * ExecutionContext, or {@code null}. - */ - String selectProcess(ExecutionContext context); - - /** - * Returns the an Array of {@link ProcessDefinition}s of the processes - * included in this module. - * - * @return an array of resource uris of the processes included in this - * module. - */ - String[] getProcessDefinitions(); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/ModuleRegistration.java deleted file mode 100644 index fc352742d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/modulregistration/ModuleRegistration.java +++ /dev/null @@ -1,29 +0,0 @@ -package at.gv.egovernment.moa.id.moduls.modulregistration; - -import com.datentechnik.process_engine.api.ExecutionContext; - -public class ModuleRegistration { - - private static ModuleRegistration instance; - - public static ModuleRegistration getInstance() { - if (instance == null) { - instance = new ModuleRegistration(); - } - return instance; - } - - private ModuleRegistration() { - initRegistry(); - } - - private void initRegistry() { - // TODO: use ServiceLoader and Spring to find all modules - } - - public String selectProcess(ExecutionContext context) { - // TODO: implement - return null; - } - -} -- cgit v1.2.3 From aa216fc322265515a67e5218e33700e95b7788d3 Mon Sep 17 00:00:00 2001 From: Christian Wagner Date: Wed, 28 Jan 2015 11:08:26 +0100 Subject: add automated process selection --- .../moa/id/moduls/AuthenticationManager.java | 34 ++++++++++++++-------- .../moduleregistration/ModuleRegistration.java | 16 +++++++--- 2 files changed, 34 insertions(+), 16 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 0c481d94e..1a0c11aa1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -76,6 +76,7 @@ import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.SLOInformationContainer; import at.gv.egovernment.moa.id.data.SLOInformationImpl; +import at.gv.egovernment.moa.id.moduls.moduleregistration.ModuleRegistration; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; @@ -94,9 +95,11 @@ import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +import com.datentechnik.process_engine.ExecutionContextImpl; import com.datentechnik.process_engine.ProcessEngine; import com.datentechnik.process_engine.ProcessExecutionException; import com.datentechnik.process_engine.ProcessInstance; +import com.datentechnik.process_engine.api.ExecutionContext; public class AuthenticationManager implements MOAIDAuthConstants { @@ -544,13 +547,26 @@ public class AuthenticationManager implements MOAIDAuthConstants { Logger.info("Start Authentication Module: " + moasession.getModul() + " Action: " + moasession.getAction()); - + // create execution context + ExecutionContext executionContext = new ExecutionContextImpl(); + executionContext.put("ccc", moasession.getCcc()); + executionContext.put("useMandate", moasession.getUseMandate()); + executionContext.put("bkuURL", moasession.getBkuURL()); + executionContext.put(PARAM_SESSIONID, moasession.getSessionID()); + // create process instance - // TODO[MOAID-49]: Automatically selection of process - ProcessInstance pi = processEngine.createProcessInstance("DefaultAuthentication"); - // keep process instance id in moa session - moasession.setProcessInstanceId(pi.getId()); - + String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); + + if (processDefinitionId == null) { + Logger.warn("No suitable process found for SessionID " + moasession.getSessionID() ); + throw new MOAIDException("process.02",new Object[] { + moasession.getSessionID()}); + } + + ProcessInstance pi = processEngine.createProcessInstance(processDefinitionId, executionContext); + // keep process instance id in moa session + moasession.setProcessInstanceId(pi.getId()); + // make sure moa session has been persisted before running the process try { AuthenticationSessionStoreage.storeSession(moasession); @@ -560,12 +576,6 @@ public class AuthenticationManager implements MOAIDAuthConstants { moasession.getSessionID()}); } - // set execution context - pi.getExecutionContext().put("ccc", moasession.getCcc()); - pi.getExecutionContext().put("useMandate", moasession.getUseMandate()); - pi.getExecutionContext().put("bkuURL", moasession.getBkuURL()); - pi.getExecutionContext().put(PARAM_SESSIONID, moasession.getSessionID()); - // start process processEngine.start(pi); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java index 522e5c7eb..b90e0d94f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java @@ -1,5 +1,7 @@ package at.gv.egovernment.moa.id.moduls.moduleregistration; +import java.io.IOException; +import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -17,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; +import com.datentechnik.process_engine.ProcessDefinitionParserException; import com.datentechnik.process_engine.ProcessEngine; import com.datentechnik.process_engine.api.ExecutionContext; @@ -94,11 +97,16 @@ public class ModuleRegistration { for (String uri : module.getProcessDefinitions()) { Resource resource = ctx.getResource(uri); if (resource.exists()) { - log.debug("Registering process definition resource url: '{}'.", resource); - // TODO: register resource with the process engine - // processEngine.registerResourceUri(resource); + log.debug("Registering process definition resource uri: '{}'.", resource); + try (InputStream processDefinitionInputStream = resource.getInputStream()) { + processEngine.registerProcessDefinition(processDefinitionInputStream); + } catch (IOException e) { + log.info("Resource uri: '{}' could NOT be read.", resource); + } catch (ProcessDefinitionParserException e) { + log.warn("Error while parsing process definition in '{}'", resource); + } } else { - log.info("Resource url: '{}' does NOT exist.", resource); + log.info("Resource uri: '{}' does NOT exist.", resource); } } } -- cgit v1.2.3 From 7ae32988fcf9e4407b4bcae7831772338da55a8f Mon Sep 17 00:00:00 2001 From: Gerwin Gsenger Date: Wed, 28 Jan 2015 11:52:10 +0100 Subject: switch to automated process selection --- .../servlet/GenerateIFrameTemplateServlet.java | 29 +++++++++++++++------- 1 file changed, 20 insertions(+), 9 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index 430936e97..6e817e2a5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -41,12 +41,15 @@ import at.gv.egovernment.moa.id.commons.db.dao.config.TemplateType; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.moduleregistration.ModuleRegistration; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; +import com.datentechnik.process_engine.ExecutionContextImpl; import com.datentechnik.process_engine.ProcessInstance; +import com.datentechnik.process_engine.api.ExecutionContext; public class GenerateIFrameTemplateServlet extends AuthServlet { @@ -144,16 +147,24 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { moasession.getAction(), req); } - + + ExecutionContext ec = new ExecutionContextImpl(); + // set execution context + ec.put("ccc", moasession.getCcc()); + ec.put("useMandate", moasession.getUseMandate()); + ec.put("bkuURL", moasession.getBkuURL()); + // select and create process instance - // TODO[MOAID-49]: Automatically selection of process - ProcessInstance pi = getProcessEngine().createProcessInstance("DefaultAuthentication"); - // keep process instance id in moa session - moasession.setProcessInstanceId(pi.getId()); - // set execution context - pi.getExecutionContext().put("ccc", moasession.getCcc()); - pi.getExecutionContext().put("useMandate", moasession.getUseMandate()); - pi.getExecutionContext().put("bkuURL", moasession.getBkuURL()); + String processDefinitionId = ModuleRegistration.getInstance().selectProcess(ec); + ProcessInstance pi = getProcessEngine().createProcessInstance(processDefinitionId, ec); + + if (processDefinitionId == null) { + Logger.warn("No suitable process found for SessionID " + moasession.getSessionID()); + throw new MOAIDException("process.02", new Object[] { moasession.getSessionID() }); + } + + // keep process instance id in moa session + moasession.setProcessInstanceId(pi.getId()); // make sure moa session has been persisted before running the process try { -- cgit v1.2.3 From d45b41a740a6267c78a6ea27b7617c3d317db837 Mon Sep 17 00:00:00 2001 From: Christian Wagner Date: Thu, 29 Jan 2015 08:18:00 +0100 Subject: integrate process engine from project 'dti-process-engine' - INCOMPLETE! - commit neccessary in order to avoid blocking the development process additional small fix due to earlier package renaming --- .../moa/id/process/ExecutionContextImpl.java | 79 ++++++ .../process/ExpressionEvaluationContextImpl.java | 44 +++ .../moa/id/process/ProcessDefinitionParser.java | 224 +++++++++++++++ .../process/ProcessDefinitionParserException.java | 35 +++ .../egovernment/moa/id/process/ProcessEngine.java | 113 ++++++++ .../moa/id/process/ProcessEngineImpl.java | 304 +++++++++++++++++++++ .../moa/id/process/ProcessExecutionException.java | 36 +++ .../moa/id/process/ProcessInstance.java | 166 +++++++++++ .../moa/id/process/ProcessInstanceState.java | 30 ++ .../moa/id/process/api/ExecutionContext.java | 63 +++++ .../process/api/ExpressionEvaluationContext.java | 23 ++ .../moa/id/process/api/ExpressionEvaluator.java | 25 ++ .../at/gv/egovernment/moa/id/process/api/Task.java | 21 ++ .../egovernment/moa/id/process/model/EndEvent.java | 42 +++ .../moa/id/process/model/ProcessDefinition.java | 158 +++++++++++ .../moa/id/process/model/ProcessNode.java | 69 +++++ .../moa/id/process/model/StartEvent.java | 45 +++ .../egovernment/moa/id/process/model/TaskInfo.java | 94 +++++++ .../moa/id/process/model/Transition.java | 136 +++++++++ .../process/spring/SpringExpressionEvaluator.java | 61 +++++ .../springweb/AbstractAuthSourceServlet.java | 116 ++++++++ .../springweb/AbstractSpringWebSupportedTask.java | 73 +++++ .../moa/id/process/support/SecureRandomHolder.java | 35 +++ 23 files changed, 1992 insertions(+) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParserException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessExecutionException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstanceState.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExecutionContext.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluator.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/EndEvent.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/StartEvent.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/support/SecureRandomHolder.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java new file mode 100644 index 000000000..87ee57a24 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java @@ -0,0 +1,79 @@ +package at.gv.egovernment.moa.id.process; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * ExecutionContext implementation, related to a certain process instance. + * + * @author tknall + * + */ +public class ExecutionContextImpl implements ExecutionContext { + + private static final long serialVersionUID = 1L; + + private Map ctxData = Collections.synchronizedMap(new HashMap()); + + private String processInstanceId; + + /** + * Creates a new instance. + */ + public ExecutionContextImpl() { + } + + /** + * Creates a new instance and associated it with a certain process instance. + */ + public ExecutionContextImpl(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @Override + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + @Override + public String getProcessInstanceId() { + return processInstanceId; + } + + @Override + public Serializable get(String key) { + return ctxData.get(key); + } + + @Override + public Serializable remove(String key) { + return ctxData.remove(key); + } + + @Override + public void put(String key, Serializable object) { + ctxData.put(key, object); + } + + @Override + public Set keySet() { + return Collections.unmodifiableSet(ctxData.keySet()); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ExecutionContextImpl ["); + builder.append("id=").append(processInstanceId); + builder.append(", variables="); + builder.append(ctxData.keySet()); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java new file mode 100644 index 000000000..acc10449f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java @@ -0,0 +1,44 @@ +package at.gv.egovernment.moa.id.process; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.datentechnik.process_engine.api.ExecutionContext; +import com.datentechnik.process_engine.api.ExpressionEvaluationContext; + +/** + * Context implementation used for expression evaluation only. + * + * @author tknall + * + */ +public class ExpressionEvaluationContextImpl implements ExpressionEvaluationContext { + + private static final long serialVersionUID = 1L; + + private Map ctxData; + + /** + * Creates a new instance and initializes it with data from a given process instance. + * + * @param processInstance + * The process instance. + */ + ExpressionEvaluationContextImpl(ProcessInstance processInstance) { + ExecutionContext executionContext = processInstance.getExecutionContext(); + Set keys = executionContext.keySet(); + ctxData = Collections.synchronizedMap(new HashMap(keys.size())); + for (String key : keys) { + ctxData.put(key, executionContext.get(key)); + } + } + + @Override + public Map getCtx() { + return Collections.unmodifiableMap(ctxData); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java new file mode 100644 index 000000000..b38bb7aa0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java @@ -0,0 +1,224 @@ +package at.gv.egovernment.moa.id.process; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; + +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.events.Attribute; +import javax.xml.stream.events.StartElement; +import javax.xml.stream.events.XMLEvent; +import javax.xml.stream.util.EventReaderDelegate; +import javax.xml.transform.stax.StAXSource; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Validator; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.SAXException; + +import com.datentechnik.process_engine.model.EndEvent; +import com.datentechnik.process_engine.model.ProcessDefinition; +import com.datentechnik.process_engine.model.ProcessNode; +import com.datentechnik.process_engine.model.StartEvent; +import com.datentechnik.process_engine.model.TaskInfo; +import com.datentechnik.process_engine.model.Transition; + +/** + * Parses an XML representation of a process definition as defined by the respective XML schema. + *

transitionElements = new ArrayList<>(); + final List startEvents = new ArrayList<>(); + + reader = new EventReaderDelegate(reader) { + + @Override + public XMLEvent nextEvent() throws XMLStreamException { + XMLEvent event = super.nextEvent(); + + switch (event.getEventType()) { + case XMLStreamConstants.START_ELEMENT: + StartElement element = event.asStartElement(); + QName qname = element.getName(); + + if (NS.equals(qname.getNamespaceURI())) { + log.trace("Found process description element '{}'.", qname.getLocalPart()); + Attribute id = element.getAttributeByName(new QName("id")); + + switch (qname.getLocalPart()) { + case "ProcessDefinition": + if (id != null) { + pd.setId(id.getValue()); + } + break; + case "StartEvent": + StartEvent startEvent = new StartEvent(); + if (id != null) { + startEvent.setId(id.getValue()); + } + startEvents.add(startEvent); + break; + case "EndEvent": + EndEvent endEvent = new EndEvent(); + if (id != null) { + endEvent.setId(id.getValue()); + pd.getEndEvents().put(id.getValue(), endEvent); + } + break; + case "Transition": + transitionElements.add(element); + break; + case "Task": + TaskInfo taskInfo = new TaskInfo(); + if (id != null) { + taskInfo.setId(id.getValue()); + pd.getTaskInfos().put(id.getValue(), taskInfo); + } + Attribute async = element.getAttributeByName(new QName("async")); + if (async != null) { + taskInfo.setAsync(Boolean.valueOf(async.getValue())); + } + Attribute implementingClass = element.getAttributeByName(new QName("class")); + if (implementingClass != null) { + taskInfo.setTaskImplementingClass(implementingClass.getValue()); + } + break; + } + + } + + break; + } + + return event; + } + + }; + + // validator is not thread-safe + Validator validator = LazyProcessDefinitionSchemaHolder.PD_SCHEMA_INSTANCE.newValidator(); + validator.validate(new StAXSource(reader)); + log.trace("Process definition successfully schema validated."); + + // perform some basic checks + log.trace("Building model and performing some plausibility checks."); + if (startEvents.size() != 1) { + throw new ProcessDefinitionParserException("A ProcessDefinition must contain exactly one single StartEvent."); + } + pd.setStartEvent(startEvents.get(0)); + + // link transitions + Iterator transitions = transitionElements.iterator(); + while (transitions.hasNext()) { + StartElement element = transitions.next(); + Transition transition = new Transition(); + Attribute id = element.getAttributeByName(new QName("id")); + if (id != null) { + transition.setId(id.getValue()); + } + Attribute conditionExpression = element.getAttributeByName(new QName("conditionExpression")); + if (conditionExpression != null) { + transition.setConditionExpression(conditionExpression.getValue()); + } + Attribute from = element.getAttributeByName(new QName("from")); + if (from != null) { + ProcessNode fromNode = pd.getProcessNode(from.getValue()); + if (fromNode == null) { + throw new ProcessDefinitionParserException("Transition's 'from'-attribute refers to a non-existing event or task '" + from.getValue() + '.'); + } + if (fromNode instanceof EndEvent) { + throw new ProcessDefinitionParserException("Transition cannot start from end event."); + } + transition.setFrom(fromNode); + fromNode.getOutgoingTransitions().add(transition); + } + Attribute to = element.getAttributeByName(new QName("to")); + if (to != null) { + ProcessNode toNode = pd.getProcessNode(to.getValue()); + if (toNode == null) { + throw new ProcessDefinitionParserException("Transition's 'to'-attribute refers to a non-existing event or task '" + to.getValue() + '.'); + } + transition.setTo(toNode); + toNode.getIncomingTransitions().add(transition); + } + if (transition.getConditionExpression() == null && Objects.equals(transition.getFrom(), transition.getTo())) { + throw new ProcessDefinitionParserException("Transition's 'from' equals its 'to'. Since no 'conditionExpression' has been set this will cause a loop."); + } + } + log.debug("Process definition '{}' successfully parsed.", pd.getId()); + return pd; + + } catch (ProcessDefinitionParserException e) { + throw e; + } catch (XMLStreamException|IOException e) { + throw new ProcessDefinitionParserException("Unable to read process definition from inputstream.", e); + } catch (SAXException e) { + throw new ProcessDefinitionParserException("Schema validation of process description failed.", e); + } catch (Exception e) { + throw new ProcessDefinitionParserException("Internal error creating process definition from inputstream.", e); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (XMLStreamException e) { + // error freeing resources + } + } + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParserException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParserException.java new file mode 100644 index 000000000..0c214750d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParserException.java @@ -0,0 +1,35 @@ +package at.gv.egovernment.moa.id.process; + +/** + * Exception thrown in case of error parsing a process definition. + * + * @author tknall + * + */ +public class ProcessDefinitionParserException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * Creates a new parser exception providing a {@code message} describing the reason and the {@code cause}. + * + * @param message + * The message. + * @param cause + * The cause. + */ + public ProcessDefinitionParserException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a new parser exception providing a {@code message} describing the reason. + * + * @param message + * The message. + */ + public ProcessDefinitionParserException(String message) { + super(message); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java new file mode 100644 index 000000000..b4135ee41 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java @@ -0,0 +1,113 @@ +package at.gv.egovernment.moa.id.process; + + +import java.io.InputStream; +import java.io.Serializable; + +import com.datentechnik.process_engine.api.ExecutionContext; +import com.datentechnik.process_engine.model.ProcessDefinition; + +/** + * Process engine providing means for starting and resuming processes. + * + * @author tknall + */ +public interface ProcessEngine { + + /** + * Registers a new process definition. Note that existing definitions with the same identifier will be replaced. + * + * @param processDefinition + * The process definition to be registered. + */ + void registerProcessDefinition(ProcessDefinition processDefinition); + + /** + * Registers a new process definition given as {@link InputStream}. Note that existing definitions with the same identifier will be replaced. + * + * @param processDefinitionInputStream The input stream to the definition to be registered. + * @throws ProcessDefinitionParserException Thrown in case of an error parsing the process definition. + */ + void registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException; + + /** + * Creates a process instance according to the referenced process definition. + *

+ * Note that the method returns a process instance which will be needed in order to start a process or to continue + * process execution after asynchronous task execution (refer to {@link #start(ProcessInstance)} and + * {@link #signal(ProcessInstance)} for further information). + * + * @param processDefinitionId + * The identifier of the respective process definition. + * @param executionContext The execution context (may be {@code null}). + * @return The newly created process instance (never {@code null}). + * @throws ProcessExecutionException + * Thrown in case of error, e.g. when a {@code processDefinitionId} is referenced that does not exist. + */ + ProcessInstance createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException; + + /** + * Creates a process instance according to the referenced process definition. + *

+ * Note that the method returns a process instance which will be needed in order to start a process or to continue + * process execution after asynchronous task execution (refer to {@link #start(ProcessInstance)} and + * {@link #signal(ProcessInstance)} for further information). + * + * @param processDefinitionId + * The identifier of the respective process definition. + * @return The newly created process instance (never {@code null}). + * @throws ProcessExecutionException + * Thrown in case of error, e.g. when a {@code processDefinitionId} is referenced that does not exist. + */ + ProcessInstance createProcessInstance(String processDefinitionId) throws ProcessExecutionException; + + /** + * Returns the process instance with a given {@code processInstanceId}. + * + * @param processInstanceId + * The process instance id. + * @return The process instance (never {@code null}). + * @throws IllegalArgumentException + * In case the process instance does not/no longer exist. + */ + ProcessInstance getProcessInstance(String processInstanceId); + + /** + * Starts the process using the given {@code processInstance}. + * + * @param processInstance + * The process instance. + * @throws ProcessExecutionException + * Thrown in case of error. + */ + void start(ProcessInstance processInstance) throws ProcessExecutionException; + + /** + * Resumes process execution after an asynchronous task has been executed. + * + * @param processInstance + * The process instance. + * @throws ProcessExecutionException + * Thrown in case of error. + */ + void signal(ProcessInstance processInstance) throws ProcessExecutionException; + + /** + * Performs cleanup, removing all process instances that have not been used for a certain time. + * + * @see #setProcessInstanceMaxIdleTimeSeconds(long) + */ + void cleanup(); + + /** + * Returns the first process instance with a process context containing some {@code value} stored under key {@code key}. + * + * @param key + * The key. + * @param value + * The value that needs to match. + * @return The process instance or {@code null} in case no process instance was found. + */ + ProcessInstance findProcessInstanceWith(String key, Serializable value); + +} \ No newline at end of file diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java new file mode 100644 index 000000000..8f9d73b3d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java @@ -0,0 +1,304 @@ +package at.gv.egovernment.moa.id.process; + +import java.io.InputStream; +import java.io.Serializable; +import java.util.Date; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.Predicate; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +import com.datentechnik.process_engine.api.ExecutionContext; +import com.datentechnik.process_engine.api.ExpressionEvaluationContext; +import com.datentechnik.process_engine.api.ExpressionEvaluator; +import com.datentechnik.process_engine.api.Task; +import com.datentechnik.process_engine.model.EndEvent; +import com.datentechnik.process_engine.model.ProcessDefinition; +import com.datentechnik.process_engine.model.ProcessNode; +import com.datentechnik.process_engine.model.StartEvent; +import com.datentechnik.process_engine.model.TaskInfo; +import com.datentechnik.process_engine.model.Transition; + +/** + * Process engine implementation allowing starting and continuing processes as well as providing means for cleanup actions. + * @author tknall + * + */ +public class ProcessEngineImpl implements ProcessEngine { + + private Logger log = LoggerFactory.getLogger(getClass()); + + private ProcessDefinitionParser pdp = new ProcessDefinitionParser(); + + private Map processDefinitions = new ConcurrentHashMap(); + private Map processInstances = new ConcurrentHashMap(); + + private final static String MDC_CTX_PI_NAME = "processInstanceId"; + private final static String MDC_CTX_TASK_NAME = "taskId"; + + private static final long DEFAULT_PROCESS_INSTANCE_MAX_AGE_SECONDS = 3600; + private long processInstanceIdleTimeSeconds = DEFAULT_PROCESS_INSTANCE_MAX_AGE_SECONDS; + private ExpressionEvaluator transitionConditionExpressionEvaluator; + + @Override + public void registerProcessDefinition(ProcessDefinition processDefinition) { + log.info("Registering process definition '{}'.", processDefinition.getId()); + processDefinitions.put(processDefinition.getId(), processDefinition); + } + + @Override + public void registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException{ + registerProcessDefinition(pdp.parse(processDefinitionInputStream)); + } + + /** + * Sets the process definitions. + * + * @param processDefinitions + * The process definitions. + * @throws IllegalArgumentException + * In case the process definitions contain definitions with the same identifier. + */ + public void setProcessDefinitions(Iterable processDefinitions) { + this.processDefinitions.clear(); + for (ProcessDefinition pd : processDefinitions) { + if (this.processDefinitions.containsKey(pd.getId())) { + throw new IllegalArgumentException("Duplicate process definition identifier '" + pd.getId() + "'."); + } + registerProcessDefinition(pd); + } + } + + /** + * Defines the time frame in seconds an idle process instance will be managed by the process engine. A process + * instance with an idle time larger than the given time will be removed. + *

+ * Note that {@link #cleanup()} needs to be called in order to remove expired process instances. + * + * @param processInstanceMaxIdleTimeSeconds + * The maximum idle time in seconds. + */ + public void setProcessInstanceMaxIdleTimeSeconds(long processInstanceMaxIdleTimeSeconds) { + this.processInstanceIdleTimeSeconds = processInstanceMaxIdleTimeSeconds; + } + + /** + * Sets an expression evaluator that should be used to process transition condition expressions. + * @param transitionConditionExpressionEvaluator The expression evaluator. + */ + public void setTransitionConditionExpressionEvaluator( + ExpressionEvaluator transitionConditionExpressionEvaluator) { + this.transitionConditionExpressionEvaluator = transitionConditionExpressionEvaluator; + } + + + @Override + public ProcessInstance createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException { + // look for respective process definition + ProcessDefinition pd = processDefinitions.get(processDefinitionId); + if (pd == null) { + throw new ProcessExecutionException("Unable to find process definition for process '" + processDefinitionId + "'."); + } + // create and keep process instance + ProcessInstance pi = new ProcessInstance(pd, executionContext); + log.info("Creating process instance from process definition '{}': {}", processDefinitionId, pi.getId()); + processInstances.put(pi.getId(), pi); + return pi; + } + + @Override + public ProcessInstance createProcessInstance(String processDefinitionId) throws ProcessExecutionException { + return createProcessInstance(processDefinitionId, null); + } + + @Override + public void start(ProcessInstance pi) throws ProcessExecutionException { + MDC.put(MDC_CTX_PI_NAME, pi.getId()); + try { + if (!ProcessInstanceState.NOT_STARTED.equals(pi.getState())) { + throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has already been started (current state is " + pi.getState() + ")."); + } + log.info("Starting process instance '{}'.", pi.getId()); + // execute process + pi.setState(ProcessInstanceState.STARTED); + execute(pi); + } finally { + MDC.remove(MDC_CTX_PI_NAME); + } + } + + @Override + public void signal(ProcessInstance pi) throws ProcessExecutionException { + MDC.put(MDC_CTX_PI_NAME, pi.getId()); + try { + if (!ProcessInstanceState.SUSPENDED.equals(pi.getState())) { + throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has not been suspended (current state is " + pi.getState() + ")."); + } + log.info("Waking up process instance '{}'.", pi.getId()); + pi.setState(ProcessInstanceState.STARTED); + execute(pi); + } finally { + MDC.remove(MDC_CTX_PI_NAME); + } + } + + @Override + public synchronized void cleanup() { + log.trace("Cleanup job started."); + Iterator> it = processInstances.entrySet().iterator(); + while (it.hasNext()) { + Entry entry = it.next(); + ProcessInstance pi = entry.getValue(); + log.trace("Checking process instance {}.", pi); + long ageMillis = new Date().getTime() - pi.getLru().getTime(); + if (ageMillis > processInstanceIdleTimeSeconds * 1000) { + log.info("Removing process instance '{}'.", pi.getId()); + processInstances.remove(entry.getKey()); + } + } + log.trace("Cleanup job completed."); + } + + /** + * Instantates a task implementation given by a {@link TaskInfo}. + * @param ti The task info. + * @return A Task implementation or {@code null} if the task info does not reference any task implementing classes. + * @throws ProcessExecutionException Thrown in case of error (when the referenced class does not implement {@link Task} for instance). + */ + private Task createTaskInstance(TaskInfo ti) throws ProcessExecutionException { + String clazz = StringUtils.trimToNull(ti.getTaskImplementingClass()); + Task task = null; + + if (clazz != null) { + log.debug("Instantiating task implementing class '{}'.", clazz); + Class instanceClass = null; + try { + instanceClass = Class.forName(clazz, true, Thread.currentThread().getContextClassLoader()); + } catch (Exception e) { + throw new ProcessExecutionException("Unable to get class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); + } + if (!Task.class.isAssignableFrom(instanceClass)) { + throw new ProcessExecutionException("Class '" + clazz + "' associated with task '" + ti.getId() + "' is not assignable to " + Task.class.getName() + "."); + } + try { + task = (Task) instanceClass.newInstance(); + } catch (Exception e) { + throw new ProcessExecutionException("Unable to instantiate class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); + } + } + + return task; + } + + /** + * Starts/executes a given process instance. + * @param pi The process instance. + * @throws ProcessExecutionException Thrown in case of error. + */ + private void execute(final ProcessInstance pi) throws ProcessExecutionException { + if (ProcessInstanceState.ENDED.equals(pi.getState())) { + throw new ProcessExecutionException("Process for instance '" + pi.getId() + "' has already been ended."); + } + ProcessDefinition pd = pi.getProcessDefinition(); + ProcessNode processNode = pd.getProcessNode(pi.getNextId()); + log.debug("Processing node '{}'.", processNode.getId()); + + // distinguish process node types StartEvent, TaskInfo and EndEvent + + if (processNode instanceof TaskInfo) { + // TaskInfo types need to be executed + TaskInfo ti = (TaskInfo) processNode; + MDC.put(MDC_CTX_TASK_NAME, ti.getId()); + try { + log.info("Processing task '{}'.", ti.getId()); + Task task = createTaskInstance(ti); + if (task != null) { + try { + log.info("Executing task implementation for task '{}'.", ti.getId()); + log.debug("Execution context before task execution: {}", pi.getExecutionContext().keySet()); + task.execute(pi.getExecutionContext()); + log.info("Returned from execution of task '{}'.", ti.getId()); + log.debug("Execution context after task execution: {}", pi.getExecutionContext().keySet()); + } catch (Throwable t) { + throw new ProcessExecutionException("Error executing task '" + ti.getId() + "'.", t); + } + } else { + log.debug("No task implementing class set."); + } + } finally { + MDC.remove(MDC_CTX_TASK_NAME); + } + + } else if (processNode instanceof EndEvent) { + log.info("Finishing process instance '{}'.", pi.getId()); + processInstances.remove(pi.getId()); + pi.setState(ProcessInstanceState.ENDED); + log.debug("Final process context: {}", pi.getExecutionContext().keySet()); + return; + } + + final ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContextImpl(pi); + + // traverse pointer + Transition t = CollectionUtils.find(processNode.getOutgoingTransitions(), new Predicate() { + @Override + public boolean evaluate(Transition transition) { + if (transitionConditionExpressionEvaluator != null && transition.getConditionExpression() != null) { + log.trace("Evaluating transition expression '{}'.", transition.getConditionExpression()); + return transitionConditionExpressionEvaluator.evaluate(expressionContext, transition.getConditionExpression()); + } + return true; + } + }); + if (t == null) { + throw new ProcessExecutionException("No valid transition starting from process node '" + processNode.getId()+ "'."); + } + log.trace("Found suitable transition: {}", t); + // update pointer + log.trace("Shifting process token from '{}' to '{}'.", pi.getNextId(), t.getTo().getId()); + pi.setNextId(t.getTo().getId()); + + // inspect current task + if (t.getTo() instanceof TaskInfo && (((TaskInfo) t.getTo()).isAsync())) { + // immediately return in case of asynchonous task + log.info("Suspending process instance '{}' for asynchronous task '{}'.", pi.getId(), t.getTo().getId()); + pi.setState(ProcessInstanceState.SUSPENDED); + return; + } + + // continue execution in case of StartEvent or Task + if (processNode instanceof StartEvent || processNode instanceof TaskInfo) { + execute(pi); + } + } + + @Override + public ProcessInstance getProcessInstance(String processInstanceId) { + ProcessInstance processInstance = processInstances.get(processInstanceId); + if (processInstance == null) { + throw new IllegalArgumentException("The process instance '" + processInstanceId + "' does not/no longer exist."); + } + return processInstance; + } + + @Override + public ProcessInstance findProcessInstanceWith(String key, Serializable value) { + Iterator it = processInstances.values().iterator(); + while (it.hasNext()) { + ProcessInstance pi = it.next(); + if (Objects.equals(pi.getExecutionContext().get(key), value)) { + return pi; + } + } + return null; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessExecutionException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessExecutionException.java new file mode 100644 index 000000000..821bbe6dc --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessExecutionException.java @@ -0,0 +1,36 @@ +package at.gv.egovernment.moa.id.process; + +/** + * Indicates a problem when executing a process. + * + * @author tknall + * + */ +public class ProcessExecutionException extends Exception { + + private static final long serialVersionUID = 1L; + + /** + * Creates a new process execution exception providing a {@code message} describing the reason and the respective + * {@code cause}. + * + * @param message + * The message. + * @param cause + * The cause. + */ + public ProcessExecutionException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a new process execution exception providing a {@code message} describing the reason. + * + * @param message + * The message. + */ + public ProcessExecutionException(String message) { + super(message); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java new file mode 100644 index 000000000..0899426ca --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java @@ -0,0 +1,166 @@ +package at.gv.egovernment.moa.id.process; + +import java.io.Serializable; +import java.util.Date; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.time.DurationFormatUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; +import com.datentechnik.process_engine.model.ProcessDefinition; +import com.datentechnik.process_engine.support.SecureRandomHolder; + +/** + * Represents a process being executed. The process instance provides information about the process and its state. + * + * @author tknall + * + */ +public class ProcessInstance implements Serializable { + + private static final long serialVersionUID = 1L; + private static final int RND_ID_LENGTH = 22; + + private ProcessDefinition processDefinition; + private String nextId; + private Date lru; + private ExecutionContext executionContext; + private ProcessInstanceState state = ProcessInstanceState.NOT_STARTED; + + /** + * Creates a new process instance, based on a given process definition.

+ * An execution context will be created internally. + * + * @param processDefinition + * The process definition. + */ + ProcessInstance(ProcessDefinition processDefinition) { + this(processDefinition, null); + } + + /** + * Creates a new process instance, based on a given process definition and a + * given execution context. If the given execution context is {@code null} a new execution context will be created.

+ * The process instance id of the execution context will automatically be set (and overwritten if already set). + * + * @param processDefinition + * The process definition. + * @param executionContext + * The execution context (may be {@code null}). If {@code null} a new execution context will be created internally. + */ + ProcessInstance(ProcessDefinition processDefinition, ExecutionContext executionContext) { + this.processDefinition = processDefinition; + nextId = processDefinition.getStartEvent().getId(); + String pdIdLocalPart = RandomStringUtils.random(RND_ID_LENGTH, 0, 0, true, true, null, + SecureRandomHolder.getInstance()); + if (executionContext == null) { + executionContext = new ExecutionContextImpl(); + } + executionContext.setProcessInstanceId(this.processDefinition.getId() + "-" + pdIdLocalPart); + this.executionContext = executionContext; + touch(); + } + + /** + * Returns the underlying process definition. + * + * @return The underlying process definition. + */ + ProcessDefinition getProcessDefinition() { + touch(); + return processDefinition; + } + + /** + * Returns the id of the process node to be executed next. + * + * @return The process node pointer indicating the process node to be executed next. + */ + public String getNextId() { + touch(); + return nextId; + } + + /** + * Sets the internal pointer to the process node to be executed next. + * + * @param nextId + * The process node id to be executed next. + */ + void setNextId(String nextId) { + touch(); + this.nextId = nextId; + } + + /** + * Returns the current state of the process instance. + * + * @return The current state. + */ + public ProcessInstanceState getState() { + touch(); + return state; + } + + /** + * Sets the current state of the process instance. + * + * @param state + * The current state. + */ + void setState(ProcessInstanceState state) { + touch(); + this.state = state; + } + + public String getId() { + touch(); + return executionContext.getProcessInstanceId(); + } + + /** + * Updates the last recently used date of the process instance. + */ + private void touch() { + lru = new Date(); + } + + /** + * Returns the date the process instance has been accessed last. + * + * @return The last recently used date. + */ + Date getLru() { + return lru; + } + + /** + * Returns the associated execution context. + * @return The execution context (never {@code null}). + */ + public ExecutionContext getExecutionContext() { + touch(); + return executionContext; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ProcessInstance ["); + builder.append("id=").append(executionContext.getProcessInstanceId()); + builder.append(", idle since=").append( + DurationFormatUtils.formatDurationWords(new Date().getTime() - this.lru.getTime(), true, true)); + if (processDefinition != null) { + builder.append(", processDefinition.id="); + builder.append(processDefinition.getId()); + } + if (nextId != null) { + builder.append(", nextId="); + builder.append(nextId); + } + builder.append(", executionContext=").append(executionContext); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstanceState.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstanceState.java new file mode 100644 index 000000000..2765283a0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstanceState.java @@ -0,0 +1,30 @@ +package at.gv.egovernment.moa.id.process; + +/** + * Represents a certain process instance state. + * @author tknall + * + */ +public enum ProcessInstanceState { + + /** + * Indicates that the process with this process instance has not yet been started. + */ + NOT_STARTED, + + /** + * Indicates that the process is currently running. + */ + STARTED, + + /** + * Indicates that the process has been suspended until being waken up by someonce calling {@code signal}. + */ + SUSPENDED, + + /** + * Indicates that the process has been completed. + */ + ENDED + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExecutionContext.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExecutionContext.java new file mode 100644 index 000000000..4a9dfc336 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExecutionContext.java @@ -0,0 +1,63 @@ +package at.gv.egovernment.moa.id.process.api; + +import java.io.Serializable; +import java.util.Set; + +/** + * Encapsulates data needed for or provided by task execution. + * + * @author tknall + * + */ +public interface ExecutionContext extends Serializable { + + /** + * Returns the identifier of underlying process instance. + * + * @return The identifier of the process instance. + */ + String getProcessInstanceId(); + + /** + * Sets the identifier of underlying process instance. + * + * @param processInstanceId + * The identifier of the process instance. + */ + void setProcessInstanceId(String processInstanceId); + + /** + * Stores a serializable object using {@code key}. + * + * @param key + * The key under that the {@code object} should be stored. + * @param object The object to be stored. + */ + void put(String key, Serializable object); + + /** + * Returns an serializable object stored within this process context using {@code key}. + * + * @param key + * The key that has been used to store the serializable object (may be {@code null}). + * @return The object or {@code null} in case the key does not relate to a stored object or the stored object itself + * was {@code null}. + */ + Serializable get(String key); + + /** + * Removes the object stored using {@code key}. + * @param key + * The key that has been used to store the serializable object (may be {@code null}). + * @return The object that has been removed or {@code null} there was no object stored using {@code key}. + */ + Serializable remove(String key); + + /** + * Returns an unmodifiable set containing the stored keys. + * + * @return The keyset (never {@code null}). + */ + Set keySet(); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java new file mode 100644 index 000000000..bb3b267cf --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java @@ -0,0 +1,23 @@ +package at.gv.egovernment.moa.id.process.api; + +import java.io.Serializable; +import java.util.Map; + +import com.datentechnik.process_engine.model.Transition; + +/** + * Context used for evaluation of condition expressions set for {@linkplain Transition Transitions}. + * + * @author tknall + * + */ +public interface ExpressionEvaluationContext extends Serializable { + + /** + * Returns the context data map used for expression evaluation. + * + * @return An unmodifiable map (never {@code null}). + */ + Map getCtx(); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluator.java new file mode 100644 index 000000000..fe0743201 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluator.java @@ -0,0 +1,25 @@ +package at.gv.egovernment.moa.id.process.api; + +/** + * Evaluates a given {@code expression} returning a boolean value. + * + * @author tknall + */ +public interface ExpressionEvaluator { + + /** + * Evaluates a given {@code expression} returning a boolean value. + * + * @param expressionContext + * The context which can be used for evaluation of the expression. + * @param expression + * The expression resulting in a boolean (must not be {@code null}). + * @return A boolean value. + * @throws IllegalArgumentException + * In case of an invalid {@code expression}. + * @throws NullPointerException + * In case of a {@code null} expression. + */ + boolean evaluate(ExpressionEvaluationContext expressionContext, String expression); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java new file mode 100644 index 000000000..6401b1d5d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java @@ -0,0 +1,21 @@ +package at.gv.egovernment.moa.id.process.api; + + +/** + * Represents a single task to be performed upon process execution. + * + * @author tknall + * + */ +public interface Task { + + /** + * Executes this task. + * + * @param executionContext + * Provides execution related information. + * @throws Exception An exception upon task execution. + */ + void execute(ExecutionContext executionContext) throws Exception; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/EndEvent.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/EndEvent.java new file mode 100644 index 000000000..49fb082ea --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/EndEvent.java @@ -0,0 +1,42 @@ +package at.gv.egovernment.moa.id.process.model; + +import java.io.Serializable; + +import org.apache.commons.collections4.CollectionUtils; + +/** + * Represents an end event. Process execution terminates when an end event is reached. + * + * @author tknall + */ +public class EndEvent extends ProcessNode implements Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("EndEvent ["); + if (getId() != null) { + builder.append("id="); + builder.append(getId()); + } + if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("incomingTransitions="); + builder.append(getIncomingTransitions()); + } + if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("outgoingTransitions="); + builder.append(getOutgoingTransitions()); + } + builder.append("]"); + return builder.toString(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java new file mode 100644 index 000000000..19e78b0e6 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java @@ -0,0 +1,158 @@ +package at.gv.egovernment.moa.id.process.model; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +import com.datentechnik.process_engine.ProcessDefinitionParser; + +/** + * Represents a single process definition containing + *

    + *
  • a {@link StartEvent},
  • + *
  • one or more {@linkplain TaskInfo Tasks},
  • + *
  • one or more {@linkplain EndEvent EndEvents} and
  • + *
  • some {@linkplain Transition Transitions} linking StartEvents, Tasks and EndEvents. + *
+ * + * @author tknall + * + */ +public class ProcessDefinition { + + private String id; + private StartEvent startEvent; + private Map taskInfos = new LinkedHashMap<>(); + private Map endEvents = new LinkedHashMap<>(); + + /** + * Returns the unique identifier of the process definition. + * + * @return The unique identifier (never {@code null} if process definition comes from + * {@link ProcessDefinitionParser}). + */ + public String getId() { + return id; + } + + /** + * Sets the unique identifier of the process definition. + * + * @param id + * The unique identifier. + */ + public void setId(String id) { + this.id = id; + } + + /** + * Returns the start event of the process definition. + * + * @return The start event (never {@code null} if process definition comes from {@link ProcessDefinitionParser}). + */ + public StartEvent getStartEvent() { + return startEvent; + } + + /** + * Sets the start event of the process definition. + * + * @param startEvent + * The start event. + */ + public void setStartEvent(StartEvent startEvent) { + this.startEvent = startEvent; + } + + /** + * Returns a map containing the tasks of the process definition. + * + * @return The tasks (map is never {@code null} if process definition comes from {@link ProcessDefinitionParser}). + */ + public Map getTaskInfos() { + return taskInfos; + } + + /** + * Sets the map containing the tasks. + * + * @param taskInfos + * The map containing the tasks. + */ + public void setTaskInfos(Map taskInfos) { + this.taskInfos = taskInfos; + } + + /** + * Returns a map containing the end events of the process description. + * + * @return The map containing the end events (map is never {@code null} if process definition comes from + * {@link ProcessDefinitionParser}). + */ + public Map getEndEvents() { + return endEvents; + } + + /** + * Sets a map containing the end events of the process description. + * + * @param endEvents + * The map containing the end events. + */ + public void setEndEvents(Map endEvents) { + this.endEvents = endEvents; + } + + /** + * Returns the process node associated with the given {@code id}. + * + * @param id + * The identifier of the process node. + * @return The process node (may be {code null} when no process node with the given {@code id} exists). + */ + public ProcessNode getProcessNode(String id) { + Objects.requireNonNull(id, "Identifier must not be null."); + if (startEvent != null && id.equals(startEvent.getId())) { + return startEvent; + } + TaskInfo task = taskInfos.get(id); + if (task != null) { + return task; + } + return endEvents.get(id); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + if (id != null) { + builder.append("id="); + builder.append(id); + } + if (startEvent != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("startEvent="); + builder.append(startEvent); + } + if (taskInfos != null && !taskInfos.isEmpty()) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("tasksInfos="); + builder.append(taskInfos.values()); + } + if (endEvents != null && !endEvents.isEmpty()) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("endEvents="); + builder.append(endEvents.values()); + } + builder.insert(0, "ProcessDefinition ["); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java new file mode 100644 index 000000000..a94d33943 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java @@ -0,0 +1,69 @@ +package at.gv.egovernment.moa.id.process.model; + +import java.util.ArrayList; +import java.util.List; + +import com.datentechnik.process_engine.ProcessDefinitionParser; + +/** + * Represents a {@link StartEvent}, an {@link EndEvent} or a {@linkplain TaskInfo Task}. + * @author tknall + * + */ +public abstract class ProcessNode { + + private String id; + private List outgoingTransitions = new ArrayList<>(); + private List incomingTransitions = new ArrayList<>(); + + /** + * Returns the unique identifier of the process node. + * + * @return The unique identifier (never {@code null} if process node comes from a process definition from + * {@link ProcessDefinitionParser}). + */ + public String getId() { + return id; + } + + /** + * Sets the unique identifier of the process node. + * @param id The unique identifier. + */ + public void setId(String id) { + this.id = id; + } + + /** + * Returns a list of transitions pointing from this process node to another one. + * @return A list of transitions (never {@code null} if process node comes from a process definition from {@link ProcessDefinitionParser}). + */ + public List getOutgoingTransitions() { + return outgoingTransitions; + } + + /** + * Sets the list of transitions pointing from this process node to another one. + * @param outgoingTransitions The list of transitions originating from this process node. + */ + public void setOutgoingTransitions(List outgoingTransitions) { + this.outgoingTransitions = outgoingTransitions; + } + + /** + * Returns a list of transitions pointing from another process node to this one. + * @return A list of transitions (never {@code null} if process node comes from a process definition from {@link ProcessDefinitionParser}). + */ + public List getIncomingTransitions() { + return incomingTransitions; + } + + /** + * Sets the list of transitions pointing from another process node to this one. + * @param incomingTransitions A list of transitions pointing to this process node. + */ + public void setIncomingTransitions(List incomingTransitions) { + this.incomingTransitions = incomingTransitions; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/StartEvent.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/StartEvent.java new file mode 100644 index 000000000..60175e09c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/StartEvent.java @@ -0,0 +1,45 @@ +package at.gv.egovernment.moa.id.process.model; + +import java.io.Serializable; + +import org.apache.commons.collections4.CollectionUtils; + +/** + * Represents a start event. Each process description contains a single start event. Process execution starts with a + * start event. + * + * @author tknall + * + */ +public class StartEvent extends ProcessNode implements Serializable { + + private static final long serialVersionUID = 1L; + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("StartEvent ["); + if (getId() != null) { + builder.append("id="); + builder.append(getId()); + } + if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("incomingTransitions="); + builder.append(getIncomingTransitions()); + } + if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("outgoingTransitions="); + + builder.append(getOutgoingTransitions()); + } + builder.append("]"); + return builder.toString(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java new file mode 100644 index 000000000..b7f13a880 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java @@ -0,0 +1,94 @@ +package at.gv.egovernment.moa.id.process.model; + +import java.io.Serializable; + +import org.apache.commons.collections4.CollectionUtils; + +import com.datentechnik.process_engine.api.Task; + +/** + * Represents information about a single task to be performed upon process execution. + * @author tknall + * + */ +public class TaskInfo extends ProcessNode implements Serializable { + + private static final long serialVersionUID = 1L; + private static final boolean DEFAULT_ASYNC = false; + + private String taskImplementingClass; + private boolean async = DEFAULT_ASYNC; + + /** + * Determines if the task is marked asynchronous ({@code true}) or synchronous ({@code false}). + * @return A flag indicating if the task should be executed asynchronously or synchronously. (Default: {@code false}) + */ + public boolean isAsync() { + return async; + } + + /** + * Marks a task to executed asynchronously ({@code true}) or synchronously ({@code false}). + * @param async The flag. + */ + public void setAsync(boolean async) { + this.async = async; + } + + /** + * Returns the class that implements the actual task (must implement {@link Task}). + * @return The task implementing class. + */ + public String getTaskImplementingClass() { + return taskImplementingClass; + } + + /** + * Sets the class that implements the actual task (must implement {@link Task}). + * @param taskImplementingClass The task implementing class. + */ + public void setTaskImplementingClass(String taskImplementingClass) { + this.taskImplementingClass = taskImplementingClass; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + if (getId() != null) { + builder.append("id="); + builder.append(getId()); + } + if (async != DEFAULT_ASYNC) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("async="); + builder.append(async); + } + if (taskImplementingClass != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("taskImplementingClass="); + builder.append(taskImplementingClass); + } + if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("incomingTransitions="); + builder.append(getIncomingTransitions()); + } + if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("outgoingTransitions="); + builder.append(getOutgoingTransitions()); + } + builder.insert(0, "TaskInfo ["); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java new file mode 100644 index 000000000..9d9c44c8c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java @@ -0,0 +1,136 @@ +package at.gv.egovernment.moa.id.process.model; + +import java.io.Serializable; + +import com.datentechnik.process_engine.ProcessDefinitionParser; + +/** + * Represents a single transition from a {@link StartEvent} or {@linkplain TaskInfo Task} to another + * {@linkplain TaskInfo Task} or {@link EndEvent}. + * + * @author tknall + * + */ +public class Transition implements Serializable { + + private static final long serialVersionUID = 1L; + + private String id; + private String conditionExpression; + private ProcessNode from; + private ProcessNode to; + + /** + * Returns the process node (effectively a {@link StartEvent} or {@linkplain TaskInfo Task}) the transition is + * pointing from. + * + * @return The transition's source process node (never {@code null} if transition comes from a process definition + * from {@link ProcessDefinitionParser}). + */ + public ProcessNode getFrom() { + return from; + } + + /** + * Sets the process node the transition is pointing from. + * + * @param from + * The transition's source process node. + */ + public void setFrom(ProcessNode from) { + this.from = from; + } + + /** + * Returns the process node (effectively a {@linkplain TaskInfo Task} or {@link EndEvent}) the transition is + * pointing to. + * + * @return The transition's destination process node (never {@code null} if transition comes from a process + * definition from {@link ProcessDefinitionParser}). + */ + public ProcessNode getTo() { + return to; + } + + /** + * Sets the process node the transition is pointing to. + * + * @param to + * The transition's destination process node. + */ + public void setTo(ProcessNode to) { + this.to = to; + } + + /** + * Returns the unique identifier of the transition. + * + * @return The unique identifier (may be {@code null}). + */ + public String getId() { + return id; + } + + /** + * Sets the unique identifier of the transition. + * + * @param id + * The unique identifier. + */ + public void setId(String id) { + this.id = id; + } + + /** + * Returns the condition expression for this transition. + * + * @return The condition expression (may be {@code null}). + */ + public String getConditionExpression() { + return conditionExpression; + } + + /** + * Sets the condition expression for this transition. + * + * @param conditionExpression + * The condition expression. + */ + public void setConditionExpression(String conditionExpression) { + this.conditionExpression = conditionExpression; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + if (id != null) { + builder.append("id="); + builder.append(id); + } + if (from != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("from.id="); + builder.append(from.getId()); + } + if (to != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("to.id="); + builder.append(to.getId()); + } + if (conditionExpression != null) { + if (builder.length() > 0) { + builder.append(", "); + } + builder.append("conditionExpression="); + builder.append(conditionExpression); + } + builder.insert(0, "Transition ["); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java new file mode 100644 index 000000000..1c91cf780 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java @@ -0,0 +1,61 @@ +package at.gv.egovernment.moa.id.process.spring; + +import java.util.Objects; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.BooleanUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.expression.Expression; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.StandardEvaluationContext; + +import com.datentechnik.process_engine.api.ExpressionEvaluationContext; +import com.datentechnik.process_engine.api.ExpressionEvaluator; +import com.datentechnik.process_engine.model.Transition; + +/** + * Expression evaluator for processing {@link Transition} conditions allowing to reference Spring beans from the + * application context. + * + * @author tknall + * + */ +public class SpringExpressionEvaluator implements ExpressionEvaluator { + + private Logger log = LoggerFactory.getLogger(getClass()); + private ExpressionParser parser = new SpelExpressionParser(); + private StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + + @Autowired(required = false) + private ApplicationContext ctx; + + @PostConstruct + private void init() { + if (ctx != null) { + evaluationContext.setBeanResolver(new BeanFactoryResolver(ctx)); + } + } + + @Override + public boolean evaluate(ExpressionEvaluationContext expressionContext, String expression) { + Objects.requireNonNull(expression, "Expression must not be null."); + log.trace("Evaluating '{}'.", expression); + + Expression expr = parser.parseExpression(expression); + Boolean result = expr.getValue(evaluationContext, expressionContext, Boolean.class); + if (result == null) { + log.warn("Evaluation of '{}' results in null-value.", expression); + } else { + log.debug("Expression '{}' -> {}", expression, result); + } + + return BooleanUtils.isTrue(result); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java new file mode 100644 index 000000000..4b5af854e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java @@ -0,0 +1,116 @@ +package at.gv.egovernment.moa.id.process.springweb; + +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.NoUniqueBeanDefinitionException; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.support.WebApplicationContextUtils; + +import com.datentechnik.process_engine.ProcessEngine; +import com.datentechnik.process_engine.ProcessInstance; +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Abstract HttpServlet that provides means for retrieving the process engine (Spring Web required) as well as + * retrieving the underlying process instance and execution context evaluating a certain request parameter. + * + * @author tknall + * + */ +public abstract class AbstractAuthSourceServlet extends HttpServlet { + + private static final long serialVersionUID = 1L; + + private ProcessEngine processEngine; + + /** + * Returns the name of the request parameter representing the respective instance id. + *

Default is {@code processInstanceId}. + * @return The request parameter name. + */ + public String getProcessInstanceIdParameterName() { + return "processInstanceId"; + } + + /** + * Returns the underlying process engine instance. + * + * @return The process engine (never {@code null}). + * @throws NoSuchBeanDefinitionException + * if no {@link ProcessEngine} bean was found. + * @throws NoUniqueBeanDefinitionException + * if more than one {@link ProcessEngine} bean was found. + * @throws BeansException + * if a problem getting the {@link ProcessEngine} bean occurred. + * @throws IllegalStateException + * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a + * Spring web environment. + */ + public synchronized ProcessEngine getProcessEngine() { + if (processEngine == null) { + WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); + if (ctx == null) { + throw new IllegalStateException( + "Unable to find Spring WebApplicationContext. Servlet needs to be executed within a Spring web environment."); + } + processEngine = ctx.getBean(ProcessEngine.class); + } + return processEngine; + } + + /** + * Retrieves the process instance referenced by the request parameter {@link #getProcessInstanceIdParameterName()}. + * + * @param request + * The HttpServletRequest. + * @return The process instance (never {@code null}). + * @throws NoSuchBeanDefinitionException + * if no {@link ProcessEngine} bean was found. + * @throws NoUniqueBeanDefinitionException + * if more than one {@link ProcessEngine} bean was found. + * @throws BeansException + * if a problem getting the {@link ProcessEngine} bean occurred. + * @throws IllegalStateException + * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a + * Spring web environment. + * @throws IllegalArgumentException + * in case the process instance id referenced by the request parameter + * {@link #getProcessInstanceIdParameterName()} does not exist. + */ + public ProcessInstance getProcessInstance(HttpServletRequest request) { + String processInstanceId = StringUtils.trimToNull(request.getParameter(getProcessInstanceIdParameterName())); + if (processInstanceId == null) { + throw new IllegalArgumentException("Missing request parameter '" + getProcessInstanceIdParameterName() + "'."); + } + return getProcessEngine().getProcessInstance(processInstanceId); + } + + /** + * Retrieves the execution context for the respective process instance referenced by the request parameter + * {@link #getProcessInstanceIdParameterName()}. + * + * @param request + * The HttpServletRequest. + * @return The execution context (never {@code null}). + * @throws NoSuchBeanDefinitionException + * if no {@link ProcessEngine} bean was found. + * @throws NoUniqueBeanDefinitionException + * if more than one {@link ProcessEngine} bean was found. + * @throws BeansException + * if a problem getting the {@link ProcessEngine} bean occurred. + * @throws IllegalStateException + * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a + * Spring web environment. + * @throws IllegalArgumentException + * in case the process instance id referenced by the request parameter + * {@link #getProcessInstanceIdParameterName()} does not exist. + */ + public ExecutionContext getExecutionContext(HttpServletRequest request) { + return getProcessInstance(request).getExecutionContext(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java new file mode 100644 index 000000000..1f7fb7690 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java @@ -0,0 +1,73 @@ +package at.gv.egovernment.moa.id.process.springweb; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.filter.RequestContextFilter; + +import com.datentechnik.process_engine.api.ExecutionContext; +import com.datentechnik.process_engine.api.Task; + +/** + * Abstract task implementation providing {@link HttpServletRequest} and {@link HttpServletResponse}. + *

+ * Note that this abstract task requires the Spring (web) framework including a {@link RequestContextFilter} to be set + * within {@code web.xml}. + * + *

+ * ...
+ * <filter>
+ *   <filter-name>requestContextFilter</filter-name>
+ *   <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
+ * </filter>
+ * <filter-mapping>
+ *   <filter-name>requestContextFilter</filter-name>
+ *   <url-pattern>/*</url-pattern>
+ * </filter-mapping>
+ * ...
+ * 
+ * + * @author tknall + * + */ +public abstract class AbstractSpringWebSupportedTask implements Task { + + /** + * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} as well as the + * respective {@link HttpServletRequest} and {@link HttpServletResponse}. + * + * @param executionContext + * The execution context (never {@code null}). + * @param request + * The HttpServletRequest (never {@code null}). + * @param response + * The HttpServletResponse (never {@code null}). + * @throws IllegalStateException + * Thrown in case the task is nur being run within the required environment. Refer to javadoc for + * further information. + * @throws Exception + * Thrown in case of error executing the task. + */ + public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, + HttpServletResponse response) throws Exception; + + @Override + public void execute(ExecutionContext executionContext) throws Exception { + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { + HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); + HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse(); + if (request == null || response == null) { + throw new IllegalStateException( + "Spring's RequestContextHolder did not provide HttpServletResponse. Did you forget to set the required org.springframework.web.filter.RequestContextFilter in your web.xml."); + } + execute(executionContext, request, response); + } else { + throw new IllegalStateException("Task needs to be executed within a Spring web environment."); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/support/SecureRandomHolder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/support/SecureRandomHolder.java new file mode 100644 index 000000000..72677739a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/support/SecureRandomHolder.java @@ -0,0 +1,35 @@ +package at.gv.egovernment.moa.id.process.support; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +/** + * Holder for a secure random instance following the initialization on demand holder design pattern. The secure random + * instance is a singleton that is initialized on first usage. + * + * @author tknall + * + */ +public class SecureRandomHolder { + + private SecureRandomHolder() { + } + + private static final SecureRandom SRND_INSTANCE; + static { + try { + SRND_INSTANCE = SecureRandom.getInstance("SHA1PRNG"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("Unable to instantiate SHA1PRNG.", e); + } + } + + /** + * Returns a secure random generator instance. + * @return The secure random instance. + */ + public static SecureRandom getInstance() { + return SecureRandomHolder.SRND_INSTANCE; + } + +} \ No newline at end of file -- cgit v1.2.3 From 8579cf80c3602f963566d31eaf04f59f68d3bf11 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Thu, 29 Jan 2015 10:56:18 +0100 Subject: Add STORK process (MOAID-58). - Add STORKAuthentication.process.xml - Add PepsConnectorTask using code from PEPSConnectorServlet. - Split code from PEPSConnectorWithLocalSigningServlet into PepsConnectorHandleResponseWithoutSignatureTask and PepsConnectorHandleLocalSignResponseTask. - Replace SpringExpressionEvaluator within applicationContext.xml with SpringWebExpressionEvaluator (allowing expressions using request parameter(s)). - Make servlet mappings /PEPSConnectorWithLocalSigning and /PEPSConnector point to the process engine signaling servlet. - Add many FIXMEs marking problematic code. - Move code to start stork authentication from StartAuthenticationBuilder to CreateStorkAuthRequestFormTask. - Mark PEPSConnectorServlet and PEPSConnectorWithLocalSigningServlet deprecated. - Remove @author tknall from classes assembled using existing (bogus) code. --- .../moa/id/auth/AuthenticationServer.java | 13 +- .../auth/builder/StartAuthenticationBuilder.java | 28 +- .../moa/id/auth/servlet/PEPSConnectorServlet.java | 1 + .../PEPSConnectorWithLocalSigningServlet.java | 1 + .../moa/id/auth/tasks/AbstractAuthServletTask.java | 3 - .../id/auth/tasks/CertificateReadRequestTask.java | 5 +- .../id/auth/tasks/CreateIdentityLinkFormTask.java | 1 - .../moa/id/auth/tasks/GetForeignIDTask.java | 1 - .../moa/id/auth/tasks/GetMISSessionIDTask.java | 1 - .../auth/tasks/PrepareAuthBlockSignatureTask.java | 1 - .../auth/tasks/VerifyAuthenticationBlockTask.java | 1 - .../moa/id/auth/tasks/VerifyCertificateTask.java | 1 - .../moa/id/auth/tasks/VerifyIdentityLinkTask.java | 9 +- .../AbstractPepsConnectorWithLocalSigningTask.java | 258 ++++++++++ .../stork/CreateStorkAuthRequestFormTask.java | 114 +++++ .../PepsConnectorHandleLocalSignResponseTask.java | 218 ++++++++ ...onnectorHandleResponseWithoutSignatureTask.java | 441 ++++++++++++++++ .../moa/id/auth/tasks/stork/PepsConnectorTask.java | 567 +++++++++++++++++++++ 18 files changed, 1619 insertions(+), 45 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/AbstractPepsConnectorWithLocalSigningTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleLocalSignResponseTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleResponseWithoutSignatureTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorTask.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index c33e5c735..cf50a1bf5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -1402,8 +1402,8 @@ public class AuthenticationServer implements MOAIDAuthConstants { * Retrieves a session from the session store. * * @param id session ID - * @return AuthenticationSession stored with given session ID, - * null if session ID unknown + * @return AuthenticationSession stored with given session ID (never {@code null}). + * @throws AuthenticationException in case the session id does not reflect a valic, active session. */ public static AuthenticationSession getSession(String id) throws AuthenticationException { @@ -1707,10 +1707,6 @@ public class AuthenticationServer implements MOAIDAuthConstants { // String acsURL = new DataURLBuilder().buildDataURL(issuerValue, // PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN, moasession.getSessionID()); - //solve Problem with sessionIDs - String acsURL = issuerValue + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; - - Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL); String providerName = oaParam.getFriendlyName(); Logger.debug("Issuer value: " + issuerValue); @@ -1744,8 +1740,12 @@ public class AuthenticationServer implements MOAIDAuthConstants { List value = new ArrayList(); Logger.debug("PEPS supports XMLSignatures:"+cpeps.isXMLSignatureSupported()); + String acsURL; if(cpeps.isXMLSignatureSupported())//Send SignRequest to PEPS { + //solve Problem with sessionIDs + acsURL = issuerValue + PEPSConnectorServlet.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); @@ -1776,6 +1776,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { } } + Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL); if (Logger.isDebugEnabled()) { Logger.debug("The following attributes are requested for this OA:"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java index a92d3f678..9a8372a2d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java @@ -52,10 +52,9 @@ public class StartAuthenticationBuilder { *
    *
  • Either creates an "IdentityLinkForm" with embedded {@code InfoBoxReadRequest} to be submitted to a citizen card * environment for reading the subject's IdentityLink
  • - *
  • or creates a STORK auth request and redirects to a CPEPS.
  • *
* - * @return The "IdentityLinkForm" or an empty String in case of STORK. + * @return The IdentityLinkForm. */ public String build(AuthenticationSession moasession, HttpServletRequest req, HttpServletResponse resp) throws WrongParametersException, MOAIDException { @@ -64,26 +63,11 @@ public class StartAuthenticationBuilder { throw new AuthenticationException("auth.18", new Object[] { }); } - STORKConfig storkConfig = AuthConfigurationProvider.getInstance().getStorkConfig(); - - Logger.info("Starting authentication for a citizen of country: " + (StringUtils.isEmpty(moasession.getCcc()) ? "AT" : moasession.getCcc())); - // STORK or normal authentication - // TODO[branch]: STORK - if (storkConfig.isSTORKAuthentication(moasession.getCcc())) { - //STORK authentication - Logger.trace("Found C-PEPS configuration for citizen of country: " + moasession.getCcc()); - Logger.debug("Starting STORK authentication"); - - AuthenticationServer.startSTORKAuthentication(req, resp, moasession); - return ""; - - } else { - //normal MOA-ID authentication - Logger.debug("Starting normal MOA-ID authentication"); - - String getIdentityLinkForm = AuthenticationServer.getInstance().startAuthentication(moasession, req); + //normal MOA-ID authentication + Logger.debug("Starting normal MOA-ID authentication"); + + String getIdentityLinkForm = AuthenticationServer.getInstance().startAuthentication(moasession, req); - return getIdentityLinkForm; - } + return getIdentityLinkForm; } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index 4cd192070..02e1cb12d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -97,6 +97,7 @@ import javax.xml.ws.BindingProvider; /** * Endpoint for receiving STORK response messages + * @deprecated Use {@link at.gv.egovernment.moa.id.auth.tasks.stork.PepsConnectorTask} instead. */ public class PEPSConnectorServlet extends AuthServlet { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java index 165445ea5..fa80bdab9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java @@ -109,6 +109,7 @@ import eu.stork.peps.exceptions.STORKSAMLEngineException; /** * Endpoint for receiving STORK response messages + * @deprecated Use {@link at.gv.egovernment.moa.id.auth.tasks.stork.PepsConnectorHandleResponseWithoutSignatureTask} instead. */ public class PEPSConnectorWithLocalSigningServlet extends AuthServlet { private static final long serialVersionUID = 1L; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java index 7351933c1..9a5c2baee 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java @@ -43,9 +43,6 @@ import com.datentechnik.process_engine.springweb.AbstractSpringWebSupportedTask; /** * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing * etc.).

The code has been taken from {@link AuthServlet}. - * - * @author tknall - * */ public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java index da8a3d997..29e9ac42f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java @@ -40,7 +40,6 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
  • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code {/VerifyCertificate}
  • * * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. - * @author tknall * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ @@ -71,9 +70,9 @@ public class CertificateReadRequestTask extends AbstractAuthServletTask { AuthenticationSession session = AuthenticationServer.getSession(sessionID); boolean useMandate = session.getUseMandate(); - boolean identityLinkFound = BooleanUtils.isTrue((Boolean) executionContext.get("identityLinkFound")); + boolean identityLinkAvailable = BooleanUtils.isTrue((Boolean) executionContext.get("identityLinkAvailable")); - if (!identityLinkFound && useMandate) { + if (!identityLinkAvailable && useMandate) { Logger.error("Online-Mandate Mode for foreign citizencs not supported."); throw new AuthenticationException("auth.13", null); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java index 70afd477d..01628dcf6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java @@ -54,7 +54,6 @@ import com.datentechnik.process_engine.api.ExecutionContext; * * * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GenerateIFrameTemplateServlet}. - * @author tknall * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java index 602ad527b..8e52e3827 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java @@ -59,7 +59,6 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
  • Redirect to {@code /dispatcher}.
  • * * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet}. - * @author tknall * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java index 40e33ae43..626d33917 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java @@ -55,7 +55,6 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
  • Redirect to {@code /dispatcher}.
  • * * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GetMISSessionIDServlet}. - * @author tknall * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java index 30777198c..8b45f1c66 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java @@ -38,7 +38,6 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
  • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
  • * * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. - * @author tknall * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java index 2bc0bb8ad..97f3a21cb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java @@ -70,7 +70,6 @@ import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; * * * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet}. - * @author tknall * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java index ddea4c414..7e76819ff 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java @@ -50,7 +50,6 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
  • {@code CreateXMLSignatureRequest} send as HttpServletResponse (for CCE).
  • * * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet}. - * @author tknall * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java index 5b21cd29c..9711b4bc4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java @@ -31,7 +31,7 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
  • Parses the identity link retrieved as {@code InfoBoxReadResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
  • *
  • Verifies the identity link.
  • *
  • Updates moa session.
  • - *
  • Puts boolean flag {@code identityLinkFound} into {@code ExecutionContext}.
  • + *
  • Puts boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.
  • * * Expects: *
      @@ -41,10 +41,9 @@ import com.datentechnik.process_engine.api.ExecutionContext; * Result: *
        *
      • Identity link put into moa session.
      • - *
      • Boolean flag {@code identityLinkFound} into {@code ExecutionContext}.
      • + *
      • Boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.
      • *
      * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. - * @author tknall * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ @@ -81,10 +80,10 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { AuthenticationSession session = AuthenticationServer.getSession(sessionID); - boolean identityLinkFound = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters) != null; + boolean identityLinkAvailable = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters) != null; AuthenticationSessionStoreage.storeSession(session); - executionContext.put("identityLinkFound", identityLinkFound); + executionContext.put("identityLinkAvailable", identityLinkAvailable); } catch (ParseException ex) { handleError(null, ex, req, resp, pendingRequestID); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/AbstractPepsConnectorWithLocalSigningTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/AbstractPepsConnectorWithLocalSigningTask.java new file mode 100644 index 000000000..eff7fe43f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/AbstractPepsConnectorWithLocalSigningTask.java @@ -0,0 +1,258 @@ +package at.gv.egovernment.moa.id.auth.tasks.stork; + +import at.gv.egovernment.moa.id.auth.tasks.AbstractAuthServletTask; +import iaik.x509.X509Certificate; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +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.bind.JAXBException; +import javax.xml.parsers.ParserConfigurationException; +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.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 org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +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.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.servlet.PEPSConnectorWithLocalSigningServlet; +import at.gv.egovernment.moa.id.auth.stork.STORKException; +import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; +import at.gv.egovernment.moa.id.auth.tasks.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.id.util.VelocityProvider; +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.egovernment.moa.util.StringUtils; +import at.gv.util.xsd.xmldsig.SignatureType; +import at.gv.util.xsd.xmldsig.X509DataType; + +import com.datentechnik.process_engine.api.ExecutionContext; + +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.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; + +public abstract class AbstractPepsConnectorWithLocalSigningTask extends AbstractAuthServletTask { + + 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 = AuthConfigurationProvider.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) 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) 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java new file mode 100644 index 000000000..c32c9d791 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java @@ -0,0 +1,114 @@ +package at.gv.egovernment.moa.id.auth.tasks.stork; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; +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.tasks.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.stork.CPEPS; +import at.gv.egovernment.moa.id.config.stork.STORKConfig; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * 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.

      + * In detail: + *

        + *
      • Validates the stork configuration in order to make sure the selected country is supported.
      • + *
      • Puts a flag ({@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}) into the ExecutionContext reflecting the capability of the C-PEPS to create xml signatures.
      • + *
      • Invokes {@link AuthenticationServer#startSTORKAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationSession)} which
      • + *
          + *
        • Creates and signs a SAML2 stork authentication request.
        • + *
        • Creates a signature request for auth block signature (either to be performed by the C-PEPS or locally).
        • + *
        • Using the velocity template engine in order to create a form with the embedded stork request.
        • + *
        • Writes the form to the response output stream.
        • + *
        + *
      + * Expects: + *
        + *
      • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
      • + *
      • Property {@code ccc} set within the moa session.
      • + *
      + * Result: + *
        + *
      • Form containing a SAML2 Stork authentication request and an action url pointing to the selected C-PEPS.
      • + *
      • 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.
      • + *
      • In case of a C-PEPS not supporting xml signature: moasession with set signedDoc property (containing the signature request for local signing).
      • + *
      • ExecutionContext contains the boolean flag {@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}. + *
      + * Code taken from {@link StartAuthenticationBuilder#build(AuthenticationSession, HttpServletRequest, HttpServletResponse)}.
      + * 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 Exception { + + String pendingRequestID = null; + String sessionID = null; + try { + setNoCachingHeaders(resp); + + sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("CreateStorkAuthRequestFormTask", PARAM_SESSIONID, "auth.12"); + } + AuthenticationSession moasession = AuthenticationServer.getSession(sessionID); + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + if (StringUtils.isEmpty(moasession.getCcc())) { + // illegal state; task should not have been executed without a selected country + throw new AuthenticationException("stork.22", new Object[] { sessionID }); + } + STORKConfig storkConfig = AuthConfigurationProvider.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(moasession.getCcc()); + Logger.debug("Found C-PEPS configuration for citizen of country: " + moasession.getCcc()); + executionContext.put(PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED, cpeps.isXMLSignatureSupported()); + + Logger.info("Starting STORK authentication for a citizen of country: " + moasession.getCcc()); + AuthenticationServer.startSTORKAuthentication(req, resp, moasession); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("CreateStorkAuthRequestFormTask has an interal Error.", e); + throw new MOAIDException("Internal error.", new Object[] { sessionID }, e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleLocalSignResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleLocalSignResponseTask.java new file mode 100644 index 000000000..738988ff7 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleLocalSignResponseTask.java @@ -0,0 +1,218 @@ +package at.gv.egovernment.moa.id.auth.tasks.stork; + +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.auth.AuthenticationServer; +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.stork.STORKException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +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 com.datentechnik.process_engine.api.ExecutionContext; + +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. + *

      + * In detail: + *

        + *
      • Changes moa session id.
      • + *
      • Decodes and validates the sign response, extracting the citizen's signature.
      • + *
      • Verifies the citizen's signature.
      • + *
      • Create {@code signedDoc} attribute.
      • + *
      • Retrieve identity link from SZR gateway using the citizen's signature.
      • + *
      • 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).
      • + *
      • The moa session is updated with authentication information.
      • + *
      • Change moa session id.
      • + *
      • Redirects back to {@code /dispatcher} in order to finalize the authentication.
      • + *
      + * Expects: + *
        + *
      • HttpServletRequest parameter {@code moaSessionID}
      • + *
      • HttpServletRequest parameter {@code signresponse}
      • + *
      + * Result: + *
        + *
      • Updated moa id session (signed auth block, signer certificate etc.)
      • + *
      • Redirect to {@code /dispatcher}.
      • + *
      • {@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.
      • + *
      + * Possible branches: + *
        + *
      • In case the szr gateway throws exception due to missing gender information: + *
          + *
        • Returns a form for gender selection with action url back to this servlet/task.
        • + *
        + *
      • + *
      + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.
      + * + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + */ +public class PepsConnectorHandleLocalSignResponseTask extends AbstractPepsConnectorWithLocalSigningTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws Exception { + 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 IOException("should not occur"); + } + return; + } + + private void handleSignResponse(ExecutionContext executionContext, HttpServletRequest request, + HttpServletResponse response) { + 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 = AuthenticationServer.getSession(moaSessionID); + // change MOASessionID + moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); + Logger.info("pendingRequestID:" + pendingRequestID); + String signResponseString = new String(Base64.decodeBase64(signResponse), "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 values = new ArrayList(); + 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? + 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) { + handleError(null, e, request, response, pendingRequestID); + + } catch (MOAIDException e) { + handleError(null, e, request, response, pendingRequestID); + + } catch (Exception e) { + Logger.error("PEPSConnector has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleResponseWithoutSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleResponseWithoutSignatureTask.java new file mode 100644 index 000000000..31bc28f5a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleResponseWithoutSignatureTask.java @@ -0,0 +1,441 @@ +package at.gv.egovernment.moa.id.auth.tasks.stork; + +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.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.AuthenticationServer; +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.servlet.PEPSConnectorWithLocalSigningServlet; +import at.gv.egovernment.moa.id.auth.stork.STORKException; +import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +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.StringUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +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. + *

      + * In detail: + *

        + *
      • Decodes and validates SAML response from C-PEPS.
      • + *
      • Retrieves the moa session using the session id provided by HttpServletRequest parameter {@code RelayState} or by {@code inResponseTo} attribute of the saml response.
      • + *
      • Store saml response in moa session.
      • + *
      • Change moa session id.
      • + *
      • Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.
      • + *
      + * Expects: + *
        + *
      • HttpServletRequest parameter {@code moaSessionID} to be {@code null}
      • + *
      • HttpServletRequest parameter {@code signresponse} to be {@code null}
      • + *
      • HttpServletRequest parameter {@code SAMLResponse}
      • + *
      • Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute within the saml response, both reflecting the moa session id.
      • + *
      + * Result: + *
        + *
      • Updated moa session (with saml response).
      • + *
      • Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.
      • + *
      + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.
      + * + * @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 Exception { + 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 IOException("should not occur"); + } + return; + } + + private void handleSAMLResponse(ExecutionContext executionContext, HttpServletRequest request, + HttpServletResponse response) { + 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.validateSTORKAuthnResponse(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); + + // load MOASession from database + AuthenticationSession moaSession = AuthenticationServer.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); + + // //////////// incorporate gender from parameters if not in stork response + + IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); + + // 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 tmp = new ArrayList(); + tmp.add(gendervalue); + gender.setValue(tmp); + + authnResponse.getPersonalAttributeList().add(gender); + } + } + } + + + + // //////////////////////////////////////////////////////////////////////// + + Logger.debug("Starting extraction of signedDoc attribute"); + // extract signed doc element and citizen signature + String citizenSignature = null; + try { + PersonalAttribute signedDoc = authnResponse.getPersonalAttributeList().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(authnResponse.getPersonalAttributeList()); + + 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 = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); + String acsURL = issuerValue + + PEPSConnectorWithLocalSigningServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; + + String url = acsURL + "?moaSessionID=" + newMOASessionID; + // redirect to OASIS module and sign there + + boolean found = false; + try { + List aps = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()).getStorkAPs(); + Logger.info("Found AttributeProviderPlugins:" + aps.size()); + for (AttributeProviderPlugin 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, authnResponse.getPersonalAttributeList(), 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) { + handleError(null, e, request, response, pendingRequestID); + + } catch (MOAIDException e) { + handleError(null, e, request, response, pendingRequestID); + + } catch (Exception e) { + Logger.error("PEPSConnector has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + + } + + 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", Base64.encodeBase64String(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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorTask.java new file mode 100644 index 000000000..0e4e2a0f7 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorTask.java @@ -0,0 +1,567 @@ +package at.gv.egovernment.moa.id.auth.tasks.stork; + +import iaik.x509.X509Certificate; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +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 com.datentechnik.process_engine.api.ExecutionContext; + +import eu.stork.documentservice.DocumentService; +import eu.stork.documentservice.data.DatabaseConnectorMySQLImpl; +import eu.stork.oasisdss.api.ApiUtils; +import eu.stork.oasisdss.api.LightweightSourceResolver; +import eu.stork.oasisdss.api.exceptions.ApiUtilsException; +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; +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +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.stork.STORKException; +import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; +import at.gv.egovernment.moa.id.auth.tasks.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.id.util.VelocityProvider; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.StringUtils; +import at.gv.util.xsd.xmldsig.SignatureType; +import at.gv.util.xsd.xmldsig.X509DataType; + +/** + * Evaluates the SAML response from the C-PEPS and authenticates the user. + *

      + * In detail: + *

        + *
      • Decodes and validates the SAML response from the C-PEPS.
      • + *
      • Change moa session id.
      • + *
      • Extracts the subject's gender from request parameter {@code gender} if not available from the saml response.
      • + *
      • Extracts the {@code signedDoc} attribute from the response, get signed doc payload using stork attribute query request.
      • + *
      • Request SZR gateway for verification of the citizen's signature and for creating of an identity link.
      • + *
      • 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).
      • + *
      • The moa session is updated with authentication information.
      • + *
      • Change moa session id.
      • + *
      • Redirects back to {@code /dispatcher} in order to finalize the authentication.
      • + *
      + * Expects: + *
        + *
      • HttpServletRequest parameter {@code SAMLResponse}
      • + *
      • Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute from the SAML response (both depicting the moa session id)
      • + *
      • HttpServletRequest parameter {@code gender} in case the request comes from the gender selection form
      • + *
      • {@code signedDoc} attribute within the SAML response.
      • + *
      + * Result: + *
        + *
      • Updated moa id session (identity link, stork attributes...)
      • + *
      • {@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.
      • + *
      • Redirect to {@code /dispatcher}.
      • + *
      + * Possible branches: + *
        + *
      • In case the szr gateway throws exception due to missing gender information: + *
          + *
        • Returns a form for gender selection with action url back to this servlet/task.
        • + *
        + *
      • + *
      + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet}.
      + * + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + */ +public class PepsConnectorTask extends AbstractAuthServletTask { + + private String dtlUrl = null; + + public PepsConnectorTask() { + super(); + 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(); + } + } + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws Exception { + 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.validateSTORKAuthnResponse(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); + + // load MOASession from database + AuthenticationSession moaSession = AuthenticationServer.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); + + // //////////// incorporate gender from parameters if not in stork response + + IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); + + // 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 tmp = new ArrayList(); + tmp.add(gendervalue); + gender.setValue(tmp); + + authnResponse.getPersonalAttributeList().add(gender); + } + } + } + + // //////////////////////////////////////////////////////////////////////// + + Logger.debug("Starting extraction of signedDoc attribute"); + // extract signed doc element and citizen signature + String citizenSignature = null; + try { + String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING + + Logger.debug("signatureInfo:" + signatureInfo); + + SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource( + new java.io.StringReader(signatureInfo))); + + // fetch signed doc + DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse); + if (ds == null) { + throw new ApiUtilsException("No datasource found in response"); + } + + InputStream incoming = ds.getInputStream(); + citizenSignature = IOUtils.toString(incoming); + incoming.close(); + + Logger.debug("citizenSignature:" + citizenSignature); + if (isDocumentServiceUsed(citizenSignature) == true) { + Logger.debug("Loading document from DocumentService."); + String url = getDtlUrlFromResponse(dssSignResponse); + // get Transferrequest + String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url); + // Load document from DocujmentService + 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) 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) 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); + // } + OAAuthParameter oaParam = AuthConfigurationProvider.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; + executionContext.put("identityLinkAvailable", false); + try { + identityLink = STORKResponseProcessor.connectToSZRGateway(authnResponse.getPersonalAttributeList(), + 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); + } + 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(authnResponse.getPersonalAttributeList()); + + 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); + + // TODO: found better solution, but QAA Level in response could be not 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) { + handleError(null, e, request, response, pendingRequestID); + + } catch (MOAIDException e) { + handleError(null, e, request, response, pendingRequestID); + + } catch (Exception e) { + Logger.error("PEPSConnector has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + + } + + private boolean isDocumentServiceUsed(String citizenSignature) // TODo add better check + { + if (citizenSignature + .contains("
      Service Name:{http://stork.eu}DocumentService
      Port Name:{http://stork.eu}DocumentServicePort
      ")) + return true; + 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 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 { + url = new URL(dtlUrl); + 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(dtlUrl)) + 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(dtlUrl); + 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); + } + } + +} -- cgit v1.2.3 From c7e846c52979756aa3c178d65f6d618c6189bd81 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Thu, 29 Jan 2015 11:20:53 +0100 Subject: Fix javadoc issues. --- .../moa/id/auth/servlet/ProcessEngineSignalServlet.java | 2 +- .../egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java | 4 ++-- .../egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java | 6 +++--- .../at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java | 6 +++--- .../at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java | 2 +- .../moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java | 2 +- .../moa/id/auth/tasks/VerifyAuthenticationBlockTask.java | 6 +++--- .../gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java | 8 ++++---- .../gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java | 6 +++--- .../moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java | 2 +- 10 files changed, 22 insertions(+), 22 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java index 849ccf5db..01f8e8949 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -50,7 +50,7 @@ public class ProcessEngineSignalServlet extends AuthServlet { /** * Resumes the current process instance that has been suspended due to an asynchronous task. The process instance is - * retrieved from the MOA session referred to by the request parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}. + * retrieved from the MOA session referred to by the request parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java index 29e9ac42f..8cd0db679 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java @@ -29,11 +29,11 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
        *
      • Renames the moa session id.
      • *
      • Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.
      • - *
      • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code {/VerifyCertificate}
      • + *
      • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code /VerifyCertificate}
      • *
      * Expects: *
        - *
      • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
      • + *
      • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
      • *
      * Result: *
        diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java index 01628dcf6..ff55eedeb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java @@ -30,14 +30,14 @@ import com.datentechnik.process_engine.api.ExecutionContext; * In detail: *
          *
        • Renames the moa session id.
        • - *
        • Removes ExecutionContext property {@link MOAIDAuthConstants#PARAM_SESSIONID}.
        • + *
        • Removes ExecutionContext property {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}.
        • *
        • Creates the http form mentioned above.
        • *
        • Returns the http form via HttpServletResponse.
        • *
        * Expects: *
          - *
        • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID} or
        • - *
        • ExecutionContext property {@link MOAIDAuthConstants#PARAM_SESSIONID} (in case of legacy authentication without CCE selection, where the moa session is not provided by request parameter).
        • + *
        • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID} or
        • + *
        • ExecutionContext property {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID} (in case of legacy authentication without CCE selection, where the moa session is not provided by request parameter).
        • *
        * Result: *
          diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java index 8e52e3827..2ce6a1ae8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java @@ -42,7 +42,7 @@ import com.datentechnik.process_engine.api.ExecutionContext; * In detail: *
            *
          • Renames the moa session id.
          • - *
          • Parses the CreateXMLSignatureResponse retrieved from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
          • + *
          • Parses the CreateXMLSignatureResponse retrieved from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
          • *
          • Extracts signature and signer certificate.
          • *
          • Send request to SZR Gateway in order to get an identity link.
          • *
          • Updates moa session (sets identity link, QAA level 4, authentication data and foreigner flag).
          • @@ -50,8 +50,8 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
          * Expects: *
            - *
          • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
          • - *
          • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
          • + *
          • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
          • + *
          • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
          • *
          * Result: *
            diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java index 626d33917..a7ee086af 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java @@ -47,7 +47,7 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
          * Expects: *
            - *
          • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
          • + *
          • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
          • *
          * Result: *
            diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java index 8b45f1c66..566616fcd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java @@ -31,7 +31,7 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
          * Expects: *
            - *
          • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
          • + *
          • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
          • *
          * Result: *
            diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java index 97f3a21cb..956ec9c88 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java @@ -45,15 +45,15 @@ import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; * In detail: *
              *
            • Renames the moa session id.
            • - *
            • Takes the {@code CreateXMLSignatureResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
            • + *
            • Takes the {@code CreateXMLSignatureResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
            • *
            • Verifies the {@code CreateXMLSignatureResponse}.
            • *
            • Updates moa session.
            • *
            • Redirects back to {@code /dispatcher} in order to finalize the authentication.
            • *
            * Expects: *
              - *
            • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
            • - *
            • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
            • + *
            • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
            • + *
            • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
            • *
            * Result: *
              diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java index 7e76819ff..854c78161 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java @@ -29,11 +29,11 @@ import at.gv.egovernment.moa.spss.util.CertificateUtils; import com.datentechnik.process_engine.api.ExecutionContext; /** - * Parses the certificate from {@code InfoBoxReadResponse} (via POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}), creates the auth block to be signed and returns a {@code CreateXMLSignatureRequest} for auth block signature.

              + * Parses the certificate from {@code InfoBoxReadResponse} (via POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}), creates the auth block to be signed and returns a {@code CreateXMLSignatureRequest} for auth block signature.

              * In detail: *

                *
              • Renames the moa session id.
              • - *
              • Retrieves the certificate via {@code InfoBoxReadResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
              • + *
              • Retrieves the certificate via {@code InfoBoxReadResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
              • *
              • Verifies the certificate.
              • *
              • Creates the auth block to be signed using information from the certificate (Organwalter, foreign citizen.
              • *
              • Puts it in a {@code CreateXMLSignatureRequest}.
              • @@ -42,8 +42,8 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
              * Expects: *
                - *
              • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
              • - *
              • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE} containing a {@code InfoBoxReadResponse}.
              • + *
              • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
              • + *
              • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_SESSIONID} containing a {@code InfoBoxReadResponse}.
              • *
              * Result: *
                diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java index 9711b4bc4..eb884e9db 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java @@ -28,15 +28,15 @@ import com.datentechnik.process_engine.api.ExecutionContext; * In detail: *
                  *
                • Renames the moa session id.
                • - *
                • Parses the identity link retrieved as {@code InfoBoxReadResponse} from POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}.
                • + *
                • Parses the identity link retrieved as {@code InfoBoxReadResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • *
                • Verifies the identity link.
                • *
                • Updates moa session.
                • *
                • Puts boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.
                • *
                * Expects: *
                  - *
                • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
                • - *
                • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE} containing a {@code InfoBoxReadResponse}.
                • + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code InfoBoxReadResponse}.
                • *
                * Result: *
                  diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java index c32c9d791..3894567ed 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java @@ -42,7 +42,7 @@ import com.datentechnik.process_engine.api.ExecutionContext; *
                * Expects: *
                  - *
                • HttpServletRequest parameter {@link MOAIDAuthConstants#PARAM_SESSIONID}
                • + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • *
                • Property {@code ccc} set within the moa session.
                • *
                * Result: -- cgit v1.2.3 From 90c4f8e9a6140b97469357deb906b8816f5f680c Mon Sep 17 00:00:00 2001 From: Gerwin Gsenger Date: Thu, 29 Jan 2015 12:18:11 +0100 Subject: integrate process engine from project 'dti-process-engine' --- .../moa/id/auth/servlet/AuthServlet.java | 3 +- .../servlet/GenerateIFrameTemplateServlet.java | 7 +- .../auth/servlet/ProcessEngineSignalServlet.java | 3 +- .../moa/id/auth/tasks/AbstractAuthServletTask.java | 11 +- .../id/auth/tasks/CertificateReadRequestTask.java | 7 +- .../id/auth/tasks/CreateIdentityLinkFormTask.java | 5 +- .../moa/id/auth/tasks/GetForeignIDTask.java | 8 +- .../moa/id/auth/tasks/GetMISSessionIDTask.java | 7 +- .../auth/tasks/PrepareAuthBlockSignatureTask.java | 6 +- .../auth/tasks/VerifyAuthenticationBlockTask.java | 8 +- .../moa/id/auth/tasks/VerifyCertificateTask.java | 7 +- .../moa/id/auth/tasks/VerifyIdentityLinkTask.java | 5 +- .../moa/id/moduls/AuthenticationManager.java | 11 +- .../id/moduls/moduleregistration/AuthModule.java | 4 +- .../moduls/moduleregistration/AuthModuleImpl.java | 2 +- .../moduleregistration/ModuleRegistration.java | 6 +- .../moa/id/process/ExecutionContextImpl.java | 2 +- .../process/ExpressionEvaluationContextImpl.java | 4 +- .../moa/id/process/ProcessDefinitionParser.java | 12 +- .../egovernment/moa/id/process/ProcessEngine.java | 4 +- .../moa/id/process/ProcessEngineImpl.java | 20 +-- .../moa/id/process/ProcessInstance.java | 6 +- .../process/api/ExpressionEvaluationContext.java | 2 +- .../moa/id/process/dao/ProcessInstanceStore.java | 48 ++++++++ .../moa/id/process/model/ProcessDefinition.java | 2 +- .../moa/id/process/model/ProcessNode.java | 2 +- .../egovernment/moa/id/process/model/TaskInfo.java | 2 +- .../moa/id/process/model/Transition.java | 2 +- .../process/spring/SpringExpressionEvaluator.java | 6 +- .../springweb/AbstractAuthSourceServlet.java | 6 +- .../springweb/AbstractSpringWebSupportedTask.java | 4 +- .../springweb/SpringWebExpressionEvaluator.java | 137 +++++++++++++++++++++ 32 files changed, 275 insertions(+), 84 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java index 404dc68af..331a7653a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java @@ -79,6 +79,7 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; +import at.gv.egovernment.moa.id.process.ProcessEngine; import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; import at.gv.egovernment.moa.id.storage.IExceptionStore; import at.gv.egovernment.moa.id.util.ServletUtils; @@ -86,8 +87,6 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLDecoder; -import com.datentechnik.process_engine.ProcessEngine; - /** * Base class for MOA-ID Auth Servlets, providing standard error handling and * constant names. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index 6e817e2a5..7f53a1a13 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -42,15 +42,14 @@ import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.moduleregistration.ModuleRegistration; +import at.gv.egovernment.moa.id.process.ExecutionContextImpl; +import at.gv.egovernment.moa.id.process.ProcessInstance; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; -import com.datentechnik.process_engine.ExecutionContextImpl; -import com.datentechnik.process_engine.ProcessInstance; -import com.datentechnik.process_engine.api.ExecutionContext; - public class GenerateIFrameTemplateServlet extends AuthServlet { private static final long serialVersionUID = 1L; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java index 849ccf5db..c172124d2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -13,10 +13,9 @@ import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; +import at.gv.egovernment.moa.id.process.ProcessInstance; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import com.datentechnik.process_engine.ProcessInstance; - /** * Servlet that resumes a suspended process (in case of asynchronous tasks). * diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java index 7351933c1..a5c30485d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java @@ -1,6 +1,12 @@ package at.gv.egovernment.moa.id.auth.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_CACHE_CONTROL; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_EXPIRES; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_PRAGMA; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_EXPIRES; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_PRAGMA; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -32,14 +38,13 @@ import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; +import at.gv.egovernment.moa.id.process.springweb.AbstractSpringWebSupportedTask; import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; import at.gv.egovernment.moa.id.storage.IExceptionStore; import at.gv.egovernment.moa.id.util.ServletUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -import com.datentechnik.process_engine.springweb.AbstractSpringWebSupportedTask; - /** * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing * etc.).

                The code has been taken from {@link AuthServlet}. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java index da8a3d997..f62c49063 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.auth.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.REQ_VERIFY_CERTIFICATE; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -9,6 +10,7 @@ import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.BooleanUtils; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -16,13 +18,12 @@ 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.commons.db.ConfigurationDBUtils; +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.ServletUtils; import at.gv.egovernment.moa.logging.Logger; -import com.datentechnik.process_engine.api.ExecutionContext; - /** * Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.

                * In detail: diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java index 70afd477d..435c77092 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java @@ -1,6 +1,6 @@ package at.gv.egovernment.moa.id.auth.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; import java.io.PrintWriter; @@ -18,13 +18,12 @@ import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.servlet.GenerateIFrameTemplateServlet; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.StringUtils; -import com.datentechnik.process_engine.api.ExecutionContext; - /** * Creates a http form including an embedded {@code InfoBoxReadRequest} for reading the identity link.

                * In detail: diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java index 602ad527b..2f361fa43 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java @@ -1,6 +1,8 @@ package at.gv.egovernment.moa.id.auth.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_XMLRESPONSE; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.REQ_VERIFY_AUTH_BLOCK; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -16,6 +18,7 @@ import org.apache.commons.lang.StringEscapeUtils; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse; @@ -28,6 +31,7 @@ import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; import at.gv.egovernment.moa.id.client.SZRGWClientException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.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.ParamValidatorUtils; @@ -35,8 +39,6 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; -import com.datentechnik.process_engine.api.ExecutionContext; - /** * Evaluates the {@code CreateXMLSignatureResponse}, extracts signature and certificate and asks the SZR Gateway for an identity link.

                * In detail: diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java index 40e33ae43..0bc01191b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.auth.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.GET_MIS_SESSIONID; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; import iaik.pki.PKIException; import java.security.GeneralSecurityException; @@ -15,6 +16,7 @@ import org.apache.commons.lang.StringEscapeUtils; import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; @@ -24,6 +26,7 @@ import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.moduls.ModulUtils; +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.ParamValidatorUtils; @@ -33,8 +36,6 @@ import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; -import com.datentechnik.process_engine.api.ExecutionContext; - /** * Retrieves a mandate from the online mandate issuing service.

                * In detail: diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java index 30777198c..fec5531ae 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java @@ -1,6 +1,6 @@ package at.gv.egovernment.moa.id.auth.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -8,19 +8,19 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +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.ServletUtils; import at.gv.egovernment.moa.logging.Logger; -import com.datentechnik.process_engine.api.ExecutionContext; - /** * Creates {@code CreateXMLSignatureRequest} for auth block signature.

                * In detail: diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java index 2bc0bb8ad..287965097 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java @@ -1,5 +1,8 @@ package at.gv.egovernment.moa.id.auth.tasks; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.GET_MIS_SESSIONID; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_XMLRESPONSE; import iaik.pki.PKIException; import java.io.IOException; @@ -17,6 +20,7 @@ import org.apache.commons.lang.StringEscapeUtils; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; @@ -29,6 +33,7 @@ import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.ModulUtils; +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.SSLUtils; @@ -37,9 +42,6 @@ import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; -import com.datentechnik.process_engine.api.ExecutionContext; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - /** * Verifies the signed authentication block (provided as {@code CreateXMLSignatureResponse}).

                * In detail: diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java index ddea4c414..bf4292c15 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.auth.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.REQ_GET_FOREIGN_ID; import iaik.x509.X509Certificate; import java.io.IOException; @@ -13,6 +14,7 @@ import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.lang.StringEscapeUtils; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; @@ -20,14 +22,13 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +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.ServletUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.spss.util.CertificateUtils; -import com.datentechnik.process_engine.api.ExecutionContext; - /** * Parses the certificate from {@code InfoBoxReadResponse} (via POST parameter {@link MOAIDAuthConstants#PARAM_XMLRESPONSE}), creates the auth block to be signed and returns a {@code CreateXMLSignatureRequest} for auth block signature.

                * In detail: diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java index 5b21cd29c..d70b89d71 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java @@ -1,6 +1,6 @@ package at.gv.egovernment.moa.id.auth.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; import java.io.IOException; import java.util.Map; @@ -17,12 +17,11 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +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.logging.Logger; -import com.datentechnik.process_engine.api.ExecutionContext; - /** * Verifies the identity link.

                * In detail: diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 1a0c11aa1..ffb5e3d65 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -77,6 +77,11 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.SLOInformationContainer; import at.gv.egovernment.moa.id.data.SLOInformationImpl; import at.gv.egovernment.moa.id.moduls.moduleregistration.ModuleRegistration; +import at.gv.egovernment.moa.id.process.ExecutionContextImpl; +import at.gv.egovernment.moa.id.process.ProcessEngine; +import at.gv.egovernment.moa.id.process.ProcessExecutionException; +import at.gv.egovernment.moa.id.process.ProcessInstance; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; @@ -95,12 +100,6 @@ import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -import com.datentechnik.process_engine.ExecutionContextImpl; -import com.datentechnik.process_engine.ProcessEngine; -import com.datentechnik.process_engine.ProcessExecutionException; -import com.datentechnik.process_engine.ProcessInstance; -import com.datentechnik.process_engine.api.ExecutionContext; - public class AuthenticationManager implements MOAIDAuthConstants { private static final AuthenticationManager INSTANCE = new AuthenticationManager(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java index 35273cd2b..6c9981feb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java @@ -1,7 +1,7 @@ package at.gv.egovernment.moa.id.moduls.moduleregistration; -import com.datentechnik.process_engine.api.ExecutionContext; -import com.datentechnik.process_engine.model.ProcessDefinition; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.model.ProcessDefinition; /** * Defines the module capabilities. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java index cbe5c5932..68835f208 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java @@ -1,6 +1,6 @@ package at.gv.egovernment.moa.id.moduls.moduleregistration; -import com.datentechnik.process_engine.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; public class AuthModuleImpl implements AuthModule { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java index b90e0d94f..5faae2897 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java @@ -19,9 +19,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.core.io.Resource; -import com.datentechnik.process_engine.ProcessDefinitionParserException; -import com.datentechnik.process_engine.ProcessEngine; -import com.datentechnik.process_engine.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.ProcessDefinitionParserException; +import at.gv.egovernment.moa.id.process.ProcessEngine; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** * This class handles registering modules. The modules are detected either with diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java index 87ee57a24..080990f71 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java @@ -6,7 +6,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; -import com.datentechnik.process_engine.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** * ExecutionContext implementation, related to a certain process instance. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java index acc10449f..f0d1c861d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java @@ -6,8 +6,8 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; -import com.datentechnik.process_engine.api.ExecutionContext; -import com.datentechnik.process_engine.api.ExpressionEvaluationContext; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; /** * Context implementation used for expression evaluation only. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java index b38bb7aa0..6b245f013 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java @@ -27,12 +27,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; -import com.datentechnik.process_engine.model.EndEvent; -import com.datentechnik.process_engine.model.ProcessDefinition; -import com.datentechnik.process_engine.model.ProcessNode; -import com.datentechnik.process_engine.model.StartEvent; -import com.datentechnik.process_engine.model.TaskInfo; -import com.datentechnik.process_engine.model.Transition; +import at.gv.egovernment.moa.id.process.model.EndEvent; +import at.gv.egovernment.moa.id.process.model.ProcessDefinition; +import at.gv.egovernment.moa.id.process.model.ProcessNode; +import at.gv.egovernment.moa.id.process.model.StartEvent; +import at.gv.egovernment.moa.id.process.model.TaskInfo; +import at.gv.egovernment.moa.id.process.model.Transition; /** * Parses an XML representation of a process definition as defined by the respective XML schema. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java index b4135ee41..2d9dcff8e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java @@ -4,8 +4,8 @@ package at.gv.egovernment.moa.id.process; import java.io.InputStream; import java.io.Serializable; -import com.datentechnik.process_engine.api.ExecutionContext; -import com.datentechnik.process_engine.model.ProcessDefinition; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.model.ProcessDefinition; /** * Process engine providing means for starting and resuming processes. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java index 8f9d73b3d..3ba8fb9ed 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java @@ -16,16 +16,16 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; -import com.datentechnik.process_engine.api.ExecutionContext; -import com.datentechnik.process_engine.api.ExpressionEvaluationContext; -import com.datentechnik.process_engine.api.ExpressionEvaluator; -import com.datentechnik.process_engine.api.Task; -import com.datentechnik.process_engine.model.EndEvent; -import com.datentechnik.process_engine.model.ProcessDefinition; -import com.datentechnik.process_engine.model.ProcessNode; -import com.datentechnik.process_engine.model.StartEvent; -import com.datentechnik.process_engine.model.TaskInfo; -import com.datentechnik.process_engine.model.Transition; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; +import at.gv.egovernment.moa.id.process.api.ExpressionEvaluator; +import at.gv.egovernment.moa.id.process.api.Task; +import at.gv.egovernment.moa.id.process.model.EndEvent; +import at.gv.egovernment.moa.id.process.model.ProcessDefinition; +import at.gv.egovernment.moa.id.process.model.ProcessNode; +import at.gv.egovernment.moa.id.process.model.StartEvent; +import at.gv.egovernment.moa.id.process.model.TaskInfo; +import at.gv.egovernment.moa.id.process.model.Transition; /** * Process engine implementation allowing starting and continuing processes as well as providing means for cleanup actions. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java index 0899426ca..ef69451eb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java @@ -6,9 +6,9 @@ import java.util.Date; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.time.DurationFormatUtils; -import com.datentechnik.process_engine.api.ExecutionContext; -import com.datentechnik.process_engine.model.ProcessDefinition; -import com.datentechnik.process_engine.support.SecureRandomHolder; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.model.ProcessDefinition; +import at.gv.egovernment.moa.id.process.support.SecureRandomHolder; /** * Represents a process being executed. The process instance provides information about the process and its state. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java index bb3b267cf..94854dcad 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java @@ -3,7 +3,7 @@ package at.gv.egovernment.moa.id.process.api; import java.io.Serializable; import java.util.Map; -import com.datentechnik.process_engine.model.Transition; +import at.gv.egovernment.moa.id.process.model.Transition; /** * Context used for evaluation of condition expressions set for {@linkplain Transition Transitions}. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java new file mode 100644 index 000000000..5270e036a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -0,0 +1,48 @@ +package at.gv.egovernment.moa.id.process.dao; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.Table; + +@Entity +@Table(name = "process_instance") +public class ProcessInstanceStore { + + @Column(name = "id", unique = true, nullable = false) + @Id + private String id; + + @Column(name = "processDefinitionID", unique = true, nullable = false) + private String processDefinitionID; + + @Column(name = "executionContextData", nullable = false) + @Lob + private byte[] executionContextData; + + public String getId() { + return id; + } + + public String getProcessDefinitionID() { + return processDefinitionID; + } + + public byte[] getExecutionContextData() { + return executionContextData; + } + + public void setId(String id) { + this.id = id; + } + + public void setProcessDefinitionID(String processDefinitionID) { + this.processDefinitionID = processDefinitionID; + } + + public void setExecutionContextData(byte[] executionContextData) { + this.executionContextData = executionContextData; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java index 19e78b0e6..518409ecf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java @@ -4,7 +4,7 @@ import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; -import com.datentechnik.process_engine.ProcessDefinitionParser; +import at.gv.egovernment.moa.id.process.ProcessDefinitionParser; /** * Represents a single process definition containing diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java index a94d33943..42f2e3cc2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java @@ -3,7 +3,7 @@ package at.gv.egovernment.moa.id.process.model; import java.util.ArrayList; import java.util.List; -import com.datentechnik.process_engine.ProcessDefinitionParser; +import at.gv.egovernment.moa.id.process.ProcessDefinitionParser; /** * Represents a {@link StartEvent}, an {@link EndEvent} or a {@linkplain TaskInfo Task}. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java index b7f13a880..78a9d6a0a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java @@ -4,7 +4,7 @@ import java.io.Serializable; import org.apache.commons.collections4.CollectionUtils; -import com.datentechnik.process_engine.api.Task; +import at.gv.egovernment.moa.id.process.api.Task; /** * Represents information about a single task to be performed upon process execution. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java index 9d9c44c8c..bc3005534 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java @@ -2,7 +2,7 @@ package at.gv.egovernment.moa.id.process.model; import java.io.Serializable; -import com.datentechnik.process_engine.ProcessDefinitionParser; +import at.gv.egovernment.moa.id.process.ProcessDefinitionParser; /** * Represents a single transition from a {@link StartEvent} or {@linkplain TaskInfo Task} to another diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java index 1c91cf780..5b30c7172 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java @@ -15,9 +15,9 @@ import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -import com.datentechnik.process_engine.api.ExpressionEvaluationContext; -import com.datentechnik.process_engine.api.ExpressionEvaluator; -import com.datentechnik.process_engine.model.Transition; +import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; +import at.gv.egovernment.moa.id.process.api.ExpressionEvaluator; +import at.gv.egovernment.moa.id.process.model.Transition; /** * Expression evaluator for processing {@link Transition} conditions allowing to reference Spring beans from the diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java index 4b5af854e..738b58834 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java @@ -10,9 +10,9 @@ import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; -import com.datentechnik.process_engine.ProcessEngine; -import com.datentechnik.process_engine.ProcessInstance; -import com.datentechnik.process_engine.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.ProcessEngine; +import at.gv.egovernment.moa.id.process.ProcessInstance; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** * Abstract HttpServlet that provides means for retrieving the process engine (Spring Web required) as well as diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java index 1f7fb7690..c9262cea9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java @@ -8,8 +8,8 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.filter.RequestContextFilter; -import com.datentechnik.process_engine.api.ExecutionContext; -import com.datentechnik.process_engine.api.Task; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.api.Task; /** * Abstract task implementation providing {@link HttpServletRequest} and {@link HttpServletResponse}. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java new file mode 100644 index 000000000..9dd7bc61e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java @@ -0,0 +1,137 @@ +package at.gv.egovernment.moa.id.process.springweb; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Objects; + +import javax.annotation.PostConstruct; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.expression.BeanFactoryResolver; +import org.springframework.expression.Expression; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.expression.spel.support.StandardEvaluationContext; + +import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; +import at.gv.egovernment.moa.id.process.api.ExpressionEvaluator; +import at.gv.egovernment.moa.id.process.model.Transition; + +/** + * Expression evaluator for processing {@link Transition} conditions allowing to + *

                  + *
                • reference Spring beans from the application context using {@code @myBeanName...},
                • + *
                • {@link ExecutionContext} properties using {@code ctx['property']},
                • + *
                • Multi valued {@link HttpServletRequest} parameters using {@code requestParameters['foo']} (keep in mind that this + * expression returns an array of String values) and
                • + *
                • Single valued {@link HttpServletRequest} parameters using {@code requestParameter['foo']}
                • + *
                + * + * @author tknall + * + */ +public class SpringWebExpressionEvaluator implements ExpressionEvaluator { + + private Logger log = LoggerFactory.getLogger(getClass()); + private ExpressionParser parser = new SpelExpressionParser(); + private StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); + + @Autowired(required = false) + private ApplicationContext ctx; + + @Autowired(required = false) + private HttpServletRequest request; + + @PostConstruct + private void init() { + if (ctx != null) { + evaluationContext.setBeanResolver(new BeanFactoryResolver(ctx)); + } + } + + /** + * Evaluation context that provides access to {@link HttpServletRequest} parameters using + * {@code requestParameter['foo']} for single value parameters or {@code requestParameters['foo']} for multi value + * parameters. Basic calls to {@code ctx} will be delegated. + * + * @author tknall + * + */ + private class SpringWebExpressionEvaluationContext implements ExpressionEvaluationContext { + + private static final long serialVersionUID = 1L; + + /** + * Creates a new expression evaluation context, providing access to HttpServletRequest parameter(s). + * + * @param delegate + * The original {@link ExpressionEvaluationContext} to be delegated to for {@code ctx['foo']} + * expressions. + */ + public SpringWebExpressionEvaluationContext(ExpressionEvaluationContext delegate) { + this.delegate = delegate; + } + + private ExpressionEvaluationContext delegate; + + @Override + public Map getCtx() { + return delegate.getCtx(); + } + + @SuppressWarnings("unused") + public Map getRequestParameter() { + if (request != null) { + Map singleValueMap = new HashMap(); + Iterator> it = request.getParameterMap().entrySet().iterator(); + while (it.hasNext()) { + Entry entry = it.next(); + if (ArrayUtils.isNotEmpty(entry.getValue())) { + singleValueMap.put(entry.getKey(), entry.getValue()[0]); + } + } + return singleValueMap; + } else { + return Collections. emptyMap(); + } + } + + @SuppressWarnings("unused") + public Map getRequestParameters() { + if (request != null) { + return request.getParameterMap(); + } else { + return Collections. emptyMap(); + } + } + + } + + @Override + public boolean evaluate(ExpressionEvaluationContext expressionContext, String expression) { + Objects.requireNonNull(expression, "Expression must not be null."); + log.trace("Evaluating '{}'.", expression); + + Expression expr = parser.parseExpression(expression); + Boolean result = expr.getValue(evaluationContext, new SpringWebExpressionEvaluationContext(expressionContext), + Boolean.class); + if (result == null) { + log.warn("Evaluation of '{}' results in null-value.", expression); + } else { + log.debug("Expression '{}' -> {}", expression, result); + } + + return BooleanUtils.isTrue(result); + } + +} -- cgit v1.2.3 From a3002d5966703675e982f5699b7a829d2dc22d84 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Thu, 29 Jan 2015 13:47:36 +0100 Subject: Integrate processes with module discovery. - Fix AuthModuleImpl process resource uri. - Create package at.gv.egovernment.moa.id.auth.modules with submodule "internal" and "stork". - Rename AuthModuleImpl to DefaultAuthModuleImpl (placed in at.gv.egovernment.moa.id.auth.modules.internal). - Move stork specific tasks to "...stork.tasks" and internal modules to "...internal.tasks". - Fix bean classes in applicationContext.xml - Move process descriptions to at.gv.egovernment.moa.id.auth.modules.[internal|stork]. - Add STORKAuthModuleImpl. --- .../modules/internal/DefaultAuthModuleImpl.java | 27 + .../internal/tasks/AbstractAuthServletTask.java | 379 ++++++++++++++ .../internal/tasks/CertificateReadRequestTask.java | 101 ++++ .../internal/tasks/CreateIdentityLinkFormTask.java | 120 +++++ .../modules/internal/tasks/GetForeignIDTask.java | 182 +++++++ .../internal/tasks/GetMISSessionIDTask.java | 181 +++++++ .../tasks/PrepareAuthBlockSignatureTask.java | 102 ++++ .../tasks/VerifyAuthenticationBlockTask.java | 246 +++++++++ .../internal/tasks/VerifyCertificateTask.java | 164 ++++++ .../internal/tasks/VerifyIdentityLinkTask.java | 103 ++++ .../id/auth/modules/stork/STORKAuthModuleImpl.java | 27 + .../AbstractPepsConnectorWithLocalSigningTask.java | 257 ++++++++++ .../tasks/CreateStorkAuthRequestFormTask.java | 114 +++++ .../PepsConnectorHandleLocalSignResponseTask.java | 218 ++++++++ ...onnectorHandleResponseWithoutSignatureTask.java | 441 ++++++++++++++++ .../modules/stork/tasks/PepsConnectorTask.java | 567 +++++++++++++++++++++ .../moa/id/auth/servlet/GetForeignIDServlet.java | 2 +- .../id/auth/servlet/GetMISSessionIDServlet.java | 2 +- .../moa/id/auth/servlet/PEPSConnectorServlet.java | 2 +- .../PEPSConnectorWithLocalSigningServlet.java | 2 +- .../servlet/VerifyAuthenticationBlockServlet.java | 2 +- .../id/auth/servlet/VerifyCertificateServlet.java | 2 +- .../id/auth/servlet/VerifyIdentityLinkServlet.java | 2 +- .../moa/id/auth/tasks/AbstractAuthServletTask.java | 379 -------------- .../id/auth/tasks/CertificateReadRequestTask.java | 101 ---- .../id/auth/tasks/CreateIdentityLinkFormTask.java | 120 ----- .../moa/id/auth/tasks/GetForeignIDTask.java | 182 ------- .../moa/id/auth/tasks/GetMISSessionIDTask.java | 181 ------- .../auth/tasks/PrepareAuthBlockSignatureTask.java | 102 ---- .../auth/tasks/VerifyAuthenticationBlockTask.java | 246 --------- .../moa/id/auth/tasks/VerifyCertificateTask.java | 164 ------ .../moa/id/auth/tasks/VerifyIdentityLinkTask.java | 103 ---- .../AbstractPepsConnectorWithLocalSigningTask.java | 258 ---------- .../stork/CreateStorkAuthRequestFormTask.java | 114 ----- .../PepsConnectorHandleLocalSignResponseTask.java | 218 -------- ...onnectorHandleResponseWithoutSignatureTask.java | 441 ---------------- .../moa/id/auth/tasks/stork/PepsConnectorTask.java | 567 --------------------- .../moduls/moduleregistration/AuthModuleImpl.java | 23 - .../moduleregistration/ModuleRegistration.java | 29 +- 39 files changed, 3251 insertions(+), 3220 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/AbstractAuthServletTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/AbstractPepsConnectorWithLocalSigningTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleLocalSignResponseTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleResponseWithoutSignatureTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java new file mode 100644 index 000000000..99c28fd7f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java @@ -0,0 +1,27 @@ +package at.gv.egovernment.moa.id.auth.modules.internal; + +import org.apache.commons.lang3.StringUtils; + +import at.gv.egovernment.moa.id.moduls.moduleregistration.AuthModule; + +import com.datentechnik.process_engine.api.ExecutionContext; + +public class DefaultAuthModuleImpl implements AuthModule { + + @Override + public int getPriority() { + // neutral priority between Integer.MIN_VALUE and Integer.MAX_VALUE + return 0; + } + + @Override + public String selectProcess(ExecutionContext context) { + return StringUtils.isBlank((String) context.get("ccc")) ? "DefaultAuthentication" : null; + } + + @Override + public String[] getProcessDefinitions() { + return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml" }; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/AbstractAuthServletTask.java new file mode 100644 index 000000000..8a6c58953 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/AbstractAuthServletTask.java @@ -0,0 +1,379 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.lang3.ArrayUtils; + +import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; +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.servlet.AuthServlet; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; +import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; +import at.gv.egovernment.moa.id.storage.IExceptionStore; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +import com.datentechnik.process_engine.springweb.AbstractSpringWebSupportedTask; + +/** + * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing + * etc.).

                The code has been taken from {@link AuthServlet}. + */ +public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask { + + protected static final String ERROR_CODE_PARAM = "errorid"; + + protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp) { + + if (null != errorMessage) { + Logger.error(errorMessage); + req.setAttribute("ErrorMessage", errorMessage); + } + + if (null != exceptionThrown) { + if (null == errorMessage) + errorMessage = exceptionThrown.getMessage(); + Logger.error(errorMessage, exceptionThrown); + req.setAttribute("ExceptionThrown", exceptionThrown); + } + + if (Logger.isDebugEnabled()) { + req.setAttribute("LogLevel", "debug"); + } + + + StatisticLogger logger = StatisticLogger.getInstance(); + logger.logErrorOperation(exceptionThrown); + + + // forward this to errorpage-auth.jsp where the HTML error page is + // generated + ServletContext context = req.getServletContext(); + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); + + dispatcher.forward(req, resp); + } catch (ServletException e) { + Logger.error(e); + } catch (IOException e) { + Logger.error(e); + } + } + + /** + * Handles an error.
                > + *
                  + *
                • Logs the error
                • + *
                • Places error message and exception thrown into the request as request + * attributes (to be used by "/errorpage-auth.jsp")
                • + *
                • Sets HTTP status 500 (internal server error)
                • + *
                + * + * @param errorMessage + * error message + * @param exceptionThrown + * exception thrown + * @param req + * servlet request + * @param resp + * servlet response + */ + protected void handleError(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { + + if (null != errorMessage) { + Logger.error(errorMessage); + req.setAttribute("ErrorMessage", errorMessage); + } + + if (null != exceptionThrown) { + if (null == errorMessage) + errorMessage = exceptionThrown.getMessage(); + Logger.error(errorMessage, exceptionThrown); + req.setAttribute("ExceptionThrown", exceptionThrown); + } + + if (Logger.isDebugEnabled()) { + req.setAttribute("LogLevel", "debug"); + } + + if (!(exceptionThrown instanceof MOAIDException)) { + Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown); + + } + + IExceptionStore store = DBExceptionStoreImpl.getStore(); + String id = store.storeException(exceptionThrown); + + if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { + + String redirectURL = null; + + redirectURL = ServletUtils.getBaseUrl(req); + redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id + + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + return; + + } else { + + //Exception can not be stored in database + handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); + } + } + + /** + * Handles a WrongParametersException. + * + * @param req + * servlet request + * @param resp + * servlet response + */ + protected void handleWrongParameters(WrongParametersException ex, + HttpServletRequest req, HttpServletResponse resp) { + Logger.error(ex.toString()); + req.setAttribute("WrongParameters", ex.getMessage()); + + // forward this to errorpage-auth.jsp where the HTML error page is + // generated + ServletContext context = req.getServletContext(); + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + setNoCachingHeaders(resp); + dispatcher.forward(req, resp); + } catch (ServletException e) { + Logger.error(e); + } catch (IOException e) { + Logger.error(e); + } + } + + /** + * Logs all servlet parameters for debugging purposes. + */ + protected void logParameters(HttpServletRequest req) { + for (Enumeration params = req.getParameterNames(); params + .hasMoreElements();) { + String parname = (String) params.nextElement(); + Logger.debug("Parameter " + parname + req.getParameter(parname)); + } + } + + /** + * Parses the request input stream for parameters, assuming parameters are + * encoded UTF-8 (no standard exists how browsers should encode them). + * + * @param req + * servlet request + * + * @return mapping parameter name -> value + * + * @throws IOException + * if parsing request parameters fails. + * + * @throws FileUploadException + * if parsing request parameters fails. + */ + protected Map getParameters(HttpServletRequest req) throws IOException, + FileUploadException { + + Map parameters = new HashMap(); + + if (ServletFileUpload.isMultipartContent(req)) { + // request is encoded as mulitpart/form-data + FileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload upload = null; + upload = new ServletFileUpload(factory); + List items = null; + items = upload.parseRequest(req); + for (int i = 0; i < items.size(); i++) { + FileItem item = (FileItem) items.get(i); + if (item.isFormField()) { + // Process only form fields - no file upload items + String logString = item.getString("UTF-8"); + + // TODO use RegExp + String startS = ""; + String endS = "urn:publicid:gv.at:baseid"; + String logWithMaskedBaseid = logString; + int start = logString.indexOf(startS); + if (start > -1) { + int end = logString.indexOf(endS); + if (end > -1) { + logWithMaskedBaseid = logString.substring(0, start); + logWithMaskedBaseid += startS; + logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; + logWithMaskedBaseid += logString.substring(end, + logString.length()); + } + } + parameters + .put(item.getFieldName(), item.getString("UTF-8")); + Logger.debug("Processed multipart/form-data request parameter: \nName: " + + item.getFieldName() + + "\nValue: " + + logWithMaskedBaseid); + } + } + } + + else { + // request is encoded as application/x-www-urlencoded + // [tknall]: we must not consume request body input stream once servlet-api request parameters have been accessed + + /* + InputStream in = req.getInputStream(); + + String paramName; + String paramValueURLEncoded; + do { + paramName = new String(readBytesUpTo(in, '=')); + if (paramName.length() > 0) { + paramValueURLEncoded = readBytesUpTo(in, '&'); + String paramValue = URLDecoder.decode(paramValueURLEncoded, + "UTF-8"); + parameters.put(paramName, paramValue); + } + } while (paramName.length() > 0); + in.close(); + */ + + Iterator> requestParamIt = req.getParameterMap().entrySet().iterator(); + while (requestParamIt.hasNext()) { + Entry entry = requestParamIt.next(); + String key = entry.getKey(); + String[] values = entry.getValue(); + // take the last value from the value array since the legacy code above also does it this way + parameters.put(key, ArrayUtils.isEmpty(values) ? null : values[values.length-1]); + } + + } + + return parameters; + } + + /** + * Reads bytes up to a delimiter, consuming the delimiter. + * + * @param in + * input stream + * @param delimiter + * delimiter character + * @return String constructed from the read bytes + * @throws IOException + */ + protected String readBytesUpTo(InputStream in, char delimiter) + throws IOException { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + boolean done = false; + int b; + while (!done && (b = in.read()) >= 0) { + if (b == delimiter) + done = true; + else + bout.write(b); + } + return bout.toString(); + } + + /** + * Sets response headers that prevent caching (code taken from {@link AuthServlet}). + * + * @param resp + * The HttpServletResponse. + */ + public void setNoCachingHeaders(HttpServletResponse resp) { + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); + } + + /** + * Adds a parameter to a URL. + * + * @param url + * the URL + * @param paramname + * parameter name + * @param paramvalue + * parameter value + * @return the URL with parameter added + */ + protected static String addURLParameter(String url, String paramname, + String paramvalue) { + String param = paramname + "=" + paramvalue; + if (url.indexOf("?") < 0) + return url + "?" + param; + else + return url + "&" + param; + } + + /** + * Checks if HTTP requests are allowed + * + * @param authURL + * requestURL + * @throws AuthenticationException + * if HTTP requests are not allowed + * @throws ConfigurationException + */ + protected void checkIfHTTPisAllowed(String authURL) + throws AuthenticationException, ConfigurationException { + // check if HTTP Connection may be allowed (through + // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) + + //Removed from MOA-ID 2.0 config +// String boolStr = AuthConfigurationProvider +// .getInstance() +// .getGenericConfigurationParameter( +// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); + if ((!authURL.startsWith("https:")) + //&& (false == BoolUtils.valueOf(boolStr)) + ) + throw new AuthenticationException("auth.07", new Object[] { authURL + + "*" }); + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java new file mode 100644 index 000000000..4af07950b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java @@ -0,0 +1,101 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.BooleanUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; +import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; +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.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.

                + * In detail: + *

                  + *
                • Renames the moa session id.
                • + *
                • Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.
                • + *
                • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code /VerifyCertificate}
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                + * Result: + *
                  + *
                • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code {/VerifyCertificate}
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class CertificateReadRequestTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + // TODO[branch]: Foreign citizen or mandate mode; respond with IRR for certificates, dataURL = "/VerifyCertificate" + Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); + + setNoCachingHeaders(resp); + + String pendingRequestID = null; + + try { + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("CertificateReadRequestTask", PARAM_SESSIONID, "auth.12"); + } + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + boolean useMandate = session.getUseMandate(); + boolean identityLinkAvailable = BooleanUtils.isTrue((Boolean) executionContext.get("identityLinkAvailable")); + + if (!identityLinkAvailable && useMandate) { + Logger.error("Online-Mandate Mode for foreign citizencs not supported."); + throw new AuthenticationException("auth.13", null); + } + + // change MOASessionID + AuthenticationSessionStoreage.changeSessionID(session); + + // create the InfoboxReadRequest to get the certificate + String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); + + // build dataurl (to the VerifyCertificateSerlvet) + String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, + session.getSessionID()); + + ServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest, + AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + } finally { + ConfigurationDBUtils.closeSession(); + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java new file mode 100644 index 000000000..d88042528 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java @@ -0,0 +1,120 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import java.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.ObjectUtils; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +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.servlet.GenerateIFrameTemplateServlet; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import at.gv.egovernment.moa.util.StringUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Creates a http form including an embedded {@code InfoBoxReadRequest} for reading the identity link.

                + * In detail: + *

                  + *
                • Renames the moa session id.
                • + *
                • Removes ExecutionContext property {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}.
                • + *
                • Creates the http form mentioned above.
                • + *
                • Returns the http form via HttpServletResponse.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID} or
                • + *
                • ExecutionContext property {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID} (in case of legacy authentication without CCE selection, where the moa session is not provided by request parameter).
                • + *
                + * Result: + *
                  + *
                • The identity link form via HttpServletResponse.
                • + *
                + * Possible branches: + *
                  + *
                • In case of STORK authentication + *
                    + *
                  • Creates STORK auth SAML request.
                  • + *
                  • Creates and returns a form for submitting the SAML request to the CPEPS (post binding).
                  • + *
                  • Returns the form via HttpServletResponse.
                  • + *
                  + *
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GenerateIFrameTemplateServlet}. + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + String pendingRequestID = null; + String moasessionid = StringEscapeUtils.escapeHtml(ObjectUtils.defaultIfNull(req.getParameter(PARAM_SESSIONID), (String) executionContext.get(PARAM_SESSIONID))); + AuthenticationSession moasession = null; + try { + + if (MiscUtil.isEmpty(moasessionid)) { + Logger.warn("MOASessionID is empty."); + throw new MOAIDException("auth.18", new Object[] {}); + } + + try { + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); + moasession = AuthenticationSessionStoreage.getSession(moasessionid); + AuthenticationSessionStoreage.changeSessionID(moasession); + executionContext.remove(PARAM_SESSIONID); + + } catch (MOADatabaseException e) { + Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { moasessionid }); + + } catch (Throwable e) { + Logger.info("No HTTP Session found!"); + throw new MOAIDException("auth.18", new Object[] {}); + } + + StartAuthenticationBuilder startauth = StartAuthenticationBuilder.getInstance(); + String getIdentityLinkForm = startauth.build(moasession, req, resp); + + if (!StringUtils.isEmpty(getIdentityLinkForm)) { + resp.setContentType("text/html;charset=UTF-8"); + PrintWriter out = new PrintWriter(resp.getOutputStream()); + out.print(getIdentityLinkForm); + out.flush(); + Logger.debug("Finished GET " + GenerateIFrameTemplateServlet.class); + } + + } catch (WrongParametersException ex) { + handleWrongParameters(ex, req, resp); + } + + catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("CreateIdentityLinkFormTask has an interal Error.", e); + + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java new file mode 100644 index 000000000..a661abc95 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java @@ -0,0 +1,182 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.cert.CertificateException; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.transform.TransformerException; + +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.lang.StringEscapeUtils; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse; +import at.gv.egovernment.moa.id.auth.data.IdentityLink; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.ParseException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; +import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; +import at.gv.egovernment.moa.id.client.SZRGWClientException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Evaluates the {@code CreateXMLSignatureResponse}, extracts signature and certificate and asks the SZR Gateway for an identity link.

                + * In detail: + *

                  + *
                • Renames the moa session id.
                • + *
                • Parses the CreateXMLSignatureResponse retrieved from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • + *
                • Extracts signature and signer certificate.
                • + *
                • Send request to SZR Gateway in order to get an identity link.
                • + *
                • Updates moa session (sets identity link, QAA level 4, authentication data and foreigner flag).
                • + *
                • Redirects back to {@code /dispatcher} in order to finalize authentication.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
                • + *
                + * Result: + *
                  + *
                • Identity link, QAA level 4 and foreigner flag put into moa session.
                • + *
                • Redirect to {@code /dispatcher}.
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet}. + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class GetForeignIDTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + Logger.debug("POST GetForeignIDServlet"); + + setNoCachingHeaders(resp); + + Map parameters; + + try { + parameters = getParameters(req); + } catch (FileUploadException e) { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + } + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + String pendingRequestID = null; + String redirectURL = null; + AuthenticationSession session = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12"); + } + String xmlCreateXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE); + if (!ParamValidatorUtils.isValidXMLDocument(xmlCreateXMLSignatureResponse)) { + throw new WrongParametersException("GetForeignID", PARAM_XMLRESPONSE, "auth.12"); + } + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + session = AuthenticationServer.getSession(sessionID); + + // change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.debug(xmlCreateXMLSignatureResponse); + + CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse) + .parseResponseDsig(); + + try { + String serializedAssertion = DOMUtils.serializeNode(csresp.getDsigSignature()); + session.setAuthBlock(serializedAssertion); + + } catch (TransformerException e) { + throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); + + } catch (IOException e) { + throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); + + } + + Element signature = csresp.getDsigSignature(); + + try { + session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature)); + } catch (CertificateException e) { + Logger.error("Could not extract certificate from CreateXMLSignatureResponse"); + throw new MOAIDException("auth.14", null); + } + + // make SZR request to the identity link + CreateIdentityLinkResponse response = AuthenticationServer.getInstance().getIdentityLink(signature); + + if (null != response.getErrorResponse()) { + // TODO fix exception parameter + throw new SZRGWClientException("service.08", (String) response.getErrorResponse().getErrorCode(), + (String) response.getErrorResponse().getInfo()); + } else { + IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream( + response.getIdentityLink())); + IdentityLink identitylink = ilParser.parseIdentityLink(); + session.setIdentityLink(identitylink); + + // set QAA Level four in case of card authentifcation + session.setQAALevel(PVPConstants.STORK_QAA_1_4); + + AuthenticationServer.getInstance().getForeignAuthenticationData(session); + + // session is implicit stored in changeSessionID!!!! + String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID); + Logger.info("Daten angelegt zu MOASession " + newMOASessionID); + + redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), + newMOASessionID); + redirectURL = resp.encodeRedirectURL(redirectURL); + + // TODO[branch]: Final step back to /dispatcher + + try { + AuthenticationSessionStoreage.storeSession(session); + } catch (MOADatabaseException e) { + throw new MOAIDException("Session store error", null); + } + + resp.setContentType("text/html"); + resp.setStatus(302); + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + } + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("GetForeignIDServlet has an interal Error.", e); + + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java new file mode 100644 index 000000000..6e4d77b17 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java @@ -0,0 +1,181 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import iaik.pki.PKIException; + +import java.security.GeneralSecurityException; +import java.util.List; + +import javax.net.ssl.SSLSocketFactory; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.apache.commons.lang.StringEscapeUtils; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +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.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.ConnectionParameter; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.SSLUtils; +import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; +import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Retrieves a mandate from the online mandate issuing service.

                + * In detail: + *

                  + *
                • Renames the moa session id.
                • + *
                • Retrieves the mandate referenced within the moa session from the online (external) mandate issuing service.
                • + *
                • Verifies the mandate.
                • + *
                • Puts mandate into moa session.
                • + *
                • Redirects back to {@code /dispatcher} in order to finalize the authentication.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                + * Result: + *
                  + *
                • Mandate put into moa session.
                • + *
                • Redirect to {@code /dispatcher}.
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GetMISSessionIDServlet}. + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class GetMISSessionIDTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + Logger.debug("POST GetMISSessionIDServlet"); + + String sessionID = req.getParameter(PARAM_SESSIONID); + + // escape parameter strings + sessionID = StringEscapeUtils.escapeHtml(sessionID); + + AuthenticationSession session = null; + String pendingRequestID = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyCertificate", + PARAM_SESSIONID, "auth.12"); + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + session = AuthenticationServer.getSession(sessionID); + + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + String misSessionID = session.getMISSessionID(); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + ConnectionParameter connectionParameters = authConf + .getOnlineMandatesConnectionParameter(); + SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory( + AuthConfigurationProvider.getInstance(), + connectionParameters); + + List list = MISSimpleClient.sendGetMandatesRequest( + connectionParameters.getUrl(), misSessionID, sslFactory); + + if (list == null || list.size() == 0) { + Logger.error("Keine Vollmacht gefunden."); + throw new AuthenticationException("auth.15", null); + } + + // for now: list contains only one element + MISMandate mandate = (MISMandate) list.get(0); + + // TODO[tlenz]: UTF-8 ? + String sMandate = new String(mandate.getMandate()); + if (sMandate == null || sMandate.compareToIgnoreCase("") == 0) { + Logger.error("Mandate is empty."); + throw new AuthenticationException("auth.15", + new Object[] { GET_MIS_SESSIONID }); + } + + //check if it is a parsable XML + byte[] byteMandate = mandate.getMandate(); + // TODO[tlenz]: UTF-8 ? + String stringMandate = new String(byteMandate); + DOMUtils.parseDocument(stringMandate, false, + null, null).getDocumentElement(); + + // extract RepresentationType + AuthenticationServer.getInstance().verifyMandate(session, mandate); + + session.setMISMandate(mandate); + session.setAuthenticatedUsed(false); + session.setAuthenticated(true); + + //set QAA Level four in case of card authentifcation + session.setQAALevel(PVPConstants.STORK_QAA_1_4); + + String oldsessionID = session.getSessionID(); + + //Session is implicite stored in changeSessionID!!! + String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); + Logger.info("Daten angelegt zu MOASession " + newMOASessionID); + + String redirectURL = new DataURLBuilder().buildDataURL( + session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), + session.getAction(), pendingRequestID), newMOASessionID); + redirectURL = resp.encodeRedirectURL(redirectURL); + + // TODO[branch]: Final step back to /dispatcher + + resp.setContentType("text/html"); + resp.setStatus(302); + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (GeneralSecurityException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (PKIException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (SAXException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (ParserConfigurationException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("MISMandateValidation has an interal Error.", e); + + } + finally { + ConfigurationDBUtils.closeSession(); + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java new file mode 100644 index 000000000..d7a95bfcc --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java @@ -0,0 +1,102 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Creates {@code CreateXMLSignatureRequest} for auth block signature.

                + * In detail: + *

                  + *
                • Renames the moa session id.
                • + *
                • Creates {@code CreateXMLSignatureRequest} for auth block signature.
                • + *
                • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                + * Result: + *
                  + *
                • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class PrepareAuthBlockSignatureTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet + + Logger.debug("Process IdentityLink"); + + setNoCachingHeaders(resp); + + String pendingRequestID = null; + + try { + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); + } + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + // change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Normal"); + + // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + + String createXMLSignatureRequest = AuthenticationServer.getInstance() + .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); + + AuthenticationSessionStoreage.storeSession(session); + + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, + createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, + "VerifyIdentityLink"); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("IdentityLinkValidation has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java new file mode 100644 index 000000000..8c59c39ba --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java @@ -0,0 +1,246 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import iaik.pki.PKIException; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.SSLSocketFactory; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.transform.TransformerException; + +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.lang.StringEscapeUtils; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.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.MISSimpleClientException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.ConnectionParameter; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.SSLUtils; +import at.gv.egovernment.moa.id.util.client.mis.simple.MISSessionId; +import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +/** + * Verifies the signed authentication block (provided as {@code CreateXMLSignatureResponse}).

                + * In detail: + *

                  + *
                • Renames the moa session id.
                • + *
                • Takes the {@code CreateXMLSignatureResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • + *
                • Verifies the {@code CreateXMLSignatureResponse}.
                • + *
                • Updates moa session.
                • + *
                • Redirects back to {@code /dispatcher} in order to finalize the authentication.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
                • + *
                + * Result: + *
                  + *
                • Authentication data put into moa session.
                • + *
                • Redirect to {@code /dispatcher}.
                • + *
                + * Possible branches: + *
                  + *
                • In case of mandate mode + *
                    + *
                  • Creates a mandate session at the external mandate issuing service.
                  • + *
                  • Redirects the user's browser to the online mandate issuing service GUI.
                  • + *
                  + *
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet}. + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet + + Logger.debug("POST VerifyAuthenticationBlock"); + + String pendingRequestID = null; + + Map parameters; + try + { + parameters = getParameters(req); + } catch (FileUploadException e) + { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + + } + String sessionID = req.getParameter(PARAM_SESSIONID); + String createXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); + + // escape parameter strings + sessionID = StringEscapeUtils.escapeHtml(sessionID); + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + String redirectURL = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); + if (!ParamValidatorUtils.isValidXMLDocument(createXMLSignatureResponse)) + throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_XMLRESPONSE, "auth.12"); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + String authenticatedMOASessionId = AuthenticationServer.getInstance().verifyAuthenticationBlock(session, createXMLSignatureResponse); + + if (authenticatedMOASessionId == null) { + //mandate Mode + + AuthConfigurationProvider authConf= AuthConfigurationProvider.getInstance(); + ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter(); + SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters); + + // get identitity link as byte[] + Element elem = session.getIdentityLink().getSamlAssertion(); + String s = DOMUtils.serializeNode(elem); + + //System.out.println("IDL: " + s); + + byte[] idl = s.getBytes("UTF-8"); + + // redirect url + // build redirect(to the GetMISSessionIdSerlvet) + + //change MOASessionID before MIS request + String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + + redirectURL = + new DataURLBuilder().buildDataURL( + session.getAuthURL(), + GET_MIS_SESSIONID, + newMOASessionID); + + String oaURL = session.getOAURLRequested(); + OAAuthParameter oaParam = authConf.getOnlineApplicationParameter(oaURL); + List profiles = oaParam.getMandateProfiles(); + + if (profiles == null) { + Logger.error("No Mandate/Profile for OA configured."); + throw new AuthenticationException("config.21", new Object[] { GET_MIS_SESSIONID}); + } + + String oaFriendlyName = oaParam.getFriendlyName(); + String mandateReferenceValue = session.getMandateReferenceValue(); + byte[] cert = session.getEncodedSignerCertificate(); + byte[] authBlock = session.getAuthBlock().getBytes("UTF-8"); + + //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_+session.getDomainIdentifier(); + + } else { + targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); + } + + MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest( + connectionParameters.getUrl(), + idl, + cert, + oaFriendlyName, + redirectURL, + mandateReferenceValue, + profiles, + targetType, + authBlock, + sslFactory); + + if (misSessionID == null) { + Logger.error("Fehler bei Anfrage an Vollmachten Service. MIS Session ID ist null."); + throw new MISSimpleClientException("Fehler bei Anfrage an Vollmachten Service."); + } + + String redirectMISGUI = misSessionID.getRedirectURL(); + session.setMISSessionID(misSessionID.getSessiondId()); + + try { + AuthenticationSessionStoreage.storeSession(session); + } catch (MOADatabaseException e) { + throw new MOAIDException("Session store error", null); + } + + // TODO[branch]: Mandate; redirect to MIS website; website redirects back to "/GetMISSessionID" + + resp.setStatus(302); + resp.addHeader("Location", redirectMISGUI); + Logger.debug("REDIRECT TO: " + redirectURL); + } + else { + // TODO[branch]: Final step back to /dispatcher + redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), + ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), authenticatedMOASessionId); + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + } + + } + + catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (GeneralSecurityException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (PKIException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (TransformerException e) { + handleError(null, e, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("AuthBlockValidation has an interal Error.", e); + } + + + finally { + ConfigurationDBUtils.closeSession(); + } + + + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java new file mode 100644 index 000000000..7f9fed37a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java @@ -0,0 +1,164 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import iaik.x509.X509Certificate; + +import java.io.IOException; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.lang.StringEscapeUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +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.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.spss.util.CertificateUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Parses the certificate from {@code InfoBoxReadResponse} (via POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}), creates the auth block to be signed and returns a {@code CreateXMLSignatureRequest} for auth block signature.

                + * In detail: + *

                  + *
                • Renames the moa session id.
                • + *
                • Retrieves the certificate via {@code InfoBoxReadResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • + *
                • Verifies the certificate.
                • + *
                • Creates the auth block to be signed using information from the certificate (Organwalter, foreign citizen.
                • + *
                • Puts it in a {@code CreateXMLSignatureRequest}.
                • + *
                • Updates moa session.
                • + *
                • Responds with {@code CreateXMLSignatureRequest}.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_SESSIONID} containing a {@code InfoBoxReadResponse}.
                • + *
                + * Result: + *
                  + *
                • {@code CreateXMLSignatureRequest} send as HttpServletResponse (for CCE).
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet}. + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class VerifyCertificateTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet + + Logger.debug("POST VerifyCertificateServlet"); + + String pendingRequestID = null; + + Map parameters; + try + { + parameters = getParameters(req); + } catch (FileUploadException e) + { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + } + String sessionID = req.getParameter(PARAM_SESSIONID); + + // escape parameter strings + sessionID = StringEscapeUtils.escapeHtml(sessionID); + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + AuthenticationSession session = null; + try { + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) + throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12"); + + session = AuthenticationServer.getSession(sessionID); + + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + + X509Certificate cert = AuthenticationServer.getInstance().getCertificate(sessionID, parameters); + if (cert == null) { + Logger.error("Certificate could not be read."); + throw new AuthenticationException("auth.14", null); + } + + boolean useMandate = session.getUseMandate(); + + if (useMandate) { + + // verify certificate for OrganWalter + String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyCertificate(session, cert); + + try { + AuthenticationSessionStoreage.storeSession(session); + } catch (MOADatabaseException e) { + throw new MOAIDException("session store error", null); + } + + // TODO[branch]: Mandate; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" + ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); + + } + else { + + + String countrycode = CertificateUtils.getIssuerCountry(cert); + if (countrycode != null) { + if (countrycode.compareToIgnoreCase("AT") == 0) { + Logger.error("Certificate issuer country code is \"AT\". Login not support in foreign identities mode."); + throw new AuthenticationException("auth.22", null); + } + } + + // Foreign Identities Modus + String createXMLSignatureRequest = AuthenticationServer.getInstance().createXMLSignatureRequestForeignID(session, cert); + // build dataurl (to the GetForeignIDSerlvet) + String dataurl = + new DataURLBuilder().buildDataURL( + session.getAuthURL(), + REQ_GET_FOREIGN_ID, + session.getSessionID()); + + try { + AuthenticationSessionStoreage.storeSession(session); + } catch (MOADatabaseException e) { + throw new MOAIDException("session store error", null); + } + + // TODO[branch]: Foreign citizen; respond with CXSR for authblock signature, dataURL "/GetForeignID" + ServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); + + Logger.debug("Send CreateXMLSignatureRequest to BKU"); + } + } + catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("CertificateValidation has an interal Error.", e); + } + + + finally { + ConfigurationDBUtils.closeSession(); + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java new file mode 100644 index 000000000..c880570b8 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java @@ -0,0 +1,103 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import java.io.IOException; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.ParseException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * Verifies the identity link.

                + * In detail: + *

                  + *
                • Renames the moa session id.
                • + *
                • Parses the identity link retrieved as {@code InfoBoxReadResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • + *
                • Verifies the identity link.
                • + *
                • Updates moa session.
                • + *
                • Puts boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code InfoBoxReadResponse}.
                • + *
                + * Result: + *
                  + *
                • Identity link put into moa session.
                • + *
                • Boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + * + */ +public class VerifyIdentityLinkTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) + throws Exception { + + // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet + + Logger.debug("POST VerifyIdentityLink"); + + setNoCachingHeaders(resp); + + Map parameters; + String pendingRequestID = null; + + try { + parameters = getParameters(req); + } catch (Exception e) { + Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); + throw new IOException(e.getMessage()); + } + + try { + + String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); + } + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + boolean identityLinkAvailable = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters) != null; + AuthenticationSessionStoreage.storeSession(session); + + executionContext.put("identityLinkAvailable", identityLinkAvailable); + + } catch (ParseException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("IdentityLinkValidation has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java new file mode 100644 index 000000000..140334b36 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java @@ -0,0 +1,27 @@ +package at.gv.egovernment.moa.id.auth.modules.stork; + +import org.apache.commons.lang3.StringUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +import at.gv.egovernment.moa.id.moduls.moduleregistration.AuthModule; + +public class STORKAuthModuleImpl implements AuthModule { + + @Override + public int getPriority() { + // neutral priority between Integer.MIN_VALUE and Integer.MAX_VALUE + return 0; + } + + @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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java new file mode 100644 index 000000000..9ffcaaa1e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java @@ -0,0 +1,257 @@ +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.io.UnsupportedEncodingException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +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.bind.JAXBException; +import javax.xml.parsers.ParserConfigurationException; +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.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 org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +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.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.internal.tasks.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet; +import at.gv.egovernment.moa.id.auth.stork.STORKException; +import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.id.util.VelocityProvider; +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.egovernment.moa.util.StringUtils; +import at.gv.util.xsd.xmldsig.SignatureType; +import at.gv.util.xsd.xmldsig.X509DataType; + +import com.datentechnik.process_engine.api.ExecutionContext; + +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.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; + +public abstract class AbstractPepsConnectorWithLocalSigningTask extends AbstractAuthServletTask { + + 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 = AuthConfigurationProvider.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) 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) 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java new file mode 100644 index 000000000..d7480f063 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java @@ -0,0 +1,114 @@ +package at.gv.egovernment.moa.id.auth.modules.stork.tasks; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; + +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; +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.internal.tasks.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.stork.CPEPS; +import at.gv.egovernment.moa.id.config.stork.STORKConfig; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.logging.Logger; + +import com.datentechnik.process_engine.api.ExecutionContext; + +/** + * 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.

                + * In detail: + *

                  + *
                • Validates the stork configuration in order to make sure the selected country is supported.
                • + *
                • Puts a flag ({@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}) into the ExecutionContext reflecting the capability of the C-PEPS to create xml signatures.
                • + *
                • Invokes {@link AuthenticationServer#startSTORKAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationSession)} which
                • + *
                    + *
                  • Creates and signs a SAML2 stork authentication request.
                  • + *
                  • Creates a signature request for auth block signature (either to be performed by the C-PEPS or locally).
                  • + *
                  • Using the velocity template engine in order to create a form with the embedded stork request.
                  • + *
                  • Writes the form to the response output stream.
                  • + *
                  + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • + *
                • Property {@code ccc} set within the moa session.
                • + *
                + * Result: + *
                  + *
                • Form containing a SAML2 Stork authentication request and an action url pointing to the selected C-PEPS.
                • + *
                • 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.
                • + *
                • In case of a C-PEPS not supporting xml signature: moasession with set signedDoc property (containing the signature request for local signing).
                • + *
                • ExecutionContext contains the boolean flag {@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}. + *
                + * Code taken from {@link StartAuthenticationBuilder#build(AuthenticationSession, HttpServletRequest, HttpServletResponse)}.
                + * 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 Exception { + + String pendingRequestID = null; + String sessionID = null; + try { + setNoCachingHeaders(resp); + + sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("CreateStorkAuthRequestFormTask", PARAM_SESSIONID, "auth.12"); + } + AuthenticationSession moasession = AuthenticationServer.getSession(sessionID); + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + + if (StringUtils.isEmpty(moasession.getCcc())) { + // illegal state; task should not have been executed without a selected country + throw new AuthenticationException("stork.22", new Object[] { sessionID }); + } + STORKConfig storkConfig = AuthConfigurationProvider.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(moasession.getCcc()); + Logger.debug("Found C-PEPS configuration for citizen of country: " + moasession.getCcc()); + executionContext.put(PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED, cpeps.isXMLSignatureSupported()); + + Logger.info("Starting STORK authentication for a citizen of country: " + moasession.getCcc()); + AuthenticationServer.startSTORKAuthentication(req, resp, moasession); + + } catch (MOAIDException ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } catch (Exception e) { + Logger.error("CreateStorkAuthRequestFormTask has an interal Error.", e); + throw new MOAIDException("Internal error.", new Object[] { sessionID }, e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java new file mode 100644 index 000000000..d772a50c0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java @@ -0,0 +1,218 @@ +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.auth.AuthenticationServer; +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.stork.STORKException; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +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 com.datentechnik.process_engine.api.ExecutionContext; + +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. + *

                + * In detail: + *

                  + *
                • Changes moa session id.
                • + *
                • Decodes and validates the sign response, extracting the citizen's signature.
                • + *
                • Verifies the citizen's signature.
                • + *
                • Create {@code signedDoc} attribute.
                • + *
                • Retrieve identity link from SZR gateway using the citizen's signature.
                • + *
                • 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).
                • + *
                • The moa session is updated with authentication information.
                • + *
                • Change moa session id.
                • + *
                • Redirects back to {@code /dispatcher} in order to finalize the authentication.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@code moaSessionID}
                • + *
                • HttpServletRequest parameter {@code signresponse}
                • + *
                + * Result: + *
                  + *
                • Updated moa id session (signed auth block, signer certificate etc.)
                • + *
                • Redirect to {@code /dispatcher}.
                • + *
                • {@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.
                • + *
                + * Possible branches: + *
                  + *
                • In case the szr gateway throws exception due to missing gender information: + *
                    + *
                  • Returns a form for gender selection with action url back to this servlet/task.
                  • + *
                  + *
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.
                + * + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + */ +public class PepsConnectorHandleLocalSignResponseTask extends AbstractPepsConnectorWithLocalSigningTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws Exception { + 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 IOException("should not occur"); + } + return; + } + + private void handleSignResponse(ExecutionContext executionContext, HttpServletRequest request, + HttpServletResponse response) { + 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 = AuthenticationServer.getSession(moaSessionID); + // change MOASessionID + moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); + + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); + Logger.info("pendingRequestID:" + pendingRequestID); + String signResponseString = new String(Base64.decodeBase64(signResponse), "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 values = new ArrayList(); + 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? + 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) { + handleError(null, e, request, response, pendingRequestID); + + } catch (MOAIDException e) { + handleError(null, e, request, response, pendingRequestID); + + } catch (Exception e) { + Logger.error("PEPSConnector has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java new file mode 100644 index 000000000..8ed1cf44f --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java @@ -0,0 +1,441 @@ +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.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.AuthenticationServer; +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.servlet.PEPSConnectorWithLocalSigningServlet; +import at.gv.egovernment.moa.id.auth.stork.STORKException; +import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +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.StringUtils; + +import com.datentechnik.process_engine.api.ExecutionContext; + +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. + *

                + * In detail: + *

                  + *
                • Decodes and validates SAML response from C-PEPS.
                • + *
                • Retrieves the moa session using the session id provided by HttpServletRequest parameter {@code RelayState} or by {@code inResponseTo} attribute of the saml response.
                • + *
                • Store saml response in moa session.
                • + *
                • Change moa session id.
                • + *
                • Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@code moaSessionID} to be {@code null}
                • + *
                • HttpServletRequest parameter {@code signresponse} to be {@code null}
                • + *
                • HttpServletRequest parameter {@code SAMLResponse}
                • + *
                • Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute within the saml response, both reflecting the moa session id.
                • + *
                + * Result: + *
                  + *
                • Updated moa session (with saml response).
                • + *
                • Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.
                + * + * @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 Exception { + 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 IOException("should not occur"); + } + return; + } + + private void handleSAMLResponse(ExecutionContext executionContext, HttpServletRequest request, + HttpServletResponse response) { + 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.validateSTORKAuthnResponse(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); + + // load MOASession from database + AuthenticationSession moaSession = AuthenticationServer.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); + + // //////////// incorporate gender from parameters if not in stork response + + IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); + + // 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 tmp = new ArrayList(); + tmp.add(gendervalue); + gender.setValue(tmp); + + authnResponse.getPersonalAttributeList().add(gender); + } + } + } + + + + // //////////////////////////////////////////////////////////////////////// + + Logger.debug("Starting extraction of signedDoc attribute"); + // extract signed doc element and citizen signature + String citizenSignature = null; + try { + PersonalAttribute signedDoc = authnResponse.getPersonalAttributeList().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(authnResponse.getPersonalAttributeList()); + + 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 = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); + String acsURL = issuerValue + + PEPSConnectorWithLocalSigningServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; + + String url = acsURL + "?moaSessionID=" + newMOASessionID; + // redirect to OASIS module and sign there + + boolean found = false; + try { + List aps = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()).getStorkAPs(); + Logger.info("Found AttributeProviderPlugins:" + aps.size()); + for (AttributeProviderPlugin 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, authnResponse.getPersonalAttributeList(), 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) { + handleError(null, e, request, response, pendingRequestID); + + } catch (MOAIDException e) { + handleError(null, e, request, response, pendingRequestID); + + } catch (Exception e) { + Logger.error("PEPSConnector has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + + } + + 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", Base64.encodeBase64String(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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java new file mode 100644 index 000000000..296132e76 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java @@ -0,0 +1,567 @@ +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.util.ArrayList; +import java.util.Arrays; +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 com.datentechnik.process_engine.api.ExecutionContext; + +import eu.stork.documentservice.DocumentService; +import eu.stork.documentservice.data.DatabaseConnectorMySQLImpl; +import eu.stork.oasisdss.api.ApiUtils; +import eu.stork.oasisdss.api.LightweightSourceResolver; +import eu.stork.oasisdss.api.exceptions.ApiUtilsException; +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; +import at.gv.egovernment.moa.id.auth.AuthenticationServer; +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.internal.tasks.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.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.ModulUtils; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.id.util.VelocityProvider; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.StringUtils; +import at.gv.util.xsd.xmldsig.SignatureType; +import at.gv.util.xsd.xmldsig.X509DataType; + +/** + * Evaluates the SAML response from the C-PEPS and authenticates the user. + *

                + * In detail: + *

                  + *
                • Decodes and validates the SAML response from the C-PEPS.
                • + *
                • Change moa session id.
                • + *
                • Extracts the subject's gender from request parameter {@code gender} if not available from the saml response.
                • + *
                • Extracts the {@code signedDoc} attribute from the response, get signed doc payload using stork attribute query request.
                • + *
                • Request SZR gateway for verification of the citizen's signature and for creating of an identity link.
                • + *
                • 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).
                • + *
                • The moa session is updated with authentication information.
                • + *
                • Change moa session id.
                • + *
                • Redirects back to {@code /dispatcher} in order to finalize the authentication.
                • + *
                + * Expects: + *
                  + *
                • HttpServletRequest parameter {@code SAMLResponse}
                • + *
                • Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute from the SAML response (both depicting the moa session id)
                • + *
                • HttpServletRequest parameter {@code gender} in case the request comes from the gender selection form
                • + *
                • {@code signedDoc} attribute within the SAML response.
                • + *
                + * Result: + *
                  + *
                • Updated moa id session (identity link, stork attributes...)
                • + *
                • {@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.
                • + *
                • Redirect to {@code /dispatcher}.
                • + *
                + * Possible branches: + *
                  + *
                • In case the szr gateway throws exception due to missing gender information: + *
                    + *
                  • Returns a form for gender selection with action url back to this servlet/task.
                  • + *
                  + *
                • + *
                + * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet}.
                + * + * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) + */ +public class PepsConnectorTask extends AbstractAuthServletTask { + + private String dtlUrl = null; + + public PepsConnectorTask() { + super(); + 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(); + } + } + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws Exception { + 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.validateSTORKAuthnResponse(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); + + // load MOASession from database + AuthenticationSession moaSession = AuthenticationServer.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); + + // //////////// incorporate gender from parameters if not in stork response + + IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); + + // 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 tmp = new ArrayList(); + tmp.add(gendervalue); + gender.setValue(tmp); + + authnResponse.getPersonalAttributeList().add(gender); + } + } + } + + // //////////////////////////////////////////////////////////////////////// + + Logger.debug("Starting extraction of signedDoc attribute"); + // extract signed doc element and citizen signature + String citizenSignature = null; + try { + String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING + + Logger.debug("signatureInfo:" + signatureInfo); + + SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource( + new java.io.StringReader(signatureInfo))); + + // fetch signed doc + DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse); + if (ds == null) { + throw new ApiUtilsException("No datasource found in response"); + } + + InputStream incoming = ds.getInputStream(); + citizenSignature = IOUtils.toString(incoming); + incoming.close(); + + Logger.debug("citizenSignature:" + citizenSignature); + if (isDocumentServiceUsed(citizenSignature) == true) { + Logger.debug("Loading document from DocumentService."); + String url = getDtlUrlFromResponse(dssSignResponse); + // get Transferrequest + String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url); + // Load document from DocujmentService + 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) 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) 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); + // } + OAAuthParameter oaParam = AuthConfigurationProvider.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; + executionContext.put("identityLinkAvailable", false); + try { + identityLink = STORKResponseProcessor.connectToSZRGateway(authnResponse.getPersonalAttributeList(), + 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); + } + 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(authnResponse.getPersonalAttributeList()); + + 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); + + // TODO: found better solution, but QAA Level in response could be not 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) { + handleError(null, e, request, response, pendingRequestID); + + } catch (MOAIDException e) { + handleError(null, e, request, response, pendingRequestID); + + } catch (Exception e) { + Logger.error("PEPSConnector has an interal Error.", e); + } + + finally { + ConfigurationDBUtils.closeSession(); + } + + } + + private boolean isDocumentServiceUsed(String citizenSignature) // TODo add better check + { + if (citizenSignature + .contains("
                Service Name:{http://stork.eu}DocumentService
                Port Name:{http://stork.eu}DocumentServicePort
                ")) + return true; + 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 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 { + url = new URL(dtlUrl); + 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(dtlUrl)) + 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(dtlUrl); + 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); + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java index f8b0dbdab..64899565b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java @@ -69,9 +69,9 @@ import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetForeignIDTask; import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; -import at.gv.egovernment.moa.id.auth.tasks.GetForeignIDTask; import at.gv.egovernment.moa.id.client.SZRGWClientException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.moduls.ModulUtils; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java index dd5253e77..ffd01299e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java @@ -67,7 +67,7 @@ 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.tasks.GetMISSessionIDTask; +import at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetMISSessionIDTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index 02e1cb12d..af4b7ffbb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -97,7 +97,7 @@ import javax.xml.ws.BindingProvider; /** * Endpoint for receiving STORK response messages - * @deprecated Use {@link at.gv.egovernment.moa.id.auth.tasks.stork.PepsConnectorTask} instead. + * @deprecated Use {@link at.gv.egovernment.moa.id.auth.modules.stork.tasks.PepsConnectorTask} instead. */ public class PEPSConnectorServlet extends AuthServlet { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java index fa80bdab9..c01a356f6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java @@ -109,7 +109,7 @@ import eu.stork.peps.exceptions.STORKSAMLEngineException; /** * Endpoint for receiving STORK response messages - * @deprecated Use {@link at.gv.egovernment.moa.id.auth.tasks.stork.PepsConnectorHandleResponseWithoutSignatureTask} instead. + * @deprecated Use {@link at.gv.egovernment.moa.id.auth.modules.stork.tasks.PepsConnectorHandleResponseWithoutSignatureTask} instead. */ public class PEPSConnectorWithLocalSigningServlet extends AuthServlet { private static final long serialVersionUID = 1L; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java index dc350bfb7..67c42cd07 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java @@ -71,7 +71,7 @@ import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; 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.tasks.VerifyAuthenticationBlockTask; +import at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyAuthenticationBlockTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConnectionParameter; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java index 77e401899..82cdb2778 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java @@ -65,7 +65,7 @@ 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.tasks.VerifyCertificateTask; +import at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyCertificateTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java index e94273881..6f2ee2d89 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java @@ -64,7 +64,7 @@ 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.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.tasks.VerifyIdentityLinkTask; +import at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyIdentityLinkTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java deleted file mode 100644 index 9a5c2baee..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/AbstractAuthServletTask.java +++ /dev/null @@ -1,379 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileItemFactory; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.lang3.ArrayUtils; - -import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; -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.servlet.AuthServlet; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; -import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -import at.gv.egovernment.moa.id.storage.IExceptionStore; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -import com.datentechnik.process_engine.springweb.AbstractSpringWebSupportedTask; - -/** - * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing - * etc.).

                The code has been taken from {@link AuthServlet}. - */ -public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask { - - protected static final String ERROR_CODE_PARAM = "errorid"; - - protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp) { - - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); - } - - - StatisticLogger logger = StatisticLogger.getInstance(); - logger.logErrorOperation(exceptionThrown); - - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = req.getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - - resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); - resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); - resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); - - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Handles an error.
                > - *
                  - *
                • Logs the error
                • - *
                • Places error message and exception thrown into the request as request - * attributes (to be used by "/errorpage-auth.jsp")
                • - *
                • Sets HTTP status 500 (internal server error)
                • - *
                - * - * @param errorMessage - * error message - * @param exceptionThrown - * exception thrown - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleError(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { - - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); - } - - if (!(exceptionThrown instanceof MOAIDException)) { - Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown); - - } - - IExceptionStore store = DBExceptionStoreImpl.getStore(); - String id = store.storeException(exceptionThrown); - - if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { - - String redirectURL = null; - - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id - + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - return; - - } else { - - //Exception can not be stored in database - handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); - } - } - - /** - * Handles a WrongParametersException. - * - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleWrongParameters(WrongParametersException ex, - HttpServletRequest req, HttpServletResponse resp) { - Logger.error(ex.toString()); - req.setAttribute("WrongParameters", ex.getMessage()); - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = req.getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - setNoCachingHeaders(resp); - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Logs all servlet parameters for debugging purposes. - */ - protected void logParameters(HttpServletRequest req) { - for (Enumeration params = req.getParameterNames(); params - .hasMoreElements();) { - String parname = (String) params.nextElement(); - Logger.debug("Parameter " + parname + req.getParameter(parname)); - } - } - - /** - * Parses the request input stream for parameters, assuming parameters are - * encoded UTF-8 (no standard exists how browsers should encode them). - * - * @param req - * servlet request - * - * @return mapping parameter name -> value - * - * @throws IOException - * if parsing request parameters fails. - * - * @throws FileUploadException - * if parsing request parameters fails. - */ - protected Map getParameters(HttpServletRequest req) throws IOException, - FileUploadException { - - Map parameters = new HashMap(); - - if (ServletFileUpload.isMultipartContent(req)) { - // request is encoded as mulitpart/form-data - FileItemFactory factory = new DiskFileItemFactory(); - ServletFileUpload upload = null; - upload = new ServletFileUpload(factory); - List items = null; - items = upload.parseRequest(req); - for (int i = 0; i < items.size(); i++) { - FileItem item = (FileItem) items.get(i); - if (item.isFormField()) { - // Process only form fields - no file upload items - String logString = item.getString("UTF-8"); - - // TODO use RegExp - String startS = ""; - String endS = "urn:publicid:gv.at:baseid"; - String logWithMaskedBaseid = logString; - int start = logString.indexOf(startS); - if (start > -1) { - int end = logString.indexOf(endS); - if (end > -1) { - logWithMaskedBaseid = logString.substring(0, start); - logWithMaskedBaseid += startS; - logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; - logWithMaskedBaseid += logString.substring(end, - logString.length()); - } - } - parameters - .put(item.getFieldName(), item.getString("UTF-8")); - Logger.debug("Processed multipart/form-data request parameter: \nName: " - + item.getFieldName() - + "\nValue: " - + logWithMaskedBaseid); - } - } - } - - else { - // request is encoded as application/x-www-urlencoded - // [tknall]: we must not consume request body input stream once servlet-api request parameters have been accessed - - /* - InputStream in = req.getInputStream(); - - String paramName; - String paramValueURLEncoded; - do { - paramName = new String(readBytesUpTo(in, '=')); - if (paramName.length() > 0) { - paramValueURLEncoded = readBytesUpTo(in, '&'); - String paramValue = URLDecoder.decode(paramValueURLEncoded, - "UTF-8"); - parameters.put(paramName, paramValue); - } - } while (paramName.length() > 0); - in.close(); - */ - - Iterator> requestParamIt = req.getParameterMap().entrySet().iterator(); - while (requestParamIt.hasNext()) { - Entry entry = requestParamIt.next(); - String key = entry.getKey(); - String[] values = entry.getValue(); - // take the last value from the value array since the legacy code above also does it this way - parameters.put(key, ArrayUtils.isEmpty(values) ? null : values[values.length-1]); - } - - } - - return parameters; - } - - /** - * Reads bytes up to a delimiter, consuming the delimiter. - * - * @param in - * input stream - * @param delimiter - * delimiter character - * @return String constructed from the read bytes - * @throws IOException - */ - protected String readBytesUpTo(InputStream in, char delimiter) - throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - boolean done = false; - int b; - while (!done && (b = in.read()) >= 0) { - if (b == delimiter) - done = true; - else - bout.write(b); - } - return bout.toString(); - } - - /** - * Sets response headers that prevent caching (code taken from {@link AuthServlet}). - * - * @param resp - * The HttpServletResponse. - */ - public void setNoCachingHeaders(HttpServletResponse resp) { - resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); - resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); - resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); - } - - /** - * Adds a parameter to a URL. - * - * @param url - * the URL - * @param paramname - * parameter name - * @param paramvalue - * parameter value - * @return the URL with parameter added - */ - protected static String addURLParameter(String url, String paramname, - String paramvalue) { - String param = paramname + "=" + paramvalue; - if (url.indexOf("?") < 0) - return url + "?" + param; - else - return url + "&" + param; - } - - /** - * Checks if HTTP requests are allowed - * - * @param authURL - * requestURL - * @throws AuthenticationException - * if HTTP requests are not allowed - * @throws ConfigurationException - */ - protected void checkIfHTTPisAllowed(String authURL) - throws AuthenticationException, ConfigurationException { - // check if HTTP Connection may be allowed (through - // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) - - //Removed from MOA-ID 2.0 config -// String boolStr = AuthConfigurationProvider -// .getInstance() -// .getGenericConfigurationParameter( -// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); - if ((!authURL.startsWith("https:")) - //&& (false == BoolUtils.valueOf(boolStr)) - ) - throw new AuthenticationException("auth.07", new Object[] { authURL - + "*" }); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java deleted file mode 100644 index 8cd0db679..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CertificateReadRequestTask.java +++ /dev/null @@ -1,101 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.BooleanUtils; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; -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.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.

                - * In detail: - *

                  - *
                • Renames the moa session id.
                • - *
                • Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.
                • - *
                • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code /VerifyCertificate}
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • - *
                - * Result: - *
                  - *
                • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code {/VerifyCertificate}
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class CertificateReadRequestTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - - // TODO[branch]: Foreign citizen or mandate mode; respond with IRR for certificates, dataURL = "/VerifyCertificate" - Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); - - setNoCachingHeaders(resp); - - String pendingRequestID = null; - - try { - - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("CertificateReadRequestTask", PARAM_SESSIONID, "auth.12"); - } - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - boolean useMandate = session.getUseMandate(); - boolean identityLinkAvailable = BooleanUtils.isTrue((Boolean) executionContext.get("identityLinkAvailable")); - - if (!identityLinkAvailable && useMandate) { - Logger.error("Online-Mandate Mode for foreign citizencs not supported."); - throw new AuthenticationException("auth.13", null); - } - - // change MOASessionID - AuthenticationSessionStoreage.changeSessionID(session); - - // create the InfoboxReadRequest to get the certificate - String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); - - // build dataurl (to the VerifyCertificateSerlvet) - String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, - session.getSessionID()); - - ServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest, - AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - } finally { - ConfigurationDBUtils.closeSession(); - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java deleted file mode 100644 index ff55eedeb..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/CreateIdentityLinkFormTask.java +++ /dev/null @@ -1,120 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import java.io.PrintWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.ObjectUtils; - -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -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.servlet.GenerateIFrameTemplateServlet; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.egovernment.moa.util.StringUtils; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * Creates a http form including an embedded {@code InfoBoxReadRequest} for reading the identity link.

                - * In detail: - *

                  - *
                • Renames the moa session id.
                • - *
                • Removes ExecutionContext property {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}.
                • - *
                • Creates the http form mentioned above.
                • - *
                • Returns the http form via HttpServletResponse.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID} or
                • - *
                • ExecutionContext property {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID} (in case of legacy authentication without CCE selection, where the moa session is not provided by request parameter).
                • - *
                - * Result: - *
                  - *
                • The identity link form via HttpServletResponse.
                • - *
                - * Possible branches: - *
                  - *
                • In case of STORK authentication - *
                    - *
                  • Creates STORK auth SAML request.
                  • - *
                  • Creates and returns a form for submitting the SAML request to the CPEPS (post binding).
                  • - *
                  • Returns the form via HttpServletResponse.
                  • - *
                  - *
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GenerateIFrameTemplateServlet}. - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - - String pendingRequestID = null; - String moasessionid = StringEscapeUtils.escapeHtml(ObjectUtils.defaultIfNull(req.getParameter(PARAM_SESSIONID), (String) executionContext.get(PARAM_SESSIONID))); - AuthenticationSession moasession = null; - try { - - if (MiscUtil.isEmpty(moasessionid)) { - Logger.warn("MOASessionID is empty."); - throw new MOAIDException("auth.18", new Object[] {}); - } - - try { - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); - moasession = AuthenticationSessionStoreage.getSession(moasessionid); - AuthenticationSessionStoreage.changeSessionID(moasession); - executionContext.remove(PARAM_SESSIONID); - - } catch (MOADatabaseException e) { - Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { moasessionid }); - - } catch (Throwable e) { - Logger.info("No HTTP Session found!"); - throw new MOAIDException("auth.18", new Object[] {}); - } - - StartAuthenticationBuilder startauth = StartAuthenticationBuilder.getInstance(); - String getIdentityLinkForm = startauth.build(moasession, req, resp); - - if (!StringUtils.isEmpty(getIdentityLinkForm)) { - resp.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(resp.getOutputStream()); - out.print(getIdentityLinkForm); - out.flush(); - Logger.debug("Finished GET " + GenerateIFrameTemplateServlet.class); - } - - } catch (WrongParametersException ex) { - handleWrongParameters(ex, req, resp); - } - - catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("CreateIdentityLinkFormTask has an interal Error.", e); - - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java deleted file mode 100644 index 2ce6a1ae8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetForeignIDTask.java +++ /dev/null @@ -1,182 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.cert.CertificateException; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.transform.TransformerException; - -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.ParseException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; -import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; -import at.gv.egovernment.moa.id.client.SZRGWClientException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * Evaluates the {@code CreateXMLSignatureResponse}, extracts signature and certificate and asks the SZR Gateway for an identity link.

                - * In detail: - *

                  - *
                • Renames the moa session id.
                • - *
                • Parses the CreateXMLSignatureResponse retrieved from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • - *
                • Extracts signature and signer certificate.
                • - *
                • Send request to SZR Gateway in order to get an identity link.
                • - *
                • Updates moa session (sets identity link, QAA level 4, authentication data and foreigner flag).
                • - *
                • Redirects back to {@code /dispatcher} in order to finalize authentication.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
                • - *
                - * Result: - *
                  - *
                • Identity link, QAA level 4 and foreigner flag put into moa session.
                • - *
                • Redirect to {@code /dispatcher}.
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet}. - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class GetForeignIDTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - - Logger.debug("POST GetForeignIDServlet"); - - setNoCachingHeaders(resp); - - Map parameters; - - try { - parameters = getParameters(req); - } catch (FileUploadException e) { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - } - - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - String pendingRequestID = null; - String redirectURL = null; - AuthenticationSession session = null; - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12"); - } - String xmlCreateXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE); - if (!ParamValidatorUtils.isValidXMLDocument(xmlCreateXMLSignatureResponse)) { - throw new WrongParametersException("GetForeignID", PARAM_XMLRESPONSE, "auth.12"); - } - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - session = AuthenticationServer.getSession(sessionID); - - // change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.debug(xmlCreateXMLSignatureResponse); - - CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse) - .parseResponseDsig(); - - try { - String serializedAssertion = DOMUtils.serializeNode(csresp.getDsigSignature()); - session.setAuthBlock(serializedAssertion); - - } catch (TransformerException e) { - throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); - - } catch (IOException e) { - throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); - - } - - Element signature = csresp.getDsigSignature(); - - try { - session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature)); - } catch (CertificateException e) { - Logger.error("Could not extract certificate from CreateXMLSignatureResponse"); - throw new MOAIDException("auth.14", null); - } - - // make SZR request to the identity link - CreateIdentityLinkResponse response = AuthenticationServer.getInstance().getIdentityLink(signature); - - if (null != response.getErrorResponse()) { - // TODO fix exception parameter - throw new SZRGWClientException("service.08", (String) response.getErrorResponse().getErrorCode(), - (String) response.getErrorResponse().getInfo()); - } else { - IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream( - response.getIdentityLink())); - IdentityLink identitylink = ilParser.parseIdentityLink(); - session.setIdentityLink(identitylink); - - // set QAA Level four in case of card authentifcation - session.setQAALevel(PVPConstants.STORK_QAA_1_4); - - AuthenticationServer.getInstance().getForeignAuthenticationData(session); - - // session is implicit stored in changeSessionID!!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID); - Logger.info("Daten angelegt zu MOASession " + newMOASessionID); - - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), - newMOASessionID); - redirectURL = resp.encodeRedirectURL(redirectURL); - - // TODO[branch]: Final step back to /dispatcher - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("Session store error", null); - } - - resp.setContentType("text/html"); - resp.setStatus(302); - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - } - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("GetForeignIDServlet has an interal Error.", e); - - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java deleted file mode 100644 index a7ee086af..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/GetMISSessionIDTask.java +++ /dev/null @@ -1,181 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; -import iaik.pki.PKIException; - -import java.security.GeneralSecurityException; -import java.util.List; - -import javax.net.ssl.SSLSocketFactory; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.lang.StringEscapeUtils; -import org.xml.sax.SAXException; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.exception.WrongParametersException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.SSLUtils; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * Retrieves a mandate from the online mandate issuing service.

                - * In detail: - *

                  - *
                • Renames the moa session id.
                • - *
                • Retrieves the mandate referenced within the moa session from the online (external) mandate issuing service.
                • - *
                • Verifies the mandate.
                • - *
                • Puts mandate into moa session.
                • - *
                • Redirects back to {@code /dispatcher} in order to finalize the authentication.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • - *
                - * Result: - *
                  - *
                • Mandate put into moa session.
                • - *
                • Redirect to {@code /dispatcher}.
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.GetMISSessionIDServlet}. - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class GetMISSessionIDTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - - Logger.debug("POST GetMISSessionIDServlet"); - - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - - AuthenticationSession session = null; - String pendingRequestID = null; - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyCertificate", - PARAM_SESSIONID, "auth.12"); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - String misSessionID = session.getMISSessionID(); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - ConnectionParameter connectionParameters = authConf - .getOnlineMandatesConnectionParameter(); - SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory( - AuthConfigurationProvider.getInstance(), - connectionParameters); - - List list = MISSimpleClient.sendGetMandatesRequest( - connectionParameters.getUrl(), misSessionID, sslFactory); - - if (list == null || list.size() == 0) { - Logger.error("Keine Vollmacht gefunden."); - throw new AuthenticationException("auth.15", null); - } - - // for now: list contains only one element - MISMandate mandate = (MISMandate) list.get(0); - - // TODO[tlenz]: UTF-8 ? - String sMandate = new String(mandate.getMandate()); - if (sMandate == null || sMandate.compareToIgnoreCase("") == 0) { - Logger.error("Mandate is empty."); - throw new AuthenticationException("auth.15", - new Object[] { GET_MIS_SESSIONID }); - } - - //check if it is a parsable XML - byte[] byteMandate = mandate.getMandate(); - // TODO[tlenz]: UTF-8 ? - String stringMandate = new String(byteMandate); - DOMUtils.parseDocument(stringMandate, false, - null, null).getDocumentElement(); - - // extract RepresentationType - AuthenticationServer.getInstance().verifyMandate(session, mandate); - - session.setMISMandate(mandate); - session.setAuthenticatedUsed(false); - session.setAuthenticated(true); - - //set QAA Level four in case of card authentifcation - session.setQAALevel(PVPConstants.STORK_QAA_1_4); - - String oldsessionID = session.getSessionID(); - - //Session is implicite stored in changeSessionID!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); - Logger.info("Daten angelegt zu MOASession " + newMOASessionID); - - String redirectURL = new DataURLBuilder().buildDataURL( - session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), - session.getAction(), pendingRequestID), newMOASessionID); - redirectURL = resp.encodeRedirectURL(redirectURL); - - // TODO[branch]: Final step back to /dispatcher - - resp.setContentType("text/html"); - resp.setStatus(302); - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (GeneralSecurityException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (PKIException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (SAXException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (ParserConfigurationException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("MISMandateValidation has an interal Error.", e); - - } - finally { - ConfigurationDBUtils.closeSession(); - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java deleted file mode 100644 index 566616fcd..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/PrepareAuthBlockSignatureTask.java +++ /dev/null @@ -1,102 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * Creates {@code CreateXMLSignatureRequest} for auth block signature.

                - * In detail: - *

                  - *
                • Renames the moa session id.
                • - *
                • Creates {@code CreateXMLSignatureRequest} for auth block signature.
                • - *
                • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • - *
                - * Result: - *
                  - *
                • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class PrepareAuthBlockSignatureTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet - - Logger.debug("Process IdentityLink"); - - setNoCachingHeaders(resp); - - String pendingRequestID = null; - - try { - - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); - } - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - // change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.info("Normal"); - - // TODO[branch]: Default behaviour; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); - - String createXMLSignatureRequest = AuthenticationServer.getInstance() - .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam); - - AuthenticationSessionStoreage.storeSession(session); - - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, - createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, - "VerifyIdentityLink"); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("IdentityLinkValidation has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java deleted file mode 100644 index 956ec9c88..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyAuthenticationBlockTask.java +++ /dev/null @@ -1,246 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import iaik.pki.PKIException; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.SSLSocketFactory; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.transform.TransformerException; - -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.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.MISSimpleClientException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.SSLUtils; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISSessionId; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; - -import com.datentechnik.process_engine.api.ExecutionContext; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -/** - * Verifies the signed authentication block (provided as {@code CreateXMLSignatureResponse}).

                - * In detail: - *

                  - *
                • Renames the moa session id.
                • - *
                • Takes the {@code CreateXMLSignatureResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • - *
                • Verifies the {@code CreateXMLSignatureResponse}.
                • - *
                • Updates moa session.
                • - *
                • Redirects back to {@code /dispatcher} in order to finalize the authentication.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.
                • - *
                - * Result: - *
                  - *
                • Authentication data put into moa session.
                • - *
                • Redirect to {@code /dispatcher}.
                • - *
                - * Possible branches: - *
                  - *
                • In case of mandate mode - *
                    - *
                  • Creates a mandate session at the external mandate issuing service.
                  • - *
                  • Redirects the user's browser to the online mandate issuing service GUI.
                  • - *
                  - *
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet}. - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - - // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet - - Logger.debug("POST VerifyAuthenticationBlock"); - - String pendingRequestID = null; - - Map parameters; - try - { - parameters = getParameters(req); - } catch (FileUploadException e) - { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - - } - String sessionID = req.getParameter(PARAM_SESSIONID); - String createXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - String redirectURL = null; - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); - if (!ParamValidatorUtils.isValidXMLDocument(createXMLSignatureResponse)) - throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_XMLRESPONSE, "auth.12"); - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - String authenticatedMOASessionId = AuthenticationServer.getInstance().verifyAuthenticationBlock(session, createXMLSignatureResponse); - - if (authenticatedMOASessionId == null) { - //mandate Mode - - AuthConfigurationProvider authConf= AuthConfigurationProvider.getInstance(); - ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter(); - SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProvider.getInstance(), connectionParameters); - - // get identitity link as byte[] - Element elem = session.getIdentityLink().getSamlAssertion(); - String s = DOMUtils.serializeNode(elem); - - //System.out.println("IDL: " + s); - - byte[] idl = s.getBytes("UTF-8"); - - // redirect url - // build redirect(to the GetMISSessionIdSerlvet) - - //change MOASessionID before MIS request - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - - redirectURL = - new DataURLBuilder().buildDataURL( - session.getAuthURL(), - GET_MIS_SESSIONID, - newMOASessionID); - - String oaURL = session.getOAURLRequested(); - OAAuthParameter oaParam = authConf.getOnlineApplicationParameter(oaURL); - List profiles = oaParam.getMandateProfiles(); - - if (profiles == null) { - Logger.error("No Mandate/Profile for OA configured."); - throw new AuthenticationException("config.21", new Object[] { GET_MIS_SESSIONID}); - } - - String oaFriendlyName = oaParam.getFriendlyName(); - String mandateReferenceValue = session.getMandateReferenceValue(); - byte[] cert = session.getEncodedSignerCertificate(); - byte[] authBlock = session.getAuthBlock().getBytes("UTF-8"); - - //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_+session.getDomainIdentifier(); - - } else { - targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); - } - - MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest( - connectionParameters.getUrl(), - idl, - cert, - oaFriendlyName, - redirectURL, - mandateReferenceValue, - profiles, - targetType, - authBlock, - sslFactory); - - if (misSessionID == null) { - Logger.error("Fehler bei Anfrage an Vollmachten Service. MIS Session ID ist null."); - throw new MISSimpleClientException("Fehler bei Anfrage an Vollmachten Service."); - } - - String redirectMISGUI = misSessionID.getRedirectURL(); - session.setMISSessionID(misSessionID.getSessiondId()); - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("Session store error", null); - } - - // TODO[branch]: Mandate; redirect to MIS website; website redirects back to "/GetMISSessionID" - - resp.setStatus(302); - resp.addHeader("Location", redirectMISGUI); - Logger.debug("REDIRECT TO: " + redirectURL); - } - else { - // TODO[branch]: Final step back to /dispatcher - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), authenticatedMOASessionId); - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - } - - } - - catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (GeneralSecurityException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (PKIException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (TransformerException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("AuthBlockValidation has an interal Error.", e); - } - - - finally { - ConfigurationDBUtils.closeSession(); - } - - - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java deleted file mode 100644 index 854c78161..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyCertificateTask.java +++ /dev/null @@ -1,164 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; -import iaik.x509.X509Certificate; - -import java.io.IOException; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.exception.WrongParametersException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.spss.util.CertificateUtils; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * Parses the certificate from {@code InfoBoxReadResponse} (via POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}), creates the auth block to be signed and returns a {@code CreateXMLSignatureRequest} for auth block signature.

                - * In detail: - *

                  - *
                • Renames the moa session id.
                • - *
                • Retrieves the certificate via {@code InfoBoxReadResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • - *
                • Verifies the certificate.
                • - *
                • Creates the auth block to be signed using information from the certificate (Organwalter, foreign citizen.
                • - *
                • Puts it in a {@code CreateXMLSignatureRequest}.
                • - *
                • Updates moa session.
                • - *
                • Responds with {@code CreateXMLSignatureRequest}.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_SESSIONID} containing a {@code InfoBoxReadResponse}.
                • - *
                - * Result: - *
                  - *
                • {@code CreateXMLSignatureRequest} send as HttpServletResponse (for CCE).
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet}. - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class VerifyCertificateTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - - // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet - - Logger.debug("POST VerifyCertificateServlet"); - - String pendingRequestID = null; - - Map parameters; - try - { - parameters = getParameters(req); - } catch (FileUploadException e) - { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - } - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - AuthenticationSession session = null; - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12"); - - session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - X509Certificate cert = AuthenticationServer.getInstance().getCertificate(sessionID, parameters); - if (cert == null) { - Logger.error("Certificate could not be read."); - throw new AuthenticationException("auth.14", null); - } - - boolean useMandate = session.getUseMandate(); - - if (useMandate) { - - // verify certificate for OrganWalter - String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyCertificate(session, cert); - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("session store error", null); - } - - // TODO[branch]: Mandate; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); - - } - else { - - - String countrycode = CertificateUtils.getIssuerCountry(cert); - if (countrycode != null) { - if (countrycode.compareToIgnoreCase("AT") == 0) { - Logger.error("Certificate issuer country code is \"AT\". Login not support in foreign identities mode."); - throw new AuthenticationException("auth.22", null); - } - } - - // Foreign Identities Modus - String createXMLSignatureRequest = AuthenticationServer.getInstance().createXMLSignatureRequestForeignID(session, cert); - // build dataurl (to the GetForeignIDSerlvet) - String dataurl = - new DataURLBuilder().buildDataURL( - session.getAuthURL(), - REQ_GET_FOREIGN_ID, - session.getSessionID()); - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("session store error", null); - } - - // TODO[branch]: Foreign citizen; respond with CXSR for authblock signature, dataURL "/GetForeignID" - ServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); - - Logger.debug("Send CreateXMLSignatureRequest to BKU"); - } - } - catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("CertificateValidation has an interal Error.", e); - } - - - finally { - ConfigurationDBUtils.closeSession(); - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java deleted file mode 100644 index eb884e9db..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/VerifyIdentityLinkTask.java +++ /dev/null @@ -1,103 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import java.io.IOException; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.ParseException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.logging.Logger; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * Verifies the identity link.

                - * In detail: - *

                  - *
                • Renames the moa session id.
                • - *
                • Parses the identity link retrieved as {@code InfoBoxReadResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.
                • - *
                • Verifies the identity link.
                • - *
                • Updates moa session.
                • - *
                • Puts boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code InfoBoxReadResponse}.
                • - *
                - * Result: - *
                  - *
                • Identity link put into moa session.
                • - *
                • Boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - * - */ -public class VerifyIdentityLinkTask extends AbstractAuthServletTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { - - // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet - - Logger.debug("POST VerifyIdentityLink"); - - setNoCachingHeaders(resp); - - Map parameters; - String pendingRequestID = null; - - try { - parameters = getParameters(req); - } catch (Exception e) { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - } - - try { - - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); - } - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - boolean identityLinkAvailable = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters) != null; - AuthenticationSessionStoreage.storeSession(session); - - executionContext.put("identityLinkAvailable", identityLinkAvailable); - - } catch (ParseException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("IdentityLinkValidation has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/AbstractPepsConnectorWithLocalSigningTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/AbstractPepsConnectorWithLocalSigningTask.java deleted file mode 100644 index eff7fe43f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/AbstractPepsConnectorWithLocalSigningTask.java +++ /dev/null @@ -1,258 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks.stork; - -import at.gv.egovernment.moa.id.auth.tasks.AbstractAuthServletTask; -import iaik.x509.X509Certificate; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -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.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; -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.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 org.xml.sax.SAXException; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.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.servlet.PEPSConnectorWithLocalSigningServlet; -import at.gv.egovernment.moa.id.auth.stork.STORKException; -import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; -import at.gv.egovernment.moa.id.auth.tasks.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.VelocityProvider; -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.egovernment.moa.util.StringUtils; -import at.gv.util.xsd.xmldsig.SignatureType; -import at.gv.util.xsd.xmldsig.X509DataType; - -import com.datentechnik.process_engine.api.ExecutionContext; - -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.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; - -public abstract class AbstractPepsConnectorWithLocalSigningTask extends AbstractAuthServletTask { - - 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 = AuthConfigurationProvider.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) 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) 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java deleted file mode 100644 index 3894567ed..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/CreateStorkAuthRequestFormTask.java +++ /dev/null @@ -1,114 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks.stork; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; -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.tasks.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.stork.CPEPS; -import at.gv.egovernment.moa.id.config.stork.STORKConfig; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.logging.Logger; - -import com.datentechnik.process_engine.api.ExecutionContext; - -/** - * 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.

                - * In detail: - *

                  - *
                • Validates the stork configuration in order to make sure the selected country is supported.
                • - *
                • Puts a flag ({@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}) into the ExecutionContext reflecting the capability of the C-PEPS to create xml signatures.
                • - *
                • Invokes {@link AuthenticationServer#startSTORKAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationSession)} which
                • - *
                    - *
                  • Creates and signs a SAML2 stork authentication request.
                  • - *
                  • Creates a signature request for auth block signature (either to be performed by the C-PEPS or locally).
                  • - *
                  • Using the velocity template engine in order to create a form with the embedded stork request.
                  • - *
                  • Writes the form to the response output stream.
                  • - *
                  - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
                • - *
                • Property {@code ccc} set within the moa session.
                • - *
                - * Result: - *
                  - *
                • Form containing a SAML2 Stork authentication request and an action url pointing to the selected C-PEPS.
                • - *
                • 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.
                • - *
                • In case of a C-PEPS not supporting xml signature: moasession with set signedDoc property (containing the signature request for local signing).
                • - *
                • ExecutionContext contains the boolean flag {@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}. - *
                - * Code taken from {@link StartAuthenticationBuilder#build(AuthenticationSession, HttpServletRequest, HttpServletResponse)}.
                - * 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 Exception { - - String pendingRequestID = null; - String sessionID = null; - try { - setNoCachingHeaders(resp); - - sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("CreateStorkAuthRequestFormTask", PARAM_SESSIONID, "auth.12"); - } - AuthenticationSession moasession = AuthenticationServer.getSession(sessionID); - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - if (StringUtils.isEmpty(moasession.getCcc())) { - // illegal state; task should not have been executed without a selected country - throw new AuthenticationException("stork.22", new Object[] { sessionID }); - } - STORKConfig storkConfig = AuthConfigurationProvider.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(moasession.getCcc()); - Logger.debug("Found C-PEPS configuration for citizen of country: " + moasession.getCcc()); - executionContext.put(PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED, cpeps.isXMLSignatureSupported()); - - Logger.info("Starting STORK authentication for a citizen of country: " + moasession.getCcc()); - AuthenticationServer.startSTORKAuthentication(req, resp, moasession); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("CreateStorkAuthRequestFormTask has an interal Error.", e); - throw new MOAIDException("Internal error.", new Object[] { sessionID }, e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleLocalSignResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleLocalSignResponseTask.java deleted file mode 100644 index 738988ff7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleLocalSignResponseTask.java +++ /dev/null @@ -1,218 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks.stork; - -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.auth.AuthenticationServer; -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.stork.STORKException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -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 com.datentechnik.process_engine.api.ExecutionContext; - -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. - *

                - * In detail: - *

                  - *
                • Changes moa session id.
                • - *
                • Decodes and validates the sign response, extracting the citizen's signature.
                • - *
                • Verifies the citizen's signature.
                • - *
                • Create {@code signedDoc} attribute.
                • - *
                • Retrieve identity link from SZR gateway using the citizen's signature.
                • - *
                • 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).
                • - *
                • The moa session is updated with authentication information.
                • - *
                • Change moa session id.
                • - *
                • Redirects back to {@code /dispatcher} in order to finalize the authentication.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@code moaSessionID}
                • - *
                • HttpServletRequest parameter {@code signresponse}
                • - *
                - * Result: - *
                  - *
                • Updated moa id session (signed auth block, signer certificate etc.)
                • - *
                • Redirect to {@code /dispatcher}.
                • - *
                • {@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.
                • - *
                - * Possible branches: - *
                  - *
                • In case the szr gateway throws exception due to missing gender information: - *
                    - *
                  • Returns a form for gender selection with action url back to this servlet/task.
                  • - *
                  - *
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.
                - * - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - */ -public class PepsConnectorHandleLocalSignResponseTask extends AbstractPepsConnectorWithLocalSigningTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws Exception { - 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 IOException("should not occur"); - } - return; - } - - private void handleSignResponse(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) { - 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 = AuthenticationServer.getSession(moaSessionID); - // change MOASessionID - moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); - Logger.info("pendingRequestID:" + pendingRequestID); - String signResponseString = new String(Base64.decodeBase64(signResponse), "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 values = new ArrayList(); - 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? - 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) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleResponseWithoutSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleResponseWithoutSignatureTask.java deleted file mode 100644 index 31bc28f5a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorHandleResponseWithoutSignatureTask.java +++ /dev/null @@ -1,441 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks.stork; - -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.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.AuthenticationServer; -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.servlet.PEPSConnectorWithLocalSigningServlet; -import at.gv.egovernment.moa.id.auth.stork.STORKException; -import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -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.StringUtils; - -import com.datentechnik.process_engine.api.ExecutionContext; - -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. - *

                - * In detail: - *

                  - *
                • Decodes and validates SAML response from C-PEPS.
                • - *
                • Retrieves the moa session using the session id provided by HttpServletRequest parameter {@code RelayState} or by {@code inResponseTo} attribute of the saml response.
                • - *
                • Store saml response in moa session.
                • - *
                • Change moa session id.
                • - *
                • Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@code moaSessionID} to be {@code null}
                • - *
                • HttpServletRequest parameter {@code signresponse} to be {@code null}
                • - *
                • HttpServletRequest parameter {@code SAMLResponse}
                • - *
                • Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute within the saml response, both reflecting the moa session id.
                • - *
                - * Result: - *
                  - *
                • Updated moa session (with saml response).
                • - *
                • Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.
                - * - * @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 Exception { - 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 IOException("should not occur"); - } - return; - } - - private void handleSAMLResponse(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) { - 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.validateSTORKAuthnResponse(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); - - // load MOASession from database - AuthenticationSession moaSession = AuthenticationServer.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); - - // //////////// incorporate gender from parameters if not in stork response - - IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); - - // 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 tmp = new ArrayList(); - tmp.add(gendervalue); - gender.setValue(tmp); - - authnResponse.getPersonalAttributeList().add(gender); - } - } - } - - - - // //////////////////////////////////////////////////////////////////////// - - Logger.debug("Starting extraction of signedDoc attribute"); - // extract signed doc element and citizen signature - String citizenSignature = null; - try { - PersonalAttribute signedDoc = authnResponse.getPersonalAttributeList().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(authnResponse.getPersonalAttributeList()); - - 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 = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); - String acsURL = issuerValue - + PEPSConnectorWithLocalSigningServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; - - String url = acsURL + "?moaSessionID=" + newMOASessionID; - // redirect to OASIS module and sign there - - boolean found = false; - try { - List aps = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()).getStorkAPs(); - Logger.info("Found AttributeProviderPlugins:" + aps.size()); - for (AttributeProviderPlugin 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, authnResponse.getPersonalAttributeList(), 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) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - - } - - 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", Base64.encodeBase64String(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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorTask.java deleted file mode 100644 index 0e4e2a0f7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/tasks/stork/PepsConnectorTask.java +++ /dev/null @@ -1,567 +0,0 @@ -package at.gv.egovernment.moa.id.auth.tasks.stork; - -import iaik.x509.X509Certificate; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -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 com.datentechnik.process_engine.api.ExecutionContext; - -import eu.stork.documentservice.DocumentService; -import eu.stork.documentservice.data.DatabaseConnectorMySQLImpl; -import eu.stork.oasisdss.api.ApiUtils; -import eu.stork.oasisdss.api.LightweightSourceResolver; -import eu.stork.oasisdss.api.exceptions.ApiUtilsException; -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; -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.stork.STORKException; -import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; -import at.gv.egovernment.moa.id.auth.tasks.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.StringUtils; -import at.gv.util.xsd.xmldsig.SignatureType; -import at.gv.util.xsd.xmldsig.X509DataType; - -/** - * Evaluates the SAML response from the C-PEPS and authenticates the user. - *

                - * In detail: - *

                  - *
                • Decodes and validates the SAML response from the C-PEPS.
                • - *
                • Change moa session id.
                • - *
                • Extracts the subject's gender from request parameter {@code gender} if not available from the saml response.
                • - *
                • Extracts the {@code signedDoc} attribute from the response, get signed doc payload using stork attribute query request.
                • - *
                • Request SZR gateway for verification of the citizen's signature and for creating of an identity link.
                • - *
                • 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).
                • - *
                • The moa session is updated with authentication information.
                • - *
                • Change moa session id.
                • - *
                • Redirects back to {@code /dispatcher} in order to finalize the authentication.
                • - *
                - * Expects: - *
                  - *
                • HttpServletRequest parameter {@code SAMLResponse}
                • - *
                • Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute from the SAML response (both depicting the moa session id)
                • - *
                • HttpServletRequest parameter {@code gender} in case the request comes from the gender selection form
                • - *
                • {@code signedDoc} attribute within the SAML response.
                • - *
                - * Result: - *
                  - *
                • Updated moa id session (identity link, stork attributes...)
                • - *
                • {@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.
                • - *
                • Redirect to {@code /dispatcher}.
                • - *
                - * Possible branches: - *
                  - *
                • In case the szr gateway throws exception due to missing gender information: - *
                    - *
                  • Returns a form for gender selection with action url back to this servlet/task.
                  • - *
                  - *
                • - *
                - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet}.
                - * - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - */ -public class PepsConnectorTask extends AbstractAuthServletTask { - - private String dtlUrl = null; - - public PepsConnectorTask() { - super(); - 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(); - } - } - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws Exception { - 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.validateSTORKAuthnResponse(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); - - // load MOASession from database - AuthenticationSession moaSession = AuthenticationServer.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); - - // //////////// incorporate gender from parameters if not in stork response - - IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); - - // 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 tmp = new ArrayList(); - tmp.add(gendervalue); - gender.setValue(tmp); - - authnResponse.getPersonalAttributeList().add(gender); - } - } - } - - // //////////////////////////////////////////////////////////////////////// - - Logger.debug("Starting extraction of signedDoc attribute"); - // extract signed doc element and citizen signature - String citizenSignature = null; - try { - String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING - - Logger.debug("signatureInfo:" + signatureInfo); - - SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource( - new java.io.StringReader(signatureInfo))); - - // fetch signed doc - DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse); - if (ds == null) { - throw new ApiUtilsException("No datasource found in response"); - } - - InputStream incoming = ds.getInputStream(); - citizenSignature = IOUtils.toString(incoming); - incoming.close(); - - Logger.debug("citizenSignature:" + citizenSignature); - if (isDocumentServiceUsed(citizenSignature) == true) { - Logger.debug("Loading document from DocumentService."); - String url = getDtlUrlFromResponse(dssSignResponse); - // get Transferrequest - String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url); - // Load document from DocujmentService - 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) 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) 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); - // } - OAAuthParameter oaParam = AuthConfigurationProvider.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; - executionContext.put("identityLinkAvailable", false); - try { - identityLink = STORKResponseProcessor.connectToSZRGateway(authnResponse.getPersonalAttributeList(), - 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); - } - 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(authnResponse.getPersonalAttributeList()); - - 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); - - // TODO: found better solution, but QAA Level in response could be not 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) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - - } - - private boolean isDocumentServiceUsed(String citizenSignature) // TODo add better check - { - if (citizenSignature - .contains("
                Service Name:{http://stork.eu}DocumentService
                Port Name:{http://stork.eu}DocumentServicePort
                ")) - return true; - 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 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 { - url = new URL(dtlUrl); - 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(dtlUrl)) - 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(dtlUrl); - 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); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java deleted file mode 100644 index cbe5c5932..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModuleImpl.java +++ /dev/null @@ -1,23 +0,0 @@ -package at.gv.egovernment.moa.id.moduls.moduleregistration; - -import com.datentechnik.process_engine.api.ExecutionContext; - -public class AuthModuleImpl implements AuthModule { - - @Override - public int getPriority() { - // neutral priority between Integer.MIN_VALUE and Integer.MAX_VALUE - return 0; - } - - @Override - public String selectProcess(ExecutionContext context) { - return context.get("ccc") == null ? "DefaultAuthentication" : null; - } - - @Override - public String[] getProcessDefinitions() { - return new String[] { "DefaultAuthentication" }; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java index b90e0d94f..35fbce053 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java @@ -32,13 +32,13 @@ public class ModuleRegistration { private static ModuleRegistration instance = new ModuleRegistration(); - private List orderedModules = new ArrayList<>(); + private List priorizedModules = new ArrayList<>(); @Autowired private ApplicationContext ctx; @Autowired - ProcessEngine processEngine; + private ProcessEngine processEngine; private Logger log = LoggerFactory.getLogger(getClass()); @@ -58,20 +58,21 @@ public class ModuleRegistration { initSpringModules(); // order modules according to their priority - orderModules(); + priorizeModules(); } /** * Discovers modules which use the ServiceLoader mechanism. */ private void initServiceLoaderModules() { - log.debug("Discovering modules which use the ServiceLoader mechanism."); + log.info("Looking for auth modules."); ServiceLoader loader = ServiceLoader.load(AuthModule.class); Iterator modules = loader.iterator(); while (modules.hasNext()) { AuthModule module = modules.next(); + log.info("Detected module {}", module.getClass().getName()); registerResourceUris(module); - orderedModules.add(module); + priorizedModules.add(module); } } @@ -83,7 +84,7 @@ public class ModuleRegistration { Map modules = ctx.getBeansOfType(AuthModule.class); for (AuthModule module : modules.values()) { registerResourceUris(module); - orderedModules.add(module); + priorizedModules.add(module); } } @@ -96,17 +97,17 @@ public class ModuleRegistration { private void registerResourceUris(AuthModule module) { for (String uri : module.getProcessDefinitions()) { Resource resource = ctx.getResource(uri); - if (resource.exists()) { - log.debug("Registering process definition resource uri: '{}'.", resource); + if (resource.isReadable()) { + log.info("Registering process definition resource: '{}'.", resource); try (InputStream processDefinitionInputStream = resource.getInputStream()) { processEngine.registerProcessDefinition(processDefinitionInputStream); } catch (IOException e) { - log.info("Resource uri: '{}' could NOT be read.", resource); + log.error("Resource uri: '{}' could NOT be read.", uri, e); } catch (ProcessDefinitionParserException e) { - log.warn("Error while parsing process definition in '{}'", resource); + log.error("Error while parsing process definition in '{}'", uri, e); } } else { - log.info("Resource uri: '{}' does NOT exist.", resource); + log.error("Resource uri: '{}' cannot be read.", uri); } } } @@ -114,8 +115,8 @@ public class ModuleRegistration { /** * Order the modules in descending order according to their priority. */ - private void orderModules() { - Collections.sort(orderedModules, new Comparator() { + private void priorizeModules() { + Collections.sort(priorizedModules, new Comparator() { @Override public int compare(AuthModule thisAuthModule, AuthModule otherAuthModule) { int thisOrder = thisAuthModule.getPriority(); @@ -135,7 +136,7 @@ public class ModuleRegistration { * @return the process id or {@code null} */ public String selectProcess(ExecutionContext context) { - for (AuthModule module : orderedModules) { + for (AuthModule module : priorizedModules) { String id = module.selectProcess(context); if (StringUtils.isNotEmpty(id)) { log.debug("Process with id '{}' selected, for context '{}'.", id, context); -- cgit v1.2.3 From c6f543e06c02c0a2635eac2e9b99c2554e6e27bd Mon Sep 17 00:00:00 2001 From: Christian Wagner Date: Thu, 29 Jan 2015 14:39:11 +0100 Subject: integrate process engine from project 'dti-process-engine' - fix unit tests - correct namespaces - refactor package name --- .../java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java index 6b245f013..162ee624a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java @@ -43,7 +43,7 @@ import at.gv.egovernment.moa.id.process.model.Transition; */ public class ProcessDefinitionParser { - private static final String NS = "http://www.datentechnik.com/process-engine/processdefinition/v1"; + private static final String NS = "http://reference.e-government.gv.at/namespace/moa/process/definition/v1"; private static Logger log = LoggerFactory.getLogger(ProcessDefinitionParser.class); -- cgit v1.2.3 From 28c91fd13c97e679666a43a57012d27518768dfd Mon Sep 17 00:00:00 2001 From: Gerwin Gsenger Date: Thu, 29 Jan 2015 15:24:47 +0100 Subject: add inital (empty) implementation of the ProcessInstanceStoreDAO --- .../moa/id/process/dao/ProcessInstanceStore.java | 13 ++++++++++- .../id/process/dao/ProcessInstanceStoreDAO.java | 26 ++++++++++++++++++++++ .../process/dao/ProcessInstanceStoreDAOImpl.java | 25 +++++++++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java index 5270e036a..ab71ef54d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -10,13 +10,16 @@ import javax.persistence.Table; @Table(name = "process_instance") public class ProcessInstanceStore { - @Column(name = "id", unique = true, nullable = false) + @Column(name = "id") @Id private String id; @Column(name = "processDefinitionID", unique = true, nullable = false) private String processDefinitionID; + @Column(name = "pointer", nullable = false) + private String pointer; + @Column(name = "executionContextData", nullable = false) @Lob private byte[] executionContextData; @@ -29,6 +32,10 @@ public class ProcessInstanceStore { return processDefinitionID; } + public String getPointer() { + return pointer; + } + public byte[] getExecutionContextData() { return executionContextData; } @@ -41,6 +48,10 @@ public class ProcessInstanceStore { this.processDefinitionID = processDefinitionID; } + public void setPointer(String pointer) { + this.pointer = pointer; + } + public void setExecutionContextData(byte[] executionContextData) { this.executionContextData = executionContextData; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java new file mode 100644 index 000000000..5e2b12349 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java @@ -0,0 +1,26 @@ +package at.gv.egovernment.moa.id.process.dao; + +import at.gv.egovernment.moa.id.process.ProcessInstance; + +public interface ProcessInstanceStoreDAO { + + /** + * Stores a {@link ProcessInstance} defined by {@code pIStore} in the + * database. + * + * @param pIStore + * the {@link ProcessInstanceStore} to persist. + */ + public void save(ProcessInstanceStore pIStore); + + /** + * Loads a {@link ProcessInstanceStore}, defined by + * {@code processInstanceID} from the database. + * + * @param processInstanceID + * the id of the {@code ProcessInstanceStore} to retrieve. + * @return a ProcessInstanceStore. + */ + public ProcessInstanceStore load(String processInstanceID); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java new file mode 100644 index 000000000..3480c4cfc --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -0,0 +1,25 @@ +package at.gv.egovernment.moa.id.process.dao; + + + +public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { + + private static ProcessInstanceStoreDAO instance = new ProcessInstanceStoreDAOImpl(); + + public static ProcessInstanceStoreDAO getInstance() { + return instance; + } + + @Override + public void save(ProcessInstanceStore pIStore) { + // TODO Auto-generated method stub + + } + + @Override + public ProcessInstanceStore load(String processInstanceID) { + // TODO Auto-generated method stub + return null; + } + +} -- cgit v1.2.3 From fca585327afd4fd3dc0b5f1146cbb5d8648c3a41 Mon Sep 17 00:00:00 2001 From: Gerwin Gsenger Date: Thu, 29 Jan 2015 16:54:28 +0100 Subject: add new methods to the dao interface, enhance db entity --- .../moa/id/process/dao/ProcessInstanceStore.java | 64 +++++++++++++++------- .../id/process/dao/ProcessInstanceStoreDAO.java | 34 +++++++++++- .../process/dao/ProcessInstanceStoreDAOImpl.java | 34 ++++++++++-- 3 files changed, 105 insertions(+), 27 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java index ab71ef54d..c94c95516 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -1,58 +1,80 @@ package at.gv.egovernment.moa.id.process.dao; +import java.io.Serializable; +import java.util.Map; + import javax.persistence.Column; import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; +import at.gv.egovernment.moa.id.process.ProcessInstanceState; + @Entity -@Table(name = "process_instance") +@Table(name = "processinstance") public class ProcessInstanceStore { @Column(name = "id") @Id - private String id; + private int id; + + @Column(name = "processInstanceId", unique = true, nullable = false) + private String processInstanceId; + + @Column(name = "processDefinitionId", nullable = false) + private String processDefinitionId; - @Column(name = "processDefinitionID", unique = true, nullable = false) - private String processDefinitionID; + @Column(name = "nextTaskId", nullable = false) + private String nextTaskId; - @Column(name = "pointer", nullable = false) - private String pointer; + @Column(name = "processState", nullable = false) + @Enumerated(value = EnumType.STRING) + private Enum processState; @Column(name = "executionContextData", nullable = false) @Lob - private byte[] executionContextData; + private Map executionContextData; - public String getId() { - return id; + public String getProcessInstanceId() { + return processInstanceId; } - public String getProcessDefinitionID() { - return processDefinitionID; + public String getProcessDefinitionId() { + return processDefinitionId; } - public String getPointer() { - return pointer; + public String getNextTaskId() { + return nextTaskId; } - public byte[] getExecutionContextData() { + public Enum getProcessState() { + return processState; + } + + public Map getExecutionContextData() { return executionContextData; } - public void setId(String id) { - this.id = id; + public void setProcessInstanceId(String processInstanceId) { + this.processInstanceId = processInstanceId; + } + + public void setProcessDefinitionId(String processDefinitionId) { + this.processDefinitionId = processDefinitionId; } - public void setProcessDefinitionID(String processDefinitionID) { - this.processDefinitionID = processDefinitionID; + public void setNextTaskId(String nextTaskId) { + this.nextTaskId = nextTaskId; } - public void setPointer(String pointer) { - this.pointer = pointer; + public void setProcessState(Enum processState) { + this.processState = processState; } - public void setExecutionContextData(byte[] executionContextData) { + public void setExecutionContextData(Map executionContextData) { this.executionContextData = executionContextData; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java index 5e2b12349..57489c33e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java @@ -1,5 +1,7 @@ package at.gv.egovernment.moa.id.process.dao; +import java.util.List; + import at.gv.egovernment.moa.id.process.ProcessInstance; public interface ProcessInstanceStoreDAO { @@ -11,7 +13,7 @@ public interface ProcessInstanceStoreDAO { * @param pIStore * the {@link ProcessInstanceStore} to persist. */ - public void save(ProcessInstanceStore pIStore); + void save(ProcessInstanceStore pIStore); /** * Loads a {@link ProcessInstanceStore}, defined by @@ -21,6 +23,34 @@ public interface ProcessInstanceStoreDAO { * the id of the {@code ProcessInstanceStore} to retrieve. * @return a ProcessInstanceStore. */ - public ProcessInstanceStore load(String processInstanceID); + ProcessInstanceStore load(String processInstanceId); + + /** + * Deletes the {@link ProcessInstance} corresponding with the + * {@code processInstanceId}. + * + * @param processInstanceID + * the id of the {@code ProcessInstance} to be deleted. + */ + void remove(String processInstanceId); + + /** + * Returns all {@link ProcessInstanceStore} objects stored in the database. + * The returned list may be empty, but never {@code null}. + * + * @return a list of {@link ProcessInstanceStore} (never {@code null}). + */ + List getAllProcessInstanceStores(); + + /** + * Returns the specific {@link ProcessInstanceStore} object corresponding to + * the given {@code processInstanceId}, or {@code null} if the object could + * not be found. + * + * @param processInstanceId + * the processInstanceId to search. + * @return the ProcessInstanceStore for the given id, or {@code null}. + */ + ProcessInstanceStore getProcessInstance(String processInstanceId); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index 3480c4cfc..cde34acd1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -1,19 +1,27 @@ package at.gv.egovernment.moa.id.process.dao; +import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +/** + * Database backed implementation of the {@link ProcessInstanceStoreDAO} + * interface. + */ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { - + + private Logger log = LoggerFactory.getLogger(getClass()); + private static ProcessInstanceStoreDAO instance = new ProcessInstanceStoreDAOImpl(); - + public static ProcessInstanceStoreDAO getInstance() { return instance; } - + @Override public void save(ProcessInstanceStore pIStore) { // TODO Auto-generated method stub - } @Override @@ -22,4 +30,22 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { return null; } + @Override + public void remove(String processInstanceId) { + // TODO Auto-generated method stub + + } + + @Override + public List getAllProcessInstanceStores() { + // TODO Auto-generated method stub + return null; + } + + @Override + public ProcessInstanceStore getProcessInstance(String processInstanceId) { + // TODO Auto-generated method stub + return null; + } + } -- cgit v1.2.3 From 88f2ac75cf316c755e35303cf2d6faa2343b9408 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Thu, 29 Jan 2015 17:13:21 +0100 Subject: Perform some cleanup - Remove ProcessDefinitionFactoryBean from applicationContext.xml. - Minor code cleanup. --- .../moa/id/moduls/moduleregistration/ModuleRegistration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java index 35fbce053..7e16cf637 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java @@ -98,7 +98,7 @@ public class ModuleRegistration { for (String uri : module.getProcessDefinitions()) { Resource resource = ctx.getResource(uri); if (resource.isReadable()) { - log.info("Registering process definition resource: '{}'.", resource); + log.info("Registering process definition resource: '{}'.", uri); try (InputStream processDefinitionInputStream = resource.getInputStream()) { processEngine.registerProcessDefinition(processDefinitionInputStream); } catch (IOException e) { -- cgit v1.2.3 From 6371e01c520de77b0f37f59c72dbe20fce88c91a Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Fri, 30 Jan 2015 08:53:27 +0100 Subject: Add Spring based discovery for STORKAuthModule - Add wildcard import to applicationContext.xml - Add some javadoc to AuthModule interface. - Remove STORKAuthModuleImpl from serviceloader based registration. --- .../modules/internal/DefaultAuthModuleImpl.java | 4 +++- .../auth/modules/stork/STORK.authmodule.beans.xml | 14 +++++++++++++ .../id/auth/modules/stork/STORKAuthModuleImpl.java | 17 ++++++++++++++-- .../id/moduls/moduleregistration/AuthModule.java | 23 +++++++++++----------- 4 files changed, 44 insertions(+), 14 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java index 99c28fd7f..35c7e5c79 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java @@ -6,11 +6,13 @@ import at.gv.egovernment.moa.id.moduls.moduleregistration.AuthModule; import com.datentechnik.process_engine.api.ExecutionContext; +/** + * Module descriptor + */ public class DefaultAuthModuleImpl implements AuthModule { @Override public int getPriority() { - // neutral priority between Integer.MIN_VALUE and Integer.MAX_VALUE return 0; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml new file mode 100644 index 000000000..2e924bdd0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml @@ -0,0 +1,14 @@ + + + + + + + + + + diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java index 140334b36..52423166a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java @@ -6,12 +6,25 @@ import com.datentechnik.process_engine.api.ExecutionContext; import at.gv.egovernment.moa.id.moduls.moduleregistration.AuthModule; +/** + * 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() { - // neutral priority between Integer.MIN_VALUE and Integer.MAX_VALUE - return 0; + 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 diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java index 35273cd2b..fa0149c17 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java @@ -9,31 +9,32 @@ import com.datentechnik.process_engine.model.ProcessDefinition; public interface AuthModule { /** - * Returns the priority of the module. The priority defines the place in the - * order of modules. The module with a highest priority is asked first, if - * it has a process which can do an authentication. + * Returns the priority of the module. The priority defines the order of the respective module within the chain of + * discovered modules. Higher priorized modules are asked before lower priorized modules for a process that they can + * handle. + *

                + * Internal default modules are priorized neutral ({@code 0}. Use a higher priority ({@code 1...Integer.MAX_VALUE}) + * in order to have your module(s) priorized or a lower priority ({@code Integer.MIN_VALUE...-1}) in order to put + * your modules behind default modules. * * @return the priority of the module. */ int getPriority(); /** - * Checks if the module has a process, which is able to perform an authentication - * with the given {@link ExecutionContext}. + * Checks if the module has a process, which is able to perform an authentication with the given + * {@link ExecutionContext}. * * @param context * an ExecutionContext for a process. - * @return the process-ID of a process which is able to work with the given - * ExecutionContext, or {@code null}. + * @return the process-ID of a process which is able to work with the given ExecutionContext, or {@code null}. */ String selectProcess(ExecutionContext context); /** - * Returns the an Array of {@link ProcessDefinition}s of the processes - * included in this module. + * Returns the an Array of {@link ProcessDefinition}s of the processes included in this module. * - * @return an array of resource uris of the processes included in this - * module. + * @return an array of resource uris of the processes included in this module. */ String[] getProcessDefinitions(); -- cgit v1.2.3 From 373641cfb0e404e89f4d9a011ae53d8b8cfc06c5 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Fri, 30 Jan 2015 10:45:59 +0100 Subject: Add dynamic servlet registration for STORK processes. - Add STORKWebApplicationInitializer.java - Adjust web.xml - Move STORK.authmodule.beans.xml to src/main/resources/... --- .../auth/modules/stork/STORK.authmodule.beans.xml | 14 -------- .../stork/STORKWebApplicationInitializer.java | 37 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 14 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKWebApplicationInitializer.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml deleted file mode 100644 index 2e924bdd0..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKWebApplicationInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKWebApplicationInitializer.java new file mode 100644 index 000000000..7478a57c3 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKWebApplicationInitializer.java @@ -0,0 +1,37 @@ +package at.gv.egovernment.moa.id.auth.modules.stork; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; + +import at.gv.egovernment.moa.id.auth.servlet.ProcessEngineSignalServlet; + +/** + * Spring automatically discovers {@link WebApplicationInitializer} implementations at startup.
                + * This STORK webapp initializer adds the required servlet mappings: + *

                  + *
                • {@code /PEPSConnector}
                • + *
                • {@code /PEPSConnectorWithLocalSigning}
                • + *
                + * for the {@linkplain ProcessEngineSignalServlet process engine servlet} (named {@code ProcessEngineSignal}) that wakes + * up a process in order to execute asynchronous tasks. Therefore the servlet mappings mentioned above do not need to be + * declared in {@code web.xml}. + * + * @author tknall + * @see ProcessEngineSignalServlet + */ +public class STORKWebApplicationInitializer implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + ServletRegistration servletRegistration = servletContext.getServletRegistration("ProcessEngineSignal"); + if (servletRegistration == null) { + throw new IllegalStateException("Servlet 'ProcessEngineSignal' expected to be registered."); + } + servletRegistration.addMapping("/PEPSConnectorWithLocalSigning"); + servletRegistration.addMapping("/PEPSConnector"); + } + +} -- cgit v1.2.3 From 4b8f2b481636ef71146d382f386f9c297da7a64b Mon Sep 17 00:00:00 2001 From: Gerwin Gsenger Date: Fri, 30 Jan 2015 11:11:40 +0100 Subject: implement DAO methods, add exeptions to ProcessInstanceStoreDAO interface --- .../id/config/auth/AuthConfigurationProvider.java | 3 +- .../id/process/dao/ProcessInstanceStoreDAO.java | 35 ++++----- .../process/dao/ProcessInstanceStoreDAOImpl.java | 91 ++++++++++++++++++---- 3 files changed, 95 insertions(+), 34 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index a67badf49..0dfd2236f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -110,10 +110,10 @@ import at.gv.egovernment.moa.id.config.auth.data.ProtocolAllowed; import at.gv.egovernment.moa.id.config.legacy.BuildFromLegacyConfig; import at.gv.egovernment.moa.id.config.stork.STORKConfig; import at.gv.egovernment.moa.id.data.IssuerAndSerial; +import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStore; import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.util.config.EgovUtilConfiguration; import at.gv.util.config.EgovUtilPropertiesConfiguration; /** @@ -344,6 +344,7 @@ public class AuthConfigurationProvider extends ConfigurationProvider { config.addAnnotatedClass(OldSSOSessionIDStore.class); config.addAnnotatedClass(ExceptionStore.class); config.addAnnotatedClass(InterfederationSessionStore.class); + config.addAnnotatedClass(ProcessInstanceStore.class); config.addProperties(moaSessionProp); MOASessionDBUtils.initHibernate(config, moaSessionProp); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java index 57489c33e..0aa6f80cd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java @@ -2,6 +2,7 @@ package at.gv.egovernment.moa.id.process.dao; import java.util.List; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.process.ProcessInstance; public interface ProcessInstanceStoreDAO { @@ -12,18 +13,23 @@ public interface ProcessInstanceStoreDAO { * * @param pIStore * the {@link ProcessInstanceStore} to persist. + * @throws MOADatabaseException + * is thrown if a problem occurs while accessing the database. */ - void save(ProcessInstanceStore pIStore); + void save(ProcessInstanceStore pIStore) throws MOADatabaseException; /** - * Loads a {@link ProcessInstanceStore}, defined by - * {@code processInstanceID} from the database. + * Returns a {@link ProcessInstanceStore}, defined by + * {@code processInstanceID} from the database, or {@code null} if the + * object could not be found. * * @param processInstanceID * the id of the {@code ProcessInstanceStore} to retrieve. - * @return a ProcessInstanceStore. + * @return a ProcessInstanceStore, or {@code null}. + * @throws MOADatabaseException + * is thrown if a problem occurs while accessing the database. */ - ProcessInstanceStore load(String processInstanceId); + ProcessInstanceStore load(String processInstanceId) throws MOADatabaseException; /** * Deletes the {@link ProcessInstance} corresponding with the @@ -31,26 +37,19 @@ public interface ProcessInstanceStoreDAO { * * @param processInstanceID * the id of the {@code ProcessInstance} to be deleted. + * @throws MOADatabaseException + * is thrown if a problem occurs while accessing the database. */ - void remove(String processInstanceId); + void remove(String processInstanceId) throws MOADatabaseException; /** * Returns all {@link ProcessInstanceStore} objects stored in the database. * The returned list may be empty, but never {@code null}. * * @return a list of {@link ProcessInstanceStore} (never {@code null}). + * @throws MOADatabaseException + * is thrown if a problem occurs while accessing the database. */ - List getAllProcessInstanceStores(); - - /** - * Returns the specific {@link ProcessInstanceStore} object corresponding to - * the given {@code processInstanceId}, or {@code null} if the object could - * not be found. - * - * @param processInstanceId - * the processInstanceId to search. - * @return the ProcessInstanceStore for the given id, or {@code null}. - */ - ProcessInstanceStore getProcessInstance(String processInstanceId); + List getAllProcessInstanceStores() throws MOADatabaseException; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index cde34acd1..f5fb71145 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -1,10 +1,18 @@ package at.gv.egovernment.moa.id.process.dao; +import java.util.Collections; import java.util.List; +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; + /** * Database backed implementation of the {@link ProcessInstanceStoreDAO} * interface. @@ -20,32 +28,85 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { } @Override - public void save(ProcessInstanceStore pIStore) { - // TODO Auto-generated method stub + public void save(ProcessInstanceStore pIStore) throws MOADatabaseException { + try { + MOASessionDBUtils.saveOrUpdate(pIStore); + log.debug("Store process instance with='{}' in the database.", pIStore.getProcessInstanceId()); + } catch (MOADatabaseException e) { + log.warn("ProcessInstanceStore could not be persisted to the database."); + throw e; + } } @Override - public ProcessInstanceStore load(String processInstanceID) { - // TODO Auto-generated method stub - return null; - } + public ProcessInstanceStore load(String processInstanceId) throws MOADatabaseException { - @Override - public void remove(String processInstanceId) { - // TODO Auto-generated method stub + log.debug("Retrieve the ProcessInstanceStore for id='{}' from the database.", processInstanceId); + Session session = MOASessionDBUtils.getCurrentSession(); + ProcessInstanceStore result = null; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + // select all where processInstanceId equals processInstanceId + Criteria criteria = session.createCriteria(ProcessInstanceStore.class); + criteria.add(Restrictions.eq("processInstanceId", processInstanceId)); + result = (ProcessInstanceStore) criteria.uniqueResult(); + tx.commit(); + } + } catch (Exception e) { + log.error("There are multiple persisted processes with the same process instance id '{}'", + processInstanceId); + if (tx != null) { + tx.rollback(); + } + throw e; + } finally { + MOASessionDBUtils.closeSession(); + } + return result; } @Override - public List getAllProcessInstanceStores() { - // TODO Auto-generated method stub - return null; + public void remove(String processInstanceId) throws MOADatabaseException { + + log.debug("Delete the ProcessInstanceStore for id='{}' from the database.", processInstanceId); + + ProcessInstanceStore toBeDeleted = load(processInstanceId); + boolean result = MOASessionDBUtils.delete(toBeDeleted); + if (result == false) { + log.warn("Could not delete the ProcessInstanceStore with process instance id '{}'", processInstanceId); + throw new MOADatabaseException("Could not delete the ProcessInstanceStore with process instance id '" + + processInstanceId + "'."); + } } + @SuppressWarnings("unchecked") @Override - public ProcessInstanceStore getProcessInstance(String processInstanceId) { - // TODO Auto-generated method stub - return null; + public List getAllProcessInstanceStores() throws MOADatabaseException { + log.debug("Retrieve a list with all ProcessInstanceStores from the database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result = Collections.emptyList(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + // select all + result = session.createCriteria(ProcessInstanceStore.class).list(); + tx.commit(); + } + } catch (Exception e) { + log.error("A problem occured while retrieving all stored ProcessInstanceStores."); + if (tx != null) { + tx.rollback(); + } + throw e; + } finally { + MOASessionDBUtils.closeSession(); + } + return result; } } -- cgit v1.2.3 From 78a3caea21bdd5475007b958d59b23b1d3deccfb Mon Sep 17 00:00:00 2001 From: Gerwin Gsenger Date: Fri, 30 Jan 2015 12:27:45 +0100 Subject: small DAO code review from Thomas --- .../process/dao/ProcessInstanceStoreDAOImpl.java | 50 ++++++++++++---------- 1 file changed, 27 insertions(+), 23 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index f5fb71145..4b7468013 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -46,24 +46,26 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { ProcessInstanceStore result = null; Transaction tx = null; - try { - synchronized (session) { + synchronized (session) { + try { + tx = session.beginTransaction(); // select all where processInstanceId equals processInstanceId Criteria criteria = session.createCriteria(ProcessInstanceStore.class); criteria.add(Restrictions.eq("processInstanceId", processInstanceId)); result = (ProcessInstanceStore) criteria.uniqueResult(); tx.commit(); + + } catch (Exception e) { + log.error("There are multiple persisted processes with the same process instance id '{}'", + processInstanceId); + if (tx != null) { + tx.rollback(); + } + throw e; + } finally { + MOASessionDBUtils.closeSession(); } - } catch (Exception e) { - log.error("There are multiple persisted processes with the same process instance id '{}'", - processInstanceId); - if (tx != null) { - tx.rollback(); - } - throw e; - } finally { - MOASessionDBUtils.closeSession(); } return result; } @@ -74,8 +76,8 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { log.debug("Delete the ProcessInstanceStore for id='{}' from the database.", processInstanceId); ProcessInstanceStore toBeDeleted = load(processInstanceId); - boolean result = MOASessionDBUtils.delete(toBeDeleted); - if (result == false) { + boolean deleted = MOASessionDBUtils.delete(toBeDeleted); + if (!deleted) { log.warn("Could not delete the ProcessInstanceStore with process instance id '{}'", processInstanceId); throw new MOADatabaseException("Could not delete the ProcessInstanceStore with process instance id '" + processInstanceId + "'."); @@ -90,21 +92,23 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { List result = Collections.emptyList(); Transaction tx = null; - try { - synchronized (session) { + synchronized (session) { + try { + tx = session.beginTransaction(); // select all result = session.createCriteria(ProcessInstanceStore.class).list(); tx.commit(); + + } catch (Exception e) { + log.error("A problem occured while retrieving all stored ProcessInstanceStores."); + if (tx != null) { + tx.rollback(); + } + throw e; + } finally { + MOASessionDBUtils.closeSession(); } - } catch (Exception e) { - log.error("A problem occured while retrieving all stored ProcessInstanceStores."); - if (tx != null) { - tx.rollback(); - } - throw e; - } finally { - MOASessionDBUtils.closeSession(); } return result; } -- cgit v1.2.3 From 23fc42a3c273ceb05938c741508537bfaedab00a Mon Sep 17 00:00:00 2001 From: Christian Wagner Date: Fri, 30 Jan 2015 14:24:45 +0100 Subject: add persistence to process-engine additionally remove unnecessary method in the DAO --- .../servlet/GenerateIFrameTemplateServlet.java | 15 +- .../auth/servlet/ProcessEngineSignalServlet.java | 3 +- .../moa/id/moduls/AuthenticationManager.java | 12 +- .../egovernment/moa/id/process/ProcessEngine.java | 57 +++--- .../moa/id/process/ProcessEngineImpl.java | 191 ++++++++++++++------- .../moa/id/process/dao/ProcessInstanceStore.java | 6 +- .../id/process/dao/ProcessInstanceStoreDAO.java | 10 -- .../process/dao/ProcessInstanceStoreDAOImpl.java | 29 ---- .../id/storage/AuthenticationSessionStoreage.java | 20 ++- 9 files changed, 176 insertions(+), 167 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index 7f53a1a13..d6c15c658 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -155,7 +155,7 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { // select and create process instance String processDefinitionId = ModuleRegistration.getInstance().selectProcess(ec); - ProcessInstance pi = getProcessEngine().createProcessInstance(processDefinitionId, ec); + String processInstanceId = getProcessEngine().createProcessInstance(processDefinitionId, ec); if (processDefinitionId == null) { Logger.warn("No suitable process found for SessionID " + moasession.getSessionID()); @@ -163,21 +163,20 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { } // keep process instance id in moa session - moasession.setProcessInstanceId(pi.getId()); + moasession.setProcessInstanceId(processInstanceId); // make sure moa session has been persisted before running the process try { AuthenticationSessionStoreage.storeSession(moasession); } catch (MOADatabaseException e) { Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { - moasession.getSessionID()}); + throw new MOAIDException("init.04", new Object[] { moasession.getSessionID() }); } - - // start process - getProcessEngine().start(pi); - } + // start process + getProcessEngine().start(processInstanceId); + + } catch (WrongParametersException ex) { handleWrongParameters(ex, req, resp); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java index c172124d2..4aff6ba38 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -72,8 +72,7 @@ public class ProcessEngineSignalServlet extends AuthServlet { } // wake up next task - ProcessInstance pi = getProcessEngine().getProcessInstance(session.getProcessInstanceId()); - getProcessEngine().signal(pi); + getProcessEngine().signal(session.getProcessInstanceId()); } catch (Exception ex) { handleError(null, ex, req, resp, null); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index ffb5e3d65..0a7f71713 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -80,7 +80,6 @@ import at.gv.egovernment.moa.id.moduls.moduleregistration.ModuleRegistration; import at.gv.egovernment.moa.id.process.ExecutionContextImpl; import at.gv.egovernment.moa.id.process.ProcessEngine; import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.id.process.ProcessInstance; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; @@ -324,7 +323,7 @@ public class AuthenticationManager implements MOAIDAuthConstants { try { authSession = AuthenticationSessionStoreage .getSession(moaSessionID); - + if(authSession == null) { Logger.info("NO MOA Authentication data for ID " + moaSessionID); return; @@ -562,9 +561,10 @@ public class AuthenticationManager implements MOAIDAuthConstants { moasession.getSessionID()}); } - ProcessInstance pi = processEngine.createProcessInstance(processDefinitionId, executionContext); + String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); + // keep process instance id in moa session - moasession.setProcessInstanceId(pi.getId()); + moasession.setProcessInstanceId(processInstanceId); // make sure moa session has been persisted before running the process try { @@ -574,9 +574,9 @@ public class AuthenticationManager implements MOAIDAuthConstants { throw new MOAIDException("init.04", new Object[] { moasession.getSessionID()}); } - + // start process - processEngine.start(pi); + processEngine.start(processInstanceId); } else { //load Parameters from OnlineApplicationConfiguration diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java index 2d9dcff8e..535070107 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java @@ -31,35 +31,35 @@ public interface ProcessEngine { void registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException; /** - * Creates a process instance according to the referenced process definition. + * Creates a process instance according to the referenced process definition, persists it into the database and returns it identifier. *

                - * Note that the method returns a process instance which will be needed in order to start a process or to continue - * process execution after asynchronous task execution (refer to {@link #start(ProcessInstance)} and - * {@link #signal(ProcessInstance)} for further information). + * Note that the method returns the identifier of a process instance which will be needed in order to start a process or to continue + * process execution after asynchronous task execution (refer to {@link #start(String)} and + * {@link #signal(String)} for further information). * * @param processDefinitionId * The identifier of the respective process definition. * @param executionContext The execution context (may be {@code null}). - * @return The newly created process instance (never {@code null}). + * @return The id of the newly created process instance (never {@code null}). * @throws ProcessExecutionException * Thrown in case of error, e.g. when a {@code processDefinitionId} is referenced that does not exist. */ - ProcessInstance createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException; + String createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException; /** - * Creates a process instance according to the referenced process definition. + * Creates a process instance according to the referenced process definition, persists it into the database and returns it identifier. *

                - * Note that the method returns a process instance which will be needed in order to start a process or to continue - * process execution after asynchronous task execution (refer to {@link #start(ProcessInstance)} and - * {@link #signal(ProcessInstance)} for further information). + * Note that the method returns the identifier of a process instance which will be needed in order to start a process or to continue + * process execution after asynchronous task execution (refer to {@link #start(String))} and + * {@link #signal(String)} for further information). * * @param processDefinitionId * The identifier of the respective process definition. - * @return The newly created process instance (never {@code null}). + * @return The id of the newly created process instance (never {@code null}). * @throws ProcessExecutionException * Thrown in case of error, e.g. when a {@code processDefinitionId} is referenced that does not exist. */ - ProcessInstance createProcessInstance(String processDefinitionId) throws ProcessExecutionException; + String createProcessInstance(String processDefinitionId) throws ProcessExecutionException; /** * Returns the process instance with a given {@code processInstanceId}. @@ -73,41 +73,24 @@ public interface ProcessEngine { ProcessInstance getProcessInstance(String processInstanceId); /** - * Starts the process using the given {@code processInstance}. + * Starts the process using the given {@code processInstanceId}. * - * @param processInstance - * The process instance. + * @param processInstanceId + * The process instance id. * @throws ProcessExecutionException * Thrown in case of error. */ - void start(ProcessInstance processInstance) throws ProcessExecutionException; + void start(String processInstanceId) throws ProcessExecutionException; + /** * Resumes process execution after an asynchronous task has been executed. * - * @param processInstance - * The process instance. + * @param processInstanceId + * The process instance id. * @throws ProcessExecutionException * Thrown in case of error. */ - void signal(ProcessInstance processInstance) throws ProcessExecutionException; - - /** - * Performs cleanup, removing all process instances that have not been used for a certain time. - * - * @see #setProcessInstanceMaxIdleTimeSeconds(long) - */ - void cleanup(); - - /** - * Returns the first process instance with a process context containing some {@code value} stored under key {@code key}. - * - * @param key - * The key. - * @param value - * The value that needs to match. - * @return The process instance or {@code null} in case no process instance was found. - */ - ProcessInstance findProcessInstanceWith(String key, Serializable value); + void signal(String processInstanceId) throws ProcessExecutionException; } \ No newline at end of file diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java index 3ba8fb9ed..8af9e1b69 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java @@ -2,11 +2,8 @@ package at.gv.egovernment.moa.id.process; import java.io.InputStream; import java.io.Serializable; -import java.util.Date; -import java.util.Iterator; +import java.util.HashMap; import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.collections4.CollectionUtils; @@ -16,10 +13,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; import at.gv.egovernment.moa.id.process.api.ExpressionEvaluator; import at.gv.egovernment.moa.id.process.api.Task; +import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStore; +import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAO; +import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAOImpl; import at.gv.egovernment.moa.id.process.model.EndEvent; import at.gv.egovernment.moa.id.process.model.ProcessDefinition; import at.gv.egovernment.moa.id.process.model.ProcessNode; @@ -33,21 +34,20 @@ import at.gv.egovernment.moa.id.process.model.Transition; * */ public class ProcessEngineImpl implements ProcessEngine { - + private Logger log = LoggerFactory.getLogger(getClass()); - + private ProcessDefinitionParser pdp = new ProcessDefinitionParser(); + ProcessInstanceStoreDAO piStoreDao = ProcessInstanceStoreDAOImpl.getInstance(); + private Map processDefinitions = new ConcurrentHashMap(); - private Map processInstances = new ConcurrentHashMap(); - + private final static String MDC_CTX_PI_NAME = "processInstanceId"; private final static String MDC_CTX_TASK_NAME = "taskId"; - - private static final long DEFAULT_PROCESS_INSTANCE_MAX_AGE_SECONDS = 3600; - private long processInstanceIdleTimeSeconds = DEFAULT_PROCESS_INSTANCE_MAX_AGE_SECONDS; + private ExpressionEvaluator transitionConditionExpressionEvaluator; - + @Override public void registerProcessDefinition(ProcessDefinition processDefinition) { log.info("Registering process definition '{}'.", processDefinition.getId()); @@ -61,7 +61,7 @@ public class ProcessEngineImpl implements ProcessEngine { /** * Sets the process definitions. - * + * * @param processDefinitions * The process definitions. * @throws IllegalArgumentException @@ -76,19 +76,6 @@ public class ProcessEngineImpl implements ProcessEngine { registerProcessDefinition(pd); } } - - /** - * Defines the time frame in seconds an idle process instance will be managed by the process engine. A process - * instance with an idle time larger than the given time will be removed. - *

                - * Note that {@link #cleanup()} needs to be called in order to remove expired process instances. - * - * @param processInstanceMaxIdleTimeSeconds - * The maximum idle time in seconds. - */ - public void setProcessInstanceMaxIdleTimeSeconds(long processInstanceMaxIdleTimeSeconds) { - this.processInstanceIdleTimeSeconds = processInstanceMaxIdleTimeSeconds; - } /** * Sets an expression evaluator that should be used to process transition condition expressions. @@ -98,10 +85,10 @@ public class ProcessEngineImpl implements ProcessEngine { ExpressionEvaluator transitionConditionExpressionEvaluator) { this.transitionConditionExpressionEvaluator = transitionConditionExpressionEvaluator; } - + @Override - public ProcessInstance createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException { + public String createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException { // look for respective process definition ProcessDefinition pd = processDefinitions.get(processDefinitionId); if (pd == null) { @@ -110,19 +97,32 @@ public class ProcessEngineImpl implements ProcessEngine { // create and keep process instance ProcessInstance pi = new ProcessInstance(pd, executionContext); log.info("Creating process instance from process definition '{}': {}", processDefinitionId, pi.getId()); - processInstances.put(pi.getId(), pi); - return pi; + + try { + saveProcessInstance(pi); + } catch (MOADatabaseException e) { + throw new ProcessExecutionException(e.getMessage(), e.getCause()); + } + + return pi.getId(); } @Override - public ProcessInstance createProcessInstance(String processDefinitionId) throws ProcessExecutionException { + public String createProcessInstance(String processDefinitionId) throws ProcessExecutionException { return createProcessInstance(processDefinitionId, null); } @Override - public void start(ProcessInstance pi) throws ProcessExecutionException { - MDC.put(MDC_CTX_PI_NAME, pi.getId()); + public void start(String processInstanceId) throws ProcessExecutionException { + + boolean mdcEntryAdded = false; + try { + ProcessInstance pi = loadProcessInstance(processInstanceId); + + MDC.put(MDC_CTX_PI_NAME, pi.getId()); + mdcEntryAdded = true; + if (!ProcessInstanceState.NOT_STARTED.equals(pi.getState())) { throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has already been started (current state is " + pi.getState() + ")."); } @@ -130,45 +130,49 @@ public class ProcessEngineImpl implements ProcessEngine { // execute process pi.setState(ProcessInstanceState.STARTED); execute(pi); + + saveProcessInstance(pi); + } catch (MOADatabaseException e) { + throw new ProcessExecutionException(e.getMessage(), e.getCause()); + } finally { - MDC.remove(MDC_CTX_PI_NAME); + if (mdcEntryAdded) + MDC.remove(MDC_CTX_PI_NAME); } } @Override - public void signal(ProcessInstance pi) throws ProcessExecutionException { - MDC.put(MDC_CTX_PI_NAME, pi.getId()); + public void signal(String processInstanceId) throws ProcessExecutionException { + + boolean mdcEntryAdded = false; + try { + ProcessInstance pi = loadProcessInstance(processInstanceId); + + MDC.put(MDC_CTX_PI_NAME, pi.getId()); + mdcEntryAdded = true; + if (!ProcessInstanceState.SUSPENDED.equals(pi.getState())) { throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has not been suspended (current state is " + pi.getState() + ")."); } + log.info("Waking up process instance '{}'.", pi.getId()); pi.setState(ProcessInstanceState.STARTED); execute(pi); + + saveProcessInstance(pi); + } catch (MOADatabaseException e) { + throw new ProcessExecutionException(e.getMessage(), e.getCause()); + } finally { - MDC.remove(MDC_CTX_PI_NAME); + if (mdcEntryAdded) + MDC.remove(MDC_CTX_PI_NAME); } } - @Override - public synchronized void cleanup() { - log.trace("Cleanup job started."); - Iterator> it = processInstances.entrySet().iterator(); - while (it.hasNext()) { - Entry entry = it.next(); - ProcessInstance pi = entry.getValue(); - log.trace("Checking process instance {}.", pi); - long ageMillis = new Date().getTime() - pi.getLru().getTime(); - if (ageMillis > processInstanceIdleTimeSeconds * 1000) { - log.info("Removing process instance '{}'.", pi.getId()); - processInstances.remove(entry.getKey()); - } - } - log.trace("Cleanup job completed."); - } /** - * Instantates a task implementation given by a {@link TaskInfo}. + * Instantiates a task implementation given by a {@link TaskInfo}. * @param ti The task info. * @return A Task implementation or {@code null} if the task info does not reference any task implementing classes. * @throws ProcessExecutionException Thrown in case of error (when the referenced class does not implement {@link Task} for instance). @@ -194,7 +198,7 @@ public class ProcessEngineImpl implements ProcessEngine { throw new ProcessExecutionException("Unable to instantiate class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); } } - + return task; } @@ -239,7 +243,12 @@ public class ProcessEngineImpl implements ProcessEngine { } else if (processNode instanceof EndEvent) { log.info("Finishing process instance '{}'.", pi.getId()); - processInstances.remove(pi.getId()); + + try { + piStoreDao.remove(pi.getId()); + } catch (MOADatabaseException e) { + throw new ProcessExecutionException(e.getMessage(), e.getCause()); + } pi.setState(ProcessInstanceState.ENDED); log.debug("Final process context: {}", pi.getExecutionContext().keySet()); return; @@ -282,23 +291,73 @@ public class ProcessEngineImpl implements ProcessEngine { @Override public ProcessInstance getProcessInstance(String processInstanceId) { - ProcessInstance processInstance = processInstances.get(processInstanceId); + + ProcessInstance processInstance; + try { + processInstance = loadProcessInstance(processInstanceId); + + } catch (MOADatabaseException e) { + throw new IllegalArgumentException("The process instance '" + processInstanceId + "' could not be retrieved."); + } + if (processInstance == null) { throw new IllegalArgumentException("The process instance '" + processInstanceId + "' does not/no longer exist."); } + return processInstance; } - @Override - public ProcessInstance findProcessInstanceWith(String key, Serializable value) { - Iterator it = processInstances.values().iterator(); - while (it.hasNext()) { - ProcessInstance pi = it.next(); - if (Objects.equals(pi.getExecutionContext().get(key), value)) { - return pi; - } + /** + * Persists a {@link ProcessInstance} to the database. + * @param processInstance The object to persist. + * @throws MOADatabaseException Thrown if an error occurs while accessing the database. + */ + private void saveProcessInstance(ProcessInstance processInstance) throws MOADatabaseException { + ProcessInstanceStore store = new ProcessInstanceStore(); + + ExecutionContext ctx = processInstance.getExecutionContext(); + + Map ctxData = new HashMap(); + for (String key : ctx.keySet()) { + ctxData.put(key, ctx.get(key)); + } + store.setExecutionContextData(ctxData); + + store.setNextTaskId(processInstance.getNextId()); + store.setProcessDefinitionId(processInstance.getProcessDefinition().getId()); + + store.setProcessInstanceId(processInstance.getId()); + store.setProcessState(processInstance.getState()); + + piStoreDao.save(store); + } + + /** + * Load a {@link ProcessInstance} with a certain id from the database. + * @param processInstanceId The process instance id + * @return The process instance corresponding to the id or {@code null} if no such object is found. + * @throws MOADatabaseException Thrown if an error occurs while accessing the database. + */ + private ProcessInstance loadProcessInstance(String processInstanceId) throws MOADatabaseException { + + ProcessInstanceStore piStore = piStoreDao.load(processInstanceId); + + if (piStore == null) { + return null; } - return null; + + ExecutionContext executionContext = new ExecutionContextImpl(piStore.getProcessInstanceId()); + + Map executionContextData = piStore.getExecutionContextData(); + for (String key : executionContextData.keySet()) { + executionContext.put(key, executionContextData.get(key)); + } + + ProcessInstance pi = new ProcessInstance(processDefinitions.get(piStore.getProcessDefinitionId()), executionContext); + pi.setNextId(piStore.getNextTaskId()); + pi.setState(piStore.getProcessState()); + + return pi; } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java index c94c95516..c86d0de3d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -32,7 +32,7 @@ public class ProcessInstanceStore { @Column(name = "processState", nullable = false) @Enumerated(value = EnumType.STRING) - private Enum processState; + private ProcessInstanceState processState; @Column(name = "executionContextData", nullable = false) @Lob @@ -50,7 +50,7 @@ public class ProcessInstanceStore { return nextTaskId; } - public Enum getProcessState() { + public ProcessInstanceState getProcessState() { return processState; } @@ -70,7 +70,7 @@ public class ProcessInstanceStore { this.nextTaskId = nextTaskId; } - public void setProcessState(Enum processState) { + public void setProcessState(ProcessInstanceState processState) { this.processState = processState; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java index 0aa6f80cd..999a9b82b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java @@ -42,14 +42,4 @@ public interface ProcessInstanceStoreDAO { */ void remove(String processInstanceId) throws MOADatabaseException; - /** - * Returns all {@link ProcessInstanceStore} objects stored in the database. - * The returned list may be empty, but never {@code null}. - * - * @return a list of {@link ProcessInstanceStore} (never {@code null}). - * @throws MOADatabaseException - * is thrown if a problem occurs while accessing the database. - */ - List getAllProcessInstanceStores() throws MOADatabaseException; - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index 4b7468013..e9e977d53 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -84,33 +84,4 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { } } - @SuppressWarnings("unchecked") - @Override - public List getAllProcessInstanceStores() throws MOADatabaseException { - log.debug("Retrieve a list with all ProcessInstanceStores from the database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result = Collections.emptyList(); - Transaction tx = null; - synchronized (session) { - try { - - tx = session.beginTransaction(); - // select all - result = session.createCriteria(ProcessInstanceStore.class).list(); - tx.commit(); - - } catch (Exception e) { - log.error("A problem occured while retrieving all stored ProcessInstanceStores."); - if (tx != null) { - tx.rollback(); - } - throw e; - } finally { - MOASessionDBUtils.closeSession(); - } - } - return result; - } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java index a9f5ed60a..9ee29c260 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java @@ -48,6 +48,7 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.EncryptedData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAOImpl; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.util.Random; @@ -912,19 +913,26 @@ public class AuthenticationSessionStoreage { } - private static void cleanDelete(AuthenticatedSessionStore result) { + private static void cleanDelete(AuthenticatedSessionStore result) { + + try { + AuthenticationSession session = getSession(result.getSessionid()); + ProcessInstanceStoreDAOImpl.getInstance().remove(session.getProcessInstanceId()); + + } catch (MOADatabaseException e) { + Logger.warn("Removing process with processID=" + result.getSessionid() + " FAILED.", e); + } + try { result.setSession("blank".getBytes()); MOASessionDBUtils.saveOrUpdate(result); - + } catch (MOADatabaseException e) { Logger.warn("Blank authenticated session with sessionID=" + result.getSessionid() + " FAILED.", e); - + } finally { if (!MOASessionDBUtils.delete(result)) - Logger.error("Authenticated session with sessionID=" + result.getSessionid() - + " not removed! (Error during Database communication)"); - + Logger.error("Authenticated session with sessionID=" + result.getSessionid() + " not removed! (Error during Database communication)"); } } -- cgit v1.2.3 From 2e27b939251017882b323b6478c345439d486494 Mon Sep 17 00:00:00 2001 From: Christian Wagner Date: Mon, 2 Feb 2015 12:45:40 +0100 Subject: fix process instance persistence --- .../moa/id/process/ProcessInstance.java | 26 ++++++++++------------ .../moa/id/process/dao/ProcessInstanceStore.java | 3 +++ 2 files changed, 15 insertions(+), 14 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java index ef69451eb..a6cf3b57f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java @@ -5,6 +5,8 @@ import java.util.Date; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.time.DurationFormatUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.process.model.ProcessDefinition; @@ -27,21 +29,12 @@ public class ProcessInstance implements Serializable { private ExecutionContext executionContext; private ProcessInstanceState state = ProcessInstanceState.NOT_STARTED; - /** - * Creates a new process instance, based on a given process definition.

                - * An execution context will be created internally. - * - * @param processDefinition - * The process definition. - */ - ProcessInstance(ProcessDefinition processDefinition) { - this(processDefinition, null); - } + private Logger log = LoggerFactory.getLogger(getClass()); /** * Creates a new process instance, based on a given process definition and a * given execution context. If the given execution context is {@code null} a new execution context will be created.

                - * The process instance id of the execution context will automatically be set (and overwritten if already set). + * The process instance id of the execution context will be newly generated if it is {@code null} in the execution context. * * @param processDefinition * The process definition. @@ -51,12 +44,17 @@ public class ProcessInstance implements Serializable { ProcessInstance(ProcessDefinition processDefinition, ExecutionContext executionContext) { this.processDefinition = processDefinition; nextId = processDefinition.getStartEvent().getId(); - String pdIdLocalPart = RandomStringUtils.random(RND_ID_LENGTH, 0, 0, true, true, null, - SecureRandomHolder.getInstance()); if (executionContext == null) { executionContext = new ExecutionContextImpl(); } - executionContext.setProcessInstanceId(this.processDefinition.getId() + "-" + pdIdLocalPart); + if (executionContext.getProcessInstanceId() == null) { + String pdIdLocalPart = RandomStringUtils.random(RND_ID_LENGTH, 0, 0, true, true, null, + SecureRandomHolder.getInstance()); + executionContext.setProcessInstanceId(this.processDefinition.getId() + "-" + pdIdLocalPart); + } else { + log.debug("Using process instance id from execution context."); + } + log.debug("Creating process instance with id '{}'.", executionContext.getProcessInstanceId()); this.executionContext = executionContext; touch(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java index c86d0de3d..010f8d984 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -4,9 +4,11 @@ import java.io.Serializable; import java.util.Map; import javax.persistence.Column; +import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; +import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; @@ -36,6 +38,7 @@ public class ProcessInstanceStore { @Column(name = "executionContextData", nullable = false) @Lob + @ElementCollection(fetch=FetchType.EAGER) private Map executionContextData; public String getProcessInstanceId() { -- cgit v1.2.3 From 036c31a1dcff04784946159c2612e48bf2ec9e0e Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Mon, 2 Feb 2015 14:03:17 +0100 Subject: Fix persistence. --- .../moa/id/process/dao/ProcessInstanceStore.java | 3 ++- .../id/process/dao/ProcessInstanceStoreDAOImpl.java | 20 +++++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java index 010f8d984..625199cd2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.process.dao; import java.io.Serializable; +import java.util.HashMap; import java.util.Map; import javax.persistence.Column; @@ -39,7 +40,7 @@ public class ProcessInstanceStore { @Column(name = "executionContextData", nullable = false) @Lob @ElementCollection(fetch=FetchType.EAGER) - private Map executionContextData; + private Map executionContextData = new HashMap<>(); public String getProcessInstanceId() { return processInstanceId; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index e9e977d53..0a50afc6c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -67,6 +67,11 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { MOASessionDBUtils.closeSession(); } } + if (result != null) { + log.debug("Found process instance store for instance '{}'.", processInstanceId); + } else { + log.debug("Unable to find process instance store for instance '{}'.", processInstanceId); + } return result; } @@ -74,14 +79,15 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { public void remove(String processInstanceId) throws MOADatabaseException { log.debug("Delete the ProcessInstanceStore for id='{}' from the database.", processInstanceId); - ProcessInstanceStore toBeDeleted = load(processInstanceId); - boolean deleted = MOASessionDBUtils.delete(toBeDeleted); - if (!deleted) { - log.warn("Could not delete the ProcessInstanceStore with process instance id '{}'", processInstanceId); - throw new MOADatabaseException("Could not delete the ProcessInstanceStore with process instance id '" - + processInstanceId + "'."); - } + if (toBeDeleted != null) { + if (!MOASessionDBUtils.delete(toBeDeleted)) { + log.warn("Could not delete the ProcessInstanceStore with process instance id '{}'", processInstanceId); + throw new MOADatabaseException("Could not delete the ProcessInstanceStore with process instance id '" + + processInstanceId + "'."); + } + } else + log.trace("ProcessInstanceStore for id='{}' was not found and could therefore not be deleted.", processInstanceId); } } -- cgit v1.2.3 From 9a94ecf85e323321e23df8a93ad206c4a699d3fd Mon Sep 17 00:00:00 2001 From: Christian Wagner Date: Tue, 3 Feb 2015 09:17:14 +0100 Subject: serialize ExecutionContext data in a single database field --- .../moa/id/process/dao/ProcessInstanceStore.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java index 625199cd2..c6bf86823 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -1,19 +1,18 @@ package at.gv.egovernment.moa.id.process.dao; import java.io.Serializable; -import java.util.HashMap; import java.util.Map; import javax.persistence.Column; -import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; -import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; +import org.hibernate.internal.util.SerializationHelper; + import at.gv.egovernment.moa.id.process.ProcessInstanceState; @Entity @@ -39,8 +38,7 @@ public class ProcessInstanceStore { @Column(name = "executionContextData", nullable = false) @Lob - @ElementCollection(fetch=FetchType.EAGER) - private Map executionContextData = new HashMap<>(); + private byte[] executionContextData; public String getProcessInstanceId() { return processInstanceId; @@ -58,8 +56,9 @@ public class ProcessInstanceStore { return processState; } + @SuppressWarnings("unchecked") public Map getExecutionContextData() { - return executionContextData; + return (Map) SerializationHelper.deserialize(executionContextData); } public void setProcessInstanceId(String processInstanceId) { @@ -79,7 +78,7 @@ public class ProcessInstanceStore { } public void setExecutionContextData(Map executionContextData) { - this.executionContextData = executionContextData; + this.executionContextData = SerializationHelper.serialize((Serializable) executionContextData); } } -- cgit v1.2.3 From 4b6fd327b29ff84f61914f33b6361fa31441c92e Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Wed, 4 Feb 2015 11:31:43 +0100 Subject: Create separate module STORK (MOAID-67) - Add new maven module moa-id-modules and sub module moa-id-module-stork. - Move stork relates processes and task to module moa-id-module-stork. - Move module registration to modules package. --- .../id/auth/modules/AbstractAuthServletTask.java | 378 ++++++++++++++ .../moa/id/auth/modules/AuthModule.java | 41 ++ .../modules/internal/DefaultAuthModuleImpl.java | 2 +- .../internal/tasks/AbstractAuthServletTask.java | 378 -------------- .../internal/tasks/CertificateReadRequestTask.java | 4 +- .../internal/tasks/CreateIdentityLinkFormTask.java | 1 + .../modules/internal/tasks/GetForeignIDTask.java | 1 + .../internal/tasks/GetMISSessionIDTask.java | 1 + .../tasks/PrepareAuthBlockSignatureTask.java | 1 + .../tasks/VerifyAuthenticationBlockTask.java | 1 + .../internal/tasks/VerifyCertificateTask.java | 1 + .../internal/tasks/VerifyIdentityLinkTask.java | 1 + .../modules/registration/ModuleRegistration.java | 149 ++++++ .../id/auth/modules/stork/STORKAuthModuleImpl.java | 39 -- .../stork/STORKWebApplicationInitializer.java | 37 -- .../AbstractPepsConnectorWithLocalSigningTask.java | 223 -------- .../tasks/CreateStorkAuthRequestFormTask.java | 112 ---- .../PepsConnectorHandleLocalSignResponseTask.java | 216 -------- ...onnectorHandleResponseWithoutSignatureTask.java | 439 ---------------- .../modules/stork/tasks/PepsConnectorTask.java | 566 --------------------- .../servlet/GenerateIFrameTemplateServlet.java | 2 +- .../moa/id/moduls/AuthenticationManager.java | 2 +- .../id/moduls/moduleregistration/AuthModule.java | 41 -- .../moduleregistration/ModuleRegistration.java | 149 ------ .../egovernment/moa/id/process/ProcessEngine.java | 3 +- .../moa/id/process/ProcessEngineImpl.java | 6 +- 26 files changed, 586 insertions(+), 2208 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/AbstractAuthServletTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKWebApplicationInitializer.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java new file mode 100644 index 000000000..3b20e85d7 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java @@ -0,0 +1,378 @@ +package at.gv.egovernment.moa.id.auth.modules; + +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.FileUploadException; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.lang3.ArrayUtils; + +import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; +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.servlet.AuthServlet; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; +import at.gv.egovernment.moa.id.process.springweb.AbstractSpringWebSupportedTask; +import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; +import at.gv.egovernment.moa.id.storage.IExceptionStore; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing + * etc.).

                The code has been taken from {@link AuthServlet}. + */ +public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask { + + protected static final String ERROR_CODE_PARAM = "errorid"; + + protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp) { + + if (null != errorMessage) { + Logger.error(errorMessage); + req.setAttribute("ErrorMessage", errorMessage); + } + + if (null != exceptionThrown) { + if (null == errorMessage) + errorMessage = exceptionThrown.getMessage(); + Logger.error(errorMessage, exceptionThrown); + req.setAttribute("ExceptionThrown", exceptionThrown); + } + + if (Logger.isDebugEnabled()) { + req.setAttribute("LogLevel", "debug"); + } + + + StatisticLogger logger = StatisticLogger.getInstance(); + logger.logErrorOperation(exceptionThrown); + + + // forward this to errorpage-auth.jsp where the HTML error page is + // generated + ServletContext context = req.getServletContext(); + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); + + dispatcher.forward(req, resp); + } catch (ServletException e) { + Logger.error(e); + } catch (IOException e) { + Logger.error(e); + } + } + + /** + * Handles an error.
                > + *
                  + *
                • Logs the error
                • + *
                • Places error message and exception thrown into the request as request + * attributes (to be used by "/errorpage-auth.jsp")
                • + *
                • Sets HTTP status 500 (internal server error)
                • + *
                + * + * @param errorMessage + * error message + * @param exceptionThrown + * exception thrown + * @param req + * servlet request + * @param resp + * servlet response + */ + protected void handleError(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { + + if (null != errorMessage) { + Logger.error(errorMessage); + req.setAttribute("ErrorMessage", errorMessage); + } + + if (null != exceptionThrown) { + if (null == errorMessage) + errorMessage = exceptionThrown.getMessage(); + Logger.error(errorMessage, exceptionThrown); + req.setAttribute("ExceptionThrown", exceptionThrown); + } + + if (Logger.isDebugEnabled()) { + req.setAttribute("LogLevel", "debug"); + } + + if (!(exceptionThrown instanceof MOAIDException)) { + Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown); + + } + + IExceptionStore store = DBExceptionStoreImpl.getStore(); + String id = store.storeException(exceptionThrown); + + if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { + + String redirectURL = null; + + redirectURL = ServletUtils.getBaseUrl(req); + redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id + + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + return; + + } else { + + //Exception can not be stored in database + handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); + } + } + + /** + * Handles a WrongParametersException. + * + * @param req + * servlet request + * @param resp + * servlet response + */ + protected void handleWrongParameters(WrongParametersException ex, + HttpServletRequest req, HttpServletResponse resp) { + Logger.error(ex.toString()); + req.setAttribute("WrongParameters", ex.getMessage()); + + // forward this to errorpage-auth.jsp where the HTML error page is + // generated + ServletContext context = req.getServletContext(); + RequestDispatcher dispatcher = context + .getRequestDispatcher("/errorpage-auth.jsp"); + try { + setNoCachingHeaders(resp); + dispatcher.forward(req, resp); + } catch (ServletException e) { + Logger.error(e); + } catch (IOException e) { + Logger.error(e); + } + } + + /** + * Logs all servlet parameters for debugging purposes. + */ + protected void logParameters(HttpServletRequest req) { + for (Enumeration params = req.getParameterNames(); params + .hasMoreElements();) { + String parname = (String) params.nextElement(); + Logger.debug("Parameter " + parname + req.getParameter(parname)); + } + } + + /** + * Parses the request input stream for parameters, assuming parameters are + * encoded UTF-8 (no standard exists how browsers should encode them). + * + * @param req + * servlet request + * + * @return mapping parameter name -> value + * + * @throws IOException + * if parsing request parameters fails. + * + * @throws FileUploadException + * if parsing request parameters fails. + */ + protected Map getParameters(HttpServletRequest req) throws IOException, + FileUploadException { + + Map parameters = new HashMap(); + + if (ServletFileUpload.isMultipartContent(req)) { + // request is encoded as mulitpart/form-data + FileItemFactory factory = new DiskFileItemFactory(); + ServletFileUpload upload = null; + upload = new ServletFileUpload(factory); + List items = null; + items = upload.parseRequest(req); + for (int i = 0; i < items.size(); i++) { + FileItem item = (FileItem) items.get(i); + if (item.isFormField()) { + // Process only form fields - no file upload items + String logString = item.getString("UTF-8"); + + // TODO use RegExp + String startS = ""; + String endS = "urn:publicid:gv.at:baseid"; + String logWithMaskedBaseid = logString; + int start = logString.indexOf(startS); + if (start > -1) { + int end = logString.indexOf(endS); + if (end > -1) { + logWithMaskedBaseid = logString.substring(0, start); + logWithMaskedBaseid += startS; + logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; + logWithMaskedBaseid += logString.substring(end, + logString.length()); + } + } + parameters + .put(item.getFieldName(), item.getString("UTF-8")); + Logger.debug("Processed multipart/form-data request parameter: \nName: " + + item.getFieldName() + + "\nValue: " + + logWithMaskedBaseid); + } + } + } + + else { + // request is encoded as application/x-www-urlencoded + // [tknall]: we must not consume request body input stream once servlet-api request parameters have been accessed + + /* + InputStream in = req.getInputStream(); + + String paramName; + String paramValueURLEncoded; + do { + paramName = new String(readBytesUpTo(in, '=')); + if (paramName.length() > 0) { + paramValueURLEncoded = readBytesUpTo(in, '&'); + String paramValue = URLDecoder.decode(paramValueURLEncoded, + "UTF-8"); + parameters.put(paramName, paramValue); + } + } while (paramName.length() > 0); + in.close(); + */ + + Iterator> requestParamIt = req.getParameterMap().entrySet().iterator(); + while (requestParamIt.hasNext()) { + Entry entry = requestParamIt.next(); + String key = entry.getKey(); + String[] values = entry.getValue(); + // take the last value from the value array since the legacy code above also does it this way + parameters.put(key, ArrayUtils.isEmpty(values) ? null : values[values.length-1]); + } + + } + + return parameters; + } + + /** + * Reads bytes up to a delimiter, consuming the delimiter. + * + * @param in + * input stream + * @param delimiter + * delimiter character + * @return String constructed from the read bytes + * @throws IOException + */ + protected String readBytesUpTo(InputStream in, char delimiter) + throws IOException { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + boolean done = false; + int b; + while (!done && (b = in.read()) >= 0) { + if (b == delimiter) + done = true; + else + bout.write(b); + } + return bout.toString(); + } + + /** + * Sets response headers that prevent caching (code taken from {@link AuthServlet}). + * + * @param resp + * The HttpServletResponse. + */ + public void setNoCachingHeaders(HttpServletResponse resp) { + resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); + resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); + resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); + resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); + } + + /** + * Adds a parameter to a URL. + * + * @param url + * the URL + * @param paramname + * parameter name + * @param paramvalue + * parameter value + * @return the URL with parameter added + */ + protected static String addURLParameter(String url, String paramname, + String paramvalue) { + String param = paramname + "=" + paramvalue; + if (url.indexOf("?") < 0) + return url + "?" + param; + else + return url + "&" + param; + } + + /** + * Checks if HTTP requests are allowed + * + * @param authURL + * requestURL + * @throws AuthenticationException + * if HTTP requests are not allowed + * @throws ConfigurationException + */ + protected void checkIfHTTPisAllowed(String authURL) + throws AuthenticationException, ConfigurationException { + // check if HTTP Connection may be allowed (through + // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) + + //Removed from MOA-ID 2.0 config +// String boolStr = AuthConfigurationProvider +// .getInstance() +// .getGenericConfigurationParameter( +// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); + if ((!authURL.startsWith("https:")) + //&& (false == BoolUtils.valueOf(boolStr)) + ) + throw new AuthenticationException("auth.07", new Object[] { authURL + + "*" }); + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java new file mode 100644 index 000000000..a31f3ceb0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java @@ -0,0 +1,41 @@ +package at.gv.egovernment.moa.id.auth.modules; + +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.model.ProcessDefinition; + +/** + * Provides metadata of a certain module. Uses for module discovery and process selection. + */ +public interface AuthModule { + + /** + * Returns the priority of the module. The priority defines the order of the respective module within the chain of + * discovered modules. Higher priorized modules are asked before lower priorized modules for a process that they can + * handle. + *

                + * Internal default modules are priorized neutral ({@code 0}. Use a higher priority ({@code 1...Integer.MAX_VALUE}) + * in order to have your module(s) priorized or a lower priority ({@code Integer.MIN_VALUE...-1}) in order to put + * your modules behind default modules. + * + * @return the priority of the module. + */ + int getPriority(); + + /** + * Checks if the module has a process, which is able to perform an authentication with the given + * {@link ExecutionContext}. + * + * @param context + * an ExecutionContext for a process. + * @return the process-ID of a process which is able to work with the given ExecutionContext, or {@code null}. + */ + String selectProcess(ExecutionContext context); + + /** + * Returns the an Array of {@link ProcessDefinition}s of the processes included in this module. + * + * @return an array of resource uris of the processes included in this module. + */ + String[] getProcessDefinitions(); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java index a3b105cfd..8ae4a9999 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java @@ -2,7 +2,7 @@ package at.gv.egovernment.moa.id.auth.modules.internal; import org.apache.commons.lang3.StringUtils; -import at.gv.egovernment.moa.id.moduls.moduleregistration.AuthModule; +import at.gv.egovernment.moa.id.auth.modules.AuthModule; import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/AbstractAuthServletTask.java deleted file mode 100644 index 088ec59d4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/AbstractAuthServletTask.java +++ /dev/null @@ -1,378 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.internal.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileItemFactory; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.lang3.ArrayUtils; - -import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; -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.servlet.AuthServlet; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; -import at.gv.egovernment.moa.id.process.springweb.AbstractSpringWebSupportedTask; -import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -import at.gv.egovernment.moa.id.storage.IExceptionStore; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing - * etc.).

                The code has been taken from {@link AuthServlet}. - */ -public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask { - - protected static final String ERROR_CODE_PARAM = "errorid"; - - protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp) { - - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); - } - - - StatisticLogger logger = StatisticLogger.getInstance(); - logger.logErrorOperation(exceptionThrown); - - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = req.getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - - resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); - resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); - resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); - - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Handles an error.
                > - *
                  - *
                • Logs the error
                • - *
                • Places error message and exception thrown into the request as request - * attributes (to be used by "/errorpage-auth.jsp")
                • - *
                • Sets HTTP status 500 (internal server error)
                • - *
                - * - * @param errorMessage - * error message - * @param exceptionThrown - * exception thrown - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleError(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { - - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); - } - - if (!(exceptionThrown instanceof MOAIDException)) { - Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown); - - } - - IExceptionStore store = DBExceptionStoreImpl.getStore(); - String id = store.storeException(exceptionThrown); - - if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { - - String redirectURL = null; - - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id - + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - return; - - } else { - - //Exception can not be stored in database - handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); - } - } - - /** - * Handles a WrongParametersException. - * - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleWrongParameters(WrongParametersException ex, - HttpServletRequest req, HttpServletResponse resp) { - Logger.error(ex.toString()); - req.setAttribute("WrongParameters", ex.getMessage()); - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = req.getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - setNoCachingHeaders(resp); - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Logs all servlet parameters for debugging purposes. - */ - protected void logParameters(HttpServletRequest req) { - for (Enumeration params = req.getParameterNames(); params - .hasMoreElements();) { - String parname = (String) params.nextElement(); - Logger.debug("Parameter " + parname + req.getParameter(parname)); - } - } - - /** - * Parses the request input stream for parameters, assuming parameters are - * encoded UTF-8 (no standard exists how browsers should encode them). - * - * @param req - * servlet request - * - * @return mapping parameter name -> value - * - * @throws IOException - * if parsing request parameters fails. - * - * @throws FileUploadException - * if parsing request parameters fails. - */ - protected Map getParameters(HttpServletRequest req) throws IOException, - FileUploadException { - - Map parameters = new HashMap(); - - if (ServletFileUpload.isMultipartContent(req)) { - // request is encoded as mulitpart/form-data - FileItemFactory factory = new DiskFileItemFactory(); - ServletFileUpload upload = null; - upload = new ServletFileUpload(factory); - List items = null; - items = upload.parseRequest(req); - for (int i = 0; i < items.size(); i++) { - FileItem item = (FileItem) items.get(i); - if (item.isFormField()) { - // Process only form fields - no file upload items - String logString = item.getString("UTF-8"); - - // TODO use RegExp - String startS = ""; - String endS = "urn:publicid:gv.at:baseid"; - String logWithMaskedBaseid = logString; - int start = logString.indexOf(startS); - if (start > -1) { - int end = logString.indexOf(endS); - if (end > -1) { - logWithMaskedBaseid = logString.substring(0, start); - logWithMaskedBaseid += startS; - logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; - logWithMaskedBaseid += logString.substring(end, - logString.length()); - } - } - parameters - .put(item.getFieldName(), item.getString("UTF-8")); - Logger.debug("Processed multipart/form-data request parameter: \nName: " - + item.getFieldName() - + "\nValue: " - + logWithMaskedBaseid); - } - } - } - - else { - // request is encoded as application/x-www-urlencoded - // [tknall]: we must not consume request body input stream once servlet-api request parameters have been accessed - - /* - InputStream in = req.getInputStream(); - - String paramName; - String paramValueURLEncoded; - do { - paramName = new String(readBytesUpTo(in, '=')); - if (paramName.length() > 0) { - paramValueURLEncoded = readBytesUpTo(in, '&'); - String paramValue = URLDecoder.decode(paramValueURLEncoded, - "UTF-8"); - parameters.put(paramName, paramValue); - } - } while (paramName.length() > 0); - in.close(); - */ - - Iterator> requestParamIt = req.getParameterMap().entrySet().iterator(); - while (requestParamIt.hasNext()) { - Entry entry = requestParamIt.next(); - String key = entry.getKey(); - String[] values = entry.getValue(); - // take the last value from the value array since the legacy code above also does it this way - parameters.put(key, ArrayUtils.isEmpty(values) ? null : values[values.length-1]); - } - - } - - return parameters; - } - - /** - * Reads bytes up to a delimiter, consuming the delimiter. - * - * @param in - * input stream - * @param delimiter - * delimiter character - * @return String constructed from the read bytes - * @throws IOException - */ - protected String readBytesUpTo(InputStream in, char delimiter) - throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - boolean done = false; - int b; - while (!done && (b = in.read()) >= 0) { - if (b == delimiter) - done = true; - else - bout.write(b); - } - return bout.toString(); - } - - /** - * Sets response headers that prevent caching (code taken from {@link AuthServlet}). - * - * @param resp - * The HttpServletResponse. - */ - public void setNoCachingHeaders(HttpServletResponse resp) { - resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); - resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); - resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); - } - - /** - * Adds a parameter to a URL. - * - * @param url - * the URL - * @param paramname - * parameter name - * @param paramvalue - * parameter value - * @return the URL with parameter added - */ - protected static String addURLParameter(String url, String paramname, - String paramvalue) { - String param = paramname + "=" + paramvalue; - if (url.indexOf("?") < 0) - return url + "?" + param; - else - return url + "&" + param; - } - - /** - * Checks if HTTP requests are allowed - * - * @param authURL - * requestURL - * @throws AuthenticationException - * if HTTP requests are not allowed - * @throws ConfigurationException - */ - protected void checkIfHTTPisAllowed(String authURL) - throws AuthenticationException, ConfigurationException { - // check if HTTP Connection may be allowed (through - // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) - - //Removed from MOA-ID 2.0 config -// String boolStr = AuthConfigurationProvider -// .getInstance() -// .getGenericConfigurationParameter( -// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); - if ((!authURL.startsWith("https:")) - //&& (false == BoolUtils.valueOf(boolStr)) - ) - throw new AuthenticationException("auth.07", new Object[] { authURL - + "*" }); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java index 4bcf717c5..bc73a9f2f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java @@ -9,13 +9,13 @@ import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.BooleanUtils; import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; 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.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; @@ -37,7 +37,7 @@ import at.gv.egovernment.moa.logging.Logger; *
              * Result: *
                - *
              • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code {/VerifyCertificate}
              • + *
              • Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code /VerifyCertificate}
              • *
              * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java index 08030e623..4cd1ea94e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java @@ -14,6 +14,7 @@ import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; 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.servlet.GenerateIFrameTemplateServlet; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java index 4e535b83d..4771628a3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java @@ -23,6 +23,7 @@ import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; import at.gv.egovernment.moa.id.client.SZRGWClientException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java index 6714dfb53..f08f96782 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java @@ -20,6 +20,7 @@ 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.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java index d7b35236e..36d6ea555 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java @@ -11,6 +11,7 @@ import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; 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.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java index 060bdf72c..1e1a4df89 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java @@ -24,6 +24,7 @@ import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; 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.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConnectionParameter; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java index af0c4c897..32ea7fe3a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java @@ -18,6 +18,7 @@ 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.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java index 75fdd19aa..bf10b3681 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java @@ -15,6 +15,7 @@ import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java new file mode 100644 index 000000000..c2a34ff21 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java @@ -0,0 +1,149 @@ +package at.gv.egovernment.moa.id.auth.modules.registration; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.ServiceLoader; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.core.io.Resource; + +import at.gv.egovernment.moa.id.auth.modules.AuthModule; +import at.gv.egovernment.moa.id.process.ProcessDefinitionParserException; +import at.gv.egovernment.moa.id.process.ProcessEngine; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; + +/** + * This class handles registering modules. The modules are detected either with + * the ServiceLoader mechanism or via Spring. All detected modules are ranked + * according to their priority. + */ +public class ModuleRegistration { + + private static ModuleRegistration instance = new ModuleRegistration(); + + private List priorizedModules = new ArrayList<>(); + + @Autowired + private ApplicationContext ctx; + + @Autowired + private ProcessEngine processEngine; + + private Logger log = LoggerFactory.getLogger(getClass()); + + public static ModuleRegistration getInstance() { + return instance; + } + + private ModuleRegistration() { + } + + @PostConstruct + private void init() { + // load modules via the ServiceLoader + initServiceLoaderModules(); + + // load modules via Spring + initSpringModules(); + + // order modules according to their priority + sortModules(); + } + + /** + * Discovers modules which use the ServiceLoader mechanism. + */ + private void initServiceLoaderModules() { + log.info("Looking for auth modules."); + ServiceLoader loader = ServiceLoader.load(AuthModule.class); + Iterator modules = loader.iterator(); + while (modules.hasNext()) { + AuthModule module = modules.next(); + log.info("Detected module {}", module.getClass().getName()); + registerModuleProcessDefinitions(module); + priorizedModules.add(module); + } + } + + /** + * Discovers modules which use Spring. + */ + private void initSpringModules() { + log.debug("Discovering Spring modules."); + Map modules = ctx.getBeansOfType(AuthModule.class); + for (AuthModule module : modules.values()) { + registerModuleProcessDefinitions(module); + priorizedModules.add(module); + } + } + + /** + * Registers the resource uris for the module. + * + * @param module + * the module. + */ + private void registerModuleProcessDefinitions(AuthModule module) { + for (String uri : module.getProcessDefinitions()) { + Resource resource = ctx.getResource(uri); + if (resource.isReadable()) { + log.info("Registering process definition '{}'.", uri); + try (InputStream processDefinitionInputStream = resource.getInputStream()) { + processEngine.registerProcessDefinition(processDefinitionInputStream); + } catch (IOException e) { + log.error("Process definition '{}' could NOT be read.", uri, e); + } catch (ProcessDefinitionParserException e) { + log.error("Error while parsing process definition '{}'", uri, e); + } + } else { + log.error("Process definition '{}' cannot be read.", uri); + } + } + } + + /** + * Order the modules in descending order according to their priority. + */ + private void sortModules() { + Collections.sort(priorizedModules, new Comparator() { + @Override + public int compare(AuthModule thisAuthModule, AuthModule otherAuthModule) { + int thisOrder = thisAuthModule.getPriority(); + int otherOrder = otherAuthModule.getPriority(); + return (thisOrder < otherOrder ? -1 : (thisOrder == otherOrder ? 0 : 1)); + } + }); + } + + /** + * Returns the process id of the first process, in the highest ranked + * module, which is able to work with the given execution context. + * + * @param context + * the {@link ExecutionContext}. + * @return the process id or {@code null} + */ + public String selectProcess(ExecutionContext context) { + for (AuthModule module : priorizedModules) { + String id = module.selectProcess(context); + if (StringUtils.isNotEmpty(id)) { + log.debug("Process with id '{}' selected, for context '{}'.", id, context); + return id; + } + } + log.info("No process is able to handle context '{}'.", context); + return null; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java deleted file mode 100644 index 55a7907ed..000000000 --- a/id/server/idserverlib/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.moduls.moduleregistration.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKWebApplicationInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKWebApplicationInitializer.java deleted file mode 100644 index 7478a57c3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKWebApplicationInitializer.java +++ /dev/null @@ -1,37 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.web.WebApplicationInitializer; - -import at.gv.egovernment.moa.id.auth.servlet.ProcessEngineSignalServlet; - -/** - * Spring automatically discovers {@link WebApplicationInitializer} implementations at startup.
              - * This STORK webapp initializer adds the required servlet mappings: - *
                - *
              • {@code /PEPSConnector}
              • - *
              • {@code /PEPSConnectorWithLocalSigning}
              • - *
              - * for the {@linkplain ProcessEngineSignalServlet process engine servlet} (named {@code ProcessEngineSignal}) that wakes - * up a process in order to execute asynchronous tasks. Therefore the servlet mappings mentioned above do not need to be - * declared in {@code web.xml}. - * - * @author tknall - * @see ProcessEngineSignalServlet - */ -public class STORKWebApplicationInitializer implements WebApplicationInitializer { - - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - ServletRegistration servletRegistration = servletContext.getServletRegistration("ProcessEngineSignal"); - if (servletRegistration == null) { - throw new IllegalStateException("Servlet 'ProcessEngineSignal' expected to be registered."); - } - servletRegistration.addMapping("/PEPSConnectorWithLocalSigning"); - servletRegistration.addMapping("/PEPSConnector"); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java deleted file mode 100644 index 202e405ef..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java +++ /dev/null @@ -1,223 +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.internal.tasks.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.AuthConfigurationProvider; -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 { - - 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 = AuthConfigurationProvider.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) 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) 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java deleted file mode 100644 index ec7ee04a6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java +++ /dev/null @@ -1,112 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork.tasks; - -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; -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.internal.tasks.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.stork.CPEPS; -import at.gv.egovernment.moa.id.config.stork.STORKConfig; -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.logging.Logger; - -/** - * 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.

              - * In detail: - *

                - *
              • Validates the stork configuration in order to make sure the selected country is supported.
              • - *
              • Puts a flag ({@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}) into the ExecutionContext reflecting the capability of the C-PEPS to create xml signatures.
              • - *
              • Invokes {@link AuthenticationServer#startSTORKAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationSession)} which
              • - *
                  - *
                • Creates and signs a SAML2 stork authentication request.
                • - *
                • Creates a signature request for auth block signature (either to be performed by the C-PEPS or locally).
                • - *
                • Using the velocity template engine in order to create a form with the embedded stork request.
                • - *
                • Writes the form to the response output stream.
                • - *
                - *
              - * Expects: - *
                - *
              • HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}
              • - *
              • Property {@code ccc} set within the moa session.
              • - *
              - * Result: - *
                - *
              • Form containing a SAML2 Stork authentication request and an action url pointing to the selected C-PEPS.
              • - *
              • 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.
              • - *
              • In case of a C-PEPS not supporting xml signature: moasession with set signedDoc property (containing the signature request for local signing).
              • - *
              • ExecutionContext contains the boolean flag {@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}. - *
              - * Code taken from {@link StartAuthenticationBuilder#build(AuthenticationSession, HttpServletRequest, HttpServletResponse)}.
              - * 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 Exception { - - String pendingRequestID = null; - String sessionID = null; - try { - setNoCachingHeaders(resp); - - sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("CreateStorkAuthRequestFormTask", PARAM_SESSIONID, "auth.12"); - } - AuthenticationSession moasession = AuthenticationServer.getSession(sessionID); - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - if (StringUtils.isEmpty(moasession.getCcc())) { - // illegal state; task should not have been executed without a selected country - throw new AuthenticationException("stork.22", new Object[] { sessionID }); - } - STORKConfig storkConfig = AuthConfigurationProvider.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(moasession.getCcc()); - Logger.debug("Found C-PEPS configuration for citizen of country: " + moasession.getCcc()); - executionContext.put(PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED, cpeps.isXMLSignatureSupported()); - - Logger.info("Starting STORK authentication for a citizen of country: " + moasession.getCcc()); - AuthenticationServer.startSTORKAuthentication(req, resp, moasession); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("CreateStorkAuthRequestFormTask has an interal Error.", e); - throw new MOAIDException("Internal error.", new Object[] { sessionID }, e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java deleted file mode 100644 index 077bb2dee..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java +++ /dev/null @@ -1,216 +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.auth.AuthenticationServer; -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.stork.STORKException; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -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 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. - *

              - * In detail: - *

                - *
              • Changes moa session id.
              • - *
              • Decodes and validates the sign response, extracting the citizen's signature.
              • - *
              • Verifies the citizen's signature.
              • - *
              • Create {@code signedDoc} attribute.
              • - *
              • Retrieve identity link from SZR gateway using the citizen's signature.
              • - *
              • 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).
              • - *
              • The moa session is updated with authentication information.
              • - *
              • Change moa session id.
              • - *
              • Redirects back to {@code /dispatcher} in order to finalize the authentication.
              • - *
              - * Expects: - *
                - *
              • HttpServletRequest parameter {@code moaSessionID}
              • - *
              • HttpServletRequest parameter {@code signresponse}
              • - *
              - * Result: - *
                - *
              • Updated moa id session (signed auth block, signer certificate etc.)
              • - *
              • Redirect to {@code /dispatcher}.
              • - *
              • {@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.
              • - *
              - * Possible branches: - *
                - *
              • In case the szr gateway throws exception due to missing gender information: - *
                  - *
                • Returns a form for gender selection with action url back to this servlet/task.
                • - *
                - *
              • - *
              - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.
              - * - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - */ -public class PepsConnectorHandleLocalSignResponseTask extends AbstractPepsConnectorWithLocalSigningTask { - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws Exception { - 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 IOException("should not occur"); - } - return; - } - - private void handleSignResponse(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) { - 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 = AuthenticationServer.getSession(moaSessionID); - // change MOASessionID - moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); - Logger.info("pendingRequestID:" + pendingRequestID); - String signResponseString = new String(Base64.decodeBase64(signResponse), "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 values = new ArrayList(); - 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? - 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) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java deleted file mode 100644 index 3338804b4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java +++ /dev/null @@ -1,439 +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.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.AuthenticationServer; -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.servlet.PEPSConnectorWithLocalSigningServlet; -import at.gv.egovernment.moa.id.auth.stork.STORKException; -import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -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.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. - *

              - * In detail: - *

                - *
              • Decodes and validates SAML response from C-PEPS.
              • - *
              • Retrieves the moa session using the session id provided by HttpServletRequest parameter {@code RelayState} or by {@code inResponseTo} attribute of the saml response.
              • - *
              • Store saml response in moa session.
              • - *
              • Change moa session id.
              • - *
              • Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.
              • - *
              - * Expects: - *
                - *
              • HttpServletRequest parameter {@code moaSessionID} to be {@code null}
              • - *
              • HttpServletRequest parameter {@code signresponse} to be {@code null}
              • - *
              • HttpServletRequest parameter {@code SAMLResponse}
              • - *
              • Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute within the saml response, both reflecting the moa session id.
              • - *
              - * Result: - *
                - *
              • Updated moa session (with saml response).
              • - *
              • Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.
              • - *
              - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.
              - * - * @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 Exception { - 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 IOException("should not occur"); - } - return; - } - - private void handleSAMLResponse(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) { - 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.validateSTORKAuthnResponse(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); - - // load MOASession from database - AuthenticationSession moaSession = AuthenticationServer.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); - - // //////////// incorporate gender from parameters if not in stork response - - IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); - - // 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 tmp = new ArrayList(); - tmp.add(gendervalue); - gender.setValue(tmp); - - authnResponse.getPersonalAttributeList().add(gender); - } - } - } - - - - // //////////////////////////////////////////////////////////////////////// - - Logger.debug("Starting extraction of signedDoc attribute"); - // extract signed doc element and citizen signature - String citizenSignature = null; - try { - PersonalAttribute signedDoc = authnResponse.getPersonalAttributeList().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(authnResponse.getPersonalAttributeList()); - - 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 = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); - String acsURL = issuerValue - + PEPSConnectorWithLocalSigningServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; - - String url = acsURL + "?moaSessionID=" + newMOASessionID; - // redirect to OASIS module and sign there - - boolean found = false; - try { - List aps = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()).getStorkAPs(); - Logger.info("Found AttributeProviderPlugins:" + aps.size()); - for (AttributeProviderPlugin 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, authnResponse.getPersonalAttributeList(), 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) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - - } - - 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", Base64.encodeBase64String(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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java deleted file mode 100644 index 3fb4fb0a9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java +++ /dev/null @@ -1,566 +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.util.ArrayList; -import java.util.Arrays; -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 at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.internal.tasks.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.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -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.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.StringUtils; -import at.gv.util.xsd.xmldsig.SignatureType; -import at.gv.util.xsd.xmldsig.X509DataType; -import eu.stork.documentservice.DocumentService; -import eu.stork.documentservice.data.DatabaseConnectorMySQLImpl; -import eu.stork.oasisdss.api.ApiUtils; -import eu.stork.oasisdss.api.LightweightSourceResolver; -import eu.stork.oasisdss.api.exceptions.ApiUtilsException; -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. - *

              - * In detail: - *

                - *
              • Decodes and validates the SAML response from the C-PEPS.
              • - *
              • Change moa session id.
              • - *
              • Extracts the subject's gender from request parameter {@code gender} if not available from the saml response.
              • - *
              • Extracts the {@code signedDoc} attribute from the response, get signed doc payload using stork attribute query request.
              • - *
              • Request SZR gateway for verification of the citizen's signature and for creating of an identity link.
              • - *
              • 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).
              • - *
              • The moa session is updated with authentication information.
              • - *
              • Change moa session id.
              • - *
              • Redirects back to {@code /dispatcher} in order to finalize the authentication.
              • - *
              - * Expects: - *
                - *
              • HttpServletRequest parameter {@code SAMLResponse}
              • - *
              • Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute from the SAML response (both depicting the moa session id)
              • - *
              • HttpServletRequest parameter {@code gender} in case the request comes from the gender selection form
              • - *
              • {@code signedDoc} attribute within the SAML response.
              • - *
              - * Result: - *
                - *
              • Updated moa id session (identity link, stork attributes...)
              • - *
              • {@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.
              • - *
              • Redirect to {@code /dispatcher}.
              • - *
              - * Possible branches: - *
                - *
              • In case the szr gateway throws exception due to missing gender information: - *
                  - *
                • Returns a form for gender selection with action url back to this servlet/task.
                • - *
                - *
              • - *
              - * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet}.
              - * - * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) - */ -public class PepsConnectorTask extends AbstractAuthServletTask { - - private String dtlUrl = null; - - public PepsConnectorTask() { - super(); - 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(); - } - } - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws Exception { - 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.validateSTORKAuthnResponse(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); - - // load MOASession from database - AuthenticationSession moaSession = AuthenticationServer.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); - - // //////////// incorporate gender from parameters if not in stork response - - IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); - - // 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 tmp = new ArrayList(); - tmp.add(gendervalue); - gender.setValue(tmp); - - authnResponse.getPersonalAttributeList().add(gender); - } - } - } - - // //////////////////////////////////////////////////////////////////////// - - Logger.debug("Starting extraction of signedDoc attribute"); - // extract signed doc element and citizen signature - String citizenSignature = null; - try { - String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING - - Logger.debug("signatureInfo:" + signatureInfo); - - SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource( - new java.io.StringReader(signatureInfo))); - - // fetch signed doc - DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse); - if (ds == null) { - throw new ApiUtilsException("No datasource found in response"); - } - - InputStream incoming = ds.getInputStream(); - citizenSignature = IOUtils.toString(incoming); - incoming.close(); - - Logger.debug("citizenSignature:" + citizenSignature); - if (isDocumentServiceUsed(citizenSignature) == true) { - Logger.debug("Loading document from DocumentService."); - String url = getDtlUrlFromResponse(dssSignResponse); - // get Transferrequest - String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url); - // Load document from DocujmentService - 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) 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) 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); - // } - OAAuthParameter oaParam = AuthConfigurationProvider.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; - executionContext.put("identityLinkAvailable", false); - try { - identityLink = STORKResponseProcessor.connectToSZRGateway(authnResponse.getPersonalAttributeList(), - 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); - } - 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(authnResponse.getPersonalAttributeList()); - - 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); - - // TODO: found better solution, but QAA Level in response could be not 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) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - - } - - private boolean isDocumentServiceUsed(String citizenSignature) // TODo add better check - { - if (citizenSignature - .contains("
              Service Name:{http://stork.eu}DocumentService
              Port Name:{http://stork.eu}DocumentServicePort
              ")) - return true; - 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 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 { - url = new URL(dtlUrl); - 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(dtlUrl)) - 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(dtlUrl); - 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); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index d6c15c658..bc8a01e41 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -35,13 +35,13 @@ 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.registration.ModuleRegistration; import at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.config.TemplateType; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.moduleregistration.ModuleRegistration; import at.gv.egovernment.moa.id.process.ExecutionContextImpl; import at.gv.egovernment.moa.id.process.ProcessInstance; import at.gv.egovernment.moa.id.process.api.ExecutionContext; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 0a7f71713..b239fbb1d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -68,6 +68,7 @@ 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.BuildException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; import at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; @@ -76,7 +77,6 @@ import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.SLOInformationContainer; import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.moduls.moduleregistration.ModuleRegistration; import at.gv.egovernment.moa.id.process.ExecutionContextImpl; import at.gv.egovernment.moa.id.process.ProcessEngine; import at.gv.egovernment.moa.id.process.ProcessExecutionException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java deleted file mode 100644 index 295a51a24..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/AuthModule.java +++ /dev/null @@ -1,41 +0,0 @@ -package at.gv.egovernment.moa.id.moduls.moduleregistration; - -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.process.model.ProcessDefinition; - -/** - * Defines the module capabilities. - */ -public interface AuthModule { - - /** - * Returns the priority of the module. The priority defines the order of the respective module within the chain of - * discovered modules. Higher priorized modules are asked before lower priorized modules for a process that they can - * handle. - *

              - * Internal default modules are priorized neutral ({@code 0}. Use a higher priority ({@code 1...Integer.MAX_VALUE}) - * in order to have your module(s) priorized or a lower priority ({@code Integer.MIN_VALUE...-1}) in order to put - * your modules behind default modules. - * - * @return the priority of the module. - */ - int getPriority(); - - /** - * Checks if the module has a process, which is able to perform an authentication with the given - * {@link ExecutionContext}. - * - * @param context - * an ExecutionContext for a process. - * @return the process-ID of a process which is able to work with the given ExecutionContext, or {@code null}. - */ - String selectProcess(ExecutionContext context); - - /** - * Returns the an Array of {@link ProcessDefinition}s of the processes included in this module. - * - * @return an array of resource uris of the processes included in this module. - */ - String[] getProcessDefinitions(); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java deleted file mode 100644 index 9e06a9ec8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/moduleregistration/ModuleRegistration.java +++ /dev/null @@ -1,149 +0,0 @@ -package at.gv.egovernment.moa.id.moduls.moduleregistration; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.ServiceLoader; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.core.io.Resource; - -import at.gv.egovernment.moa.id.process.ProcessDefinitionParserException; -import at.gv.egovernment.moa.id.process.ProcessEngine; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; - -/** - * This class handles registering modules. The modules are detected either with - * the ServiceLoader mechanism or via Spring. All detected modules are ranked - * according to their priority. - */ -public class ModuleRegistration { - - private static ModuleRegistration instance = new ModuleRegistration(); - - private List priorizedModules = new ArrayList<>(); - - @Autowired - private ApplicationContext ctx; - - @Autowired - private ProcessEngine processEngine; - - private Logger log = LoggerFactory.getLogger(getClass()); - - public static ModuleRegistration getInstance() { - return instance; - } - - private ModuleRegistration() { - } - - @PostConstruct - private void init() { - // load modules via the ServiceLoader - initServiceLoaderModules(); - - // load modules via Spring - initSpringModules(); - - // order modules according to their priority - priorizeModules(); - } - - /** - * Discovers modules which use the ServiceLoader mechanism. - */ - private void initServiceLoaderModules() { - log.info("Looking for auth modules."); - ServiceLoader loader = ServiceLoader.load(AuthModule.class); - Iterator modules = loader.iterator(); - while (modules.hasNext()) { - AuthModule module = modules.next(); - log.info("Detected module {}", module.getClass().getName()); - registerResourceUris(module); - priorizedModules.add(module); - } - } - - /** - * Discovers modules which use Spring. - */ - private void initSpringModules() { - log.debug("Discovering Spring modules."); - Map modules = ctx.getBeansOfType(AuthModule.class); - for (AuthModule module : modules.values()) { - registerResourceUris(module); - priorizedModules.add(module); - } - } - - /** - * Registers the resource uris for the module. - * - * @param module - * the module. - */ - private void registerResourceUris(AuthModule module) { - for (String uri : module.getProcessDefinitions()) { - Resource resource = ctx.getResource(uri); - if (resource.isReadable()) { - log.info("Registering process definition resource: '{}'.", uri); - try (InputStream processDefinitionInputStream = resource.getInputStream()) { - processEngine.registerProcessDefinition(processDefinitionInputStream); - } catch (IOException e) { - log.error("Resource uri: '{}' could NOT be read.", uri, e); - } catch (ProcessDefinitionParserException e) { - log.error("Error while parsing process definition in '{}'", uri, e); - } - } else { - log.error("Resource uri: '{}' cannot be read.", uri); - } - } - } - - /** - * Order the modules in descending order according to their priority. - */ - private void priorizeModules() { - Collections.sort(priorizedModules, new Comparator() { - @Override - public int compare(AuthModule thisAuthModule, AuthModule otherAuthModule) { - int thisOrder = thisAuthModule.getPriority(); - int otherOrder = otherAuthModule.getPriority(); - return (thisOrder < otherOrder ? -1 : (thisOrder == otherOrder ? 0 : 1)); - } - }); - log.debug("Modules are ordered in descending order, according to their priority."); - } - - /** - * Returns the process id of the first process, in the highest ranked - * module, which is able to work with the given execution context. - * - * @param context - * the {@link ExecutionContext}. - * @return the process id or {@code null} - */ - public String selectProcess(ExecutionContext context) { - for (AuthModule module : priorizedModules) { - String id = module.selectProcess(context); - if (StringUtils.isNotEmpty(id)) { - log.debug("Process with id '{}' selected, for context '{}'.", id, context); - return id; - } - } - log.info("No process is able to handle context '{}'.", context); - return null; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java index 2f1487564..ff6ec969e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java @@ -27,8 +27,9 @@ public interface ProcessEngine { * * @param processDefinitionInputStream The input stream to the definition to be registered. * @throws ProcessDefinitionParserException Thrown in case of an error parsing the process definition. + * @return The process definition's identifier. */ - void registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException; + String registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException; /** * Creates a process instance according to the referenced process definition, persists it into the database and returns it identifier. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java index ea5a2684e..eb6a29ad9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java @@ -55,8 +55,10 @@ public class ProcessEngineImpl implements ProcessEngine { } @Override - public void registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException{ - registerProcessDefinition(pdp.parse(processDefinitionInputStream)); + public String registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException{ + ProcessDefinition pd = pdp.parse(processDefinitionInputStream); + registerProcessDefinition(pd); + return pd.getId(); } /** -- cgit v1.2.3 From a22b7f1660560569701d086b4075192fa83ee6a8 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Wed, 4 Feb 2015 12:17:31 +0100 Subject: Persistence issue fixed (MOAID-62) - ProcessInstanceStore: Removed primary key column "id", set processInstanceId as new primary key column. - Renamed "save"-methods that actually save-or-update to "saveOrUpdate...". --- .../at/gv/egovernment/moa/id/process/ProcessEngineImpl.java | 12 +++++------- .../egovernment/moa/id/process/dao/ProcessInstanceStore.java | 4 ---- .../moa/id/process/dao/ProcessInstanceStoreDAO.java | 2 +- .../moa/id/process/dao/ProcessInstanceStoreDAOImpl.java | 5 +---- 4 files changed, 7 insertions(+), 16 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java index eb6a29ad9..650bae44e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java @@ -30,8 +30,6 @@ import at.gv.egovernment.moa.id.process.model.Transition; /** * Process engine implementation allowing starting and continuing processes as well as providing means for cleanup actions. - * @author tknall - * */ public class ProcessEngineImpl implements ProcessEngine { @@ -101,7 +99,7 @@ public class ProcessEngineImpl implements ProcessEngine { log.info("Creating process instance from process definition '{}': {}", processDefinitionId, pi.getId()); try { - saveProcessInstance(pi); + saveOrUpdateProcessInstance(pi); } catch (MOADatabaseException e) { throw new ProcessExecutionException("Unable to persist process instance.", e); } @@ -133,7 +131,7 @@ public class ProcessEngineImpl implements ProcessEngine { pi.setState(ProcessInstanceState.STARTED); execute(pi); - saveProcessInstance(pi); + saveOrUpdateProcessInstance(pi); } catch (MOADatabaseException e) { throw new ProcessExecutionException("Unable to load/save process instance.", e); @@ -162,7 +160,7 @@ public class ProcessEngineImpl implements ProcessEngine { pi.setState(ProcessInstanceState.STARTED); execute(pi); - saveProcessInstance(pi); + saveOrUpdateProcessInstance(pi); } catch (MOADatabaseException e) { throw new ProcessExecutionException("Unable to load/save process instance.", e); @@ -314,7 +312,7 @@ public class ProcessEngineImpl implements ProcessEngine { * @param processInstance The object to persist. * @throws MOADatabaseException Thrown if an error occurs while accessing the database. */ - private void saveProcessInstance(ProcessInstance processInstance) throws MOADatabaseException { + private void saveOrUpdateProcessInstance(ProcessInstance processInstance) throws MOADatabaseException { ProcessInstanceStore store = new ProcessInstanceStore(); ExecutionContext ctx = processInstance.getExecutionContext(); @@ -331,7 +329,7 @@ public class ProcessEngineImpl implements ProcessEngine { store.setProcessInstanceId(processInstance.getId()); store.setProcessState(processInstance.getState()); - piStoreDao.save(store); + piStoreDao.saveOrUpdate(store); } /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java index c6bf86823..582f50427 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -19,11 +19,7 @@ import at.gv.egovernment.moa.id.process.ProcessInstanceState; @Table(name = "processinstance") public class ProcessInstanceStore { - @Column(name = "id") @Id - private int id; - - @Column(name = "processInstanceId", unique = true, nullable = false) private String processInstanceId; @Column(name = "processDefinitionId", nullable = false) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java index 999a9b82b..6f8a8c66c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java @@ -16,7 +16,7 @@ public interface ProcessInstanceStoreDAO { * @throws MOADatabaseException * is thrown if a problem occurs while accessing the database. */ - void save(ProcessInstanceStore pIStore) throws MOADatabaseException; + void saveOrUpdate(ProcessInstanceStore pIStore) throws MOADatabaseException; /** * Returns a {@link ProcessInstanceStore}, defined by diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index 0a50afc6c..012dfe90b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -1,8 +1,5 @@ package at.gv.egovernment.moa.id.process.dao; -import java.util.Collections; -import java.util.List; - import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; @@ -28,7 +25,7 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { } @Override - public void save(ProcessInstanceStore pIStore) throws MOADatabaseException { + public void saveOrUpdate(ProcessInstanceStore pIStore) throws MOADatabaseException { try { MOASessionDBUtils.saveOrUpdate(pIStore); log.debug("Store process instance with='{}' in the database.", pIStore.getProcessInstanceId()); -- cgit v1.2.3 From 215b326e807659b30c520478e8123a888df6d204 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Wed, 4 Feb 2015 13:19:53 +0100 Subject: Add comment to ProcessInstanceStore primary key field --- .../gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java index 582f50427..d690c37bf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java @@ -19,6 +19,15 @@ import at.gv.egovernment.moa.id.process.ProcessInstanceState; @Table(name = "processinstance") public class ProcessInstanceStore { + /** + * A process instance identifier qualifies as natural primary key by satisfying these requirements + * ("unique, constant, required"): + *

                + *
              • unique value
              • + *
              • never changes (immutable)
              • + *
              • never {@code null}
              • + *
              + */ @Id private String processInstanceId; -- cgit v1.2.3 From 74a42b6128f6f8d21a65dddb9405cd52ebbc0520 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Wed, 4 Feb 2015 15:37:10 +0100 Subject: Create exemplary AuthServlet module (MOAID-68) - Create new module moa-id-module-monitoring. - Move MonitoringServlet, DatabaseTestModule, IdentityLinkTestModule, TestManager and TestModuleInterface to new module. - Update pom.xml, adding new module dependency. - Update web.xml, disabling static servlet registration. - Add @WebServlet servlet registration for MonitoringServlet. --- .../moa/id/auth/servlet/MonitoringServlet.java | 126 ------------------ .../moa/id/monitoring/DatabaseTestModule.java | 142 --------------------- .../moa/id/monitoring/IdentityLinkTestModule.java | 109 ---------------- .../egovernment/moa/id/monitoring/TestManager.java | 111 ---------------- .../moa/id/monitoring/TestModuleInterface.java | 34 ----- 5 files changed, 522 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/TestManager.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/TestModuleInterface.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java deleted file mode 100644 index e04f97e6e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java +++ /dev/null @@ -1,126 +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.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.monitoring.TestManager; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class MonitoringServlet extends AuthServlet { - - private static final long serialVersionUID = 1L; - private static final String REQUEST_ATTR_MODULE = "module"; - - - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - try { - AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); - - if (config.isMonitoringActive()) { - Logger.debug("Monitoring Servlet received request"); - - TestManager tests = TestManager.getInstance(); - - String modulename = req.getParameter(REQUEST_ATTR_MODULE); - if (MiscUtil.isEmpty(modulename)) { - - List error = tests.executeTests(); - if (error != null && error.size() > 0) { - createErrorMessage(req, resp, error); - - } else { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/html;charset=UTF-8"); - resp.getWriter().write(getHtml(config.getMonitoringMessageSuccess())); - Logger.info("Monitoring Servlet finished without errors"); - } - - } else { - if (tests.existsModule(modulename)) { - List errors = tests.executeTest(modulename); - if (errors != null && errors.size() > 0) { - createErrorMessage(req, resp, errors); - - } else { - resp.setStatus(HttpServletResponse.SC_OK); - resp.setContentType("text/html;charset=UTF-8"); - resp.getWriter().write(getHtml(config.getMonitoringMessageSuccess())); - Logger.info("Monitoring Servlet finished without errors"); - } - - } else { - Logger.warn("NO Testmodule exists with modulename " + modulename); - resp.setStatus(HttpServletResponse.SC_NOT_FOUND); - resp.setContentType("text/html;charset=UTF-8"); - PrintWriter out; - try { - out = new PrintWriter(resp.getOutputStream()); - out.write("NO Testmodule exists with modulename " + modulename); - out.flush(); - - } catch (IOException e) { - Logger.warn("Internal Monitoring Servlet Error. ", e); - } - } - - } - } - - } catch (ConfigurationException e) { - createErrorMessage(req, resp, Arrays.asList(e.getMessage())); - } - } - - private void createErrorMessage(HttpServletRequest req, HttpServletResponse resp, List errorMessage) { - Logger.warn("Monitoring Servlet found some Error: " + errorMessage); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - resp.setContentType("text/html;charset=UTF-8"); - PrintWriter out; - try { - out = new PrintWriter(resp.getOutputStream()); - for (String error : errorMessage) - out.write(error + "
              "); - out.flush(); - - } catch (IOException e) { - Logger.warn("Internal Monitoring Servlet Error. ", e); - } - } - - private String getHtml(String text) { - return "Reponse" + text +""; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java deleted file mode 100644 index a08ef5f0c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/DatabaseTestModule.java +++ /dev/null @@ -1,142 +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.monitoring; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.hibernate.Query; -import org.hibernate.Session; - -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; -import at.gv.egovernment.moa.id.commons.db.StatisticLogDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.MOAIDConfiguration; -import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; -import at.gv.egovernment.moa.id.commons.db.dao.statistic.StatisticLog; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class DatabaseTestModule implements TestModuleInterface{ - - public List performTests() throws Exception { - Logger.trace("Start MOA-ID Database Test."); - - List errors = new ArrayList(); - - AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); - - String error = testMOAConfigurationDatabase(); - if (MiscUtil.isNotEmpty(error)) - errors.add(error); - - error = testMOASessionDatabase(); - if (MiscUtil.isNotEmpty(error)) - errors.add(error); - - if (config.isAdvancedLoggingActive()) { - error = testMOAAdvancedLoggingDatabase(); - if (MiscUtil.isNotEmpty(error)) - errors.add(error); - } - - return errors; - } - - - private String testMOASessionDatabase() throws Exception{ - Logger.trace("Start Test: MOASessionDatabase"); - - Date expioredate = new Date(new Date().getTime() - 120); - - try { - List results; - Session session = MOASessionDBUtils.getCurrentSession(); - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getAssertionWithTimeOut"); - query.setTimestamp("timeout", expioredate); - results = query.list(); - session.getTransaction().commit(); - } - - Logger.trace("Finish Test: MOASessionDatabase"); - return null; - - } catch (Throwable e) { - Logger.warn("Failed Test: MOASessionDatabase", e); - return "MOASessionDatabase: " + e.getMessage(); - } - } - - private String testMOAConfigurationDatabase() throws Exception{ - - MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); - ConfigurationDBUtils.closeSession(); - - if (moaidconfig == null) - return ("MOA-ID 2.x configuration can not be loaded from Database."); - - return null; - } - - private String testMOAAdvancedLoggingDatabase() { - - Date expioredate = new Date(new Date().getTime() - 120); - try { - Session session = StatisticLogDBUtils.getCurrentSession(); - - List results; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getAllEntriesNotBeforeTimeStamp"); - query.setTimestamp("timeout", expioredate); - results = query.list(); - session.getTransaction().commit(); - } - - Logger.trace("Finish Test: AdvancedLoggingDataBase"); - return null; - - } catch (Throwable e) { - Logger.warn("Failed Test: AdvancedLoggingDataBase", e); - return "AdvancedLoggingDataBase: " + e.getMessage(); - } - } - - - public String getName() { - return "DatabaseTest"; - } - - - public void initializeTest(long delayParam, String url) throws Exception { - // TODO Auto-generated method stub - - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java deleted file mode 100644 index b5220914c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java +++ /dev/null @@ -1,109 +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.monitoring; - -import java.io.InputStream; -import java.net.URL; -import java.util.List; - -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.auth.builder.VerifyXMLSignatureRequestBuilder; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; -import at.gv.egovernment.moa.id.auth.exception.ValidateException; -import at.gv.egovernment.moa.id.auth.invoke.SignatureVerificationInvoker; -import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; -import at.gv.egovernment.moa.id.auth.parser.VerifyXMLSignatureResponseParser; -import at.gv.egovernment.moa.id.auth.validator.IdentityLinkValidator; -import at.gv.egovernment.moa.id.auth.validator.VerifyXMLSignatureResponseValidator; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.data.DynamicOAAuthParameters; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class IdentityLinkTestModule implements TestModuleInterface { - - private static IdentityLink identityLink = null; - - public void initializeTest(long delayParam, String url) throws Exception{ - - if (MiscUtil.isNotEmpty(url)) { - - URL keystoreURL = new URL(url); - InputStream idlstream = keystoreURL.openStream(); - identityLink = new IdentityLinkAssertionParser(idlstream).parseIdentityLink(); - } - - } - - public List performTests() throws Exception{ - Logger.trace("Start MOA-ID IdentityLink Test"); - - AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); - - IdentityLinkValidator.getInstance().validate(identityLink); - // builds a for a call of MOA-SP - Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() - .build(identityLink, config - .getMoaSpIdentityLinkTrustProfileID()); - - // invokes the call - Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() - .verifyXMLSignature(domVerifyXMLSignatureRequest); - // parses the - try { - VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( - domVerifyXMLSignatureResponse).parseData(); - - DynamicOAAuthParameters oaParam = new DynamicOAAuthParameters(); - oaParam.setBusinessService(true); - - VerifyXMLSignatureResponseValidator.getInstance().validate( - verifyXMLSignatureResponse, - config.getIdentityLinkX509SubjectNames(), - VerifyXMLSignatureResponseValidator.CHECK_IDENTITY_LINK, - oaParam); - - } catch (ValidateException e) { - //check if default Monitoring IDL is used then error is ignored - if ("validator.07".equals(e.getMessageId()) - && e.getMessage().contains("Das Zertifikat der Personenbindung ist")) - return null; - - else - throw e; - - } - - Logger.trace("Finished MOA-ID IdentityLink Test without errors"); - - return null; - } - - public String getName() { - return "IdentityLinkTest"; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/TestManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/TestManager.java deleted file mode 100644 index 84581abe8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/TestManager.java +++ /dev/null @@ -1,111 +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.monitoring; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.FileUtils; - -public class TestManager { - - private static TestManager instance; - - private Map tests = new HashMap(); - - public static TestManager getInstance() throws ConfigurationException { - if (instance == null) - instance = new TestManager(); - - return instance; - } - - private TestManager() throws ConfigurationException { - - AuthConfigurationProvider config = AuthConfigurationProvider.getInstance(); - - //add Database test - DatabaseTestModule test1 = new DatabaseTestModule(); - tests.put(test1.getName(), test1); - - //add IdentityLink verification test - IdentityLinkTestModule test2 = new IdentityLinkTestModule(); - String idlurl = FileUtils.makeAbsoluteURL(config.getMonitoringTestIdentityLinkURL(), config.getRootConfigFileDir()); - try { - test2.initializeTest(0, idlurl); - tests.put(test2.getName(), test2);; - - } catch (Exception e) { - Logger.warn("MOA-ID IdentityLink Test can not performed without IdentityLink. Insert IdentityLink file to MOA-ID configuration", e); - } - } - - public List executeTests() { - Logger.debug("Start MOA-ID-Auth testing"); - - - List errors; - - for (TestModuleInterface test : tests.values()) { - try { - errors = test.performTests(); - if (errors != null && errors.size() > 0) - return errors; - - } catch (Exception e) { - Logger.warn("General Testing Eception during Test " + test.getClass() + ": ", e); - return Arrays.asList(e.getMessage()); - } - } - - return null; - } - - public List executeTest(String testname) { - - TestModuleInterface test = tests.get(testname); - - if (test != null) { - try { - return test.performTests(); - - } catch (Exception e) { - Logger.warn("General Testing Eception during Test " + test.getName() + ": ", e); - return Arrays.asList(e.getMessage()); - } - - } else { - Logger.info("TestModule with Name " + testname + " is not implemented"); - return null; - } - } - - public boolean existsModule(String modulename) { - return tests.containsKey(modulename); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/TestModuleInterface.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/TestModuleInterface.java deleted file mode 100644 index 4e26b1ce8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/monitoring/TestModuleInterface.java +++ /dev/null @@ -1,34 +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.monitoring; - -import java.util.List; - -public interface TestModuleInterface { - - public List performTests() throws Exception; - - public void initializeTest(long delayParam, String url) throws Exception; - - public String getName(); -} -- cgit v1.2.3 From 63fb8960f4a72f9185d2dc4735d8bae602463e1c Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Thu, 5 Feb 2015 16:53:03 +0100 Subject: Fix wrong module sorting order. --- .../moa/id/auth/modules/registration/ModuleRegistration.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java index c2a34ff21..fa1878e74 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java @@ -122,7 +122,7 @@ public class ModuleRegistration { public int compare(AuthModule thisAuthModule, AuthModule otherAuthModule) { int thisOrder = thisAuthModule.getPriority(); int otherOrder = otherAuthModule.getPriority(); - return (thisOrder < otherOrder ? -1 : (thisOrder == otherOrder ? 0 : 1)); + return (thisOrder < otherOrder ? 1 : (thisOrder == otherOrder ? 0 : -1)); } }); } -- cgit v1.2.3 From b864faef2864cc28df98d778e2221bf2cf911954 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Thu, 5 Feb 2015 16:56:04 +0100 Subject: Perform some cleanup tasks - Rename AbstractSpringWebSupportedTask to MoaIdTask. - Remove some unnecessary code. --- .../id/auth/modules/AbstractAuthServletTask.java | 4 +- .../egovernment/moa/id/process/ProcessEngine.java | 1 - .../moa/id/process/ProcessEngineImpl.java | 12 +--- .../id/process/dao/ProcessInstanceStoreDAO.java | 2 - .../springweb/AbstractSpringWebSupportedTask.java | 73 ---------------------- .../moa/id/process/springweb/MoaIdTask.java | 73 ++++++++++++++++++++++ 6 files changed, 77 insertions(+), 88 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java index 3b20e85d7..67ddd170a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java @@ -32,7 +32,7 @@ import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; -import at.gv.egovernment.moa.id.process.springweb.AbstractSpringWebSupportedTask; +import at.gv.egovernment.moa.id.process.springweb.MoaIdTask; import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; import at.gv.egovernment.moa.id.storage.IExceptionStore; import at.gv.egovernment.moa.id.util.ServletUtils; @@ -43,7 +43,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing * etc.).

              The code has been taken from {@link AuthServlet}. */ -public abstract class AbstractAuthServletTask extends AbstractSpringWebSupportedTask { +public abstract class AbstractAuthServletTask extends MoaIdTask { protected static final String ERROR_CODE_PARAM = "errorid"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java index ff6ec969e..032cb6369 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java @@ -2,7 +2,6 @@ package at.gv.egovernment.moa.id.process; import java.io.InputStream; -import java.io.Serializable; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.process.model.ProcessDefinition; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java index 650bae44e..0ffa22ec3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java @@ -115,13 +115,10 @@ public class ProcessEngineImpl implements ProcessEngine { @Override public void start(String processInstanceId) throws ProcessExecutionException { - boolean mdcEntryAdded = false; - try { ProcessInstance pi = loadProcessInstance(processInstanceId); MDC.put(MDC_CTX_PI_NAME, pi.getId()); - mdcEntryAdded = true; if (!ProcessInstanceState.NOT_STARTED.equals(pi.getState())) { throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has already been started (current state is " + pi.getState() + ")."); @@ -136,21 +133,17 @@ public class ProcessEngineImpl implements ProcessEngine { throw new ProcessExecutionException("Unable to load/save process instance.", e); } finally { - if (mdcEntryAdded) - MDC.remove(MDC_CTX_PI_NAME); + MDC.remove(MDC_CTX_PI_NAME); } } @Override public void signal(String processInstanceId) throws ProcessExecutionException { - boolean mdcEntryAdded = false; - try { ProcessInstance pi = loadProcessInstance(processInstanceId); MDC.put(MDC_CTX_PI_NAME, pi.getId()); - mdcEntryAdded = true; if (!ProcessInstanceState.SUSPENDED.equals(pi.getState())) { throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has not been suspended (current state is " + pi.getState() + ")."); @@ -165,8 +158,7 @@ public class ProcessEngineImpl implements ProcessEngine { throw new ProcessExecutionException("Unable to load/save process instance.", e); } finally { - if (mdcEntryAdded) - MDC.remove(MDC_CTX_PI_NAME); + MDC.remove(MDC_CTX_PI_NAME); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java index 6f8a8c66c..92ffe11db 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java @@ -1,7 +1,5 @@ package at.gv.egovernment.moa.id.process.dao; -import java.util.List; - import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.process.ProcessInstance; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java deleted file mode 100644 index c9262cea9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractSpringWebSupportedTask.java +++ /dev/null @@ -1,73 +0,0 @@ -package at.gv.egovernment.moa.id.process.springweb; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.filter.RequestContextFilter; - -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.process.api.Task; - -/** - * Abstract task implementation providing {@link HttpServletRequest} and {@link HttpServletResponse}. - *

              - * Note that this abstract task requires the Spring (web) framework including a {@link RequestContextFilter} to be set - * within {@code web.xml}. - * - *

              - * ...
              - * <filter>
              - *   <filter-name>requestContextFilter</filter-name>
              - *   <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
              - * </filter>
              - * <filter-mapping>
              - *   <filter-name>requestContextFilter</filter-name>
              - *   <url-pattern>/*</url-pattern>
              - * </filter-mapping>
              - * ...
              - * 
              - * - * @author tknall - * - */ -public abstract class AbstractSpringWebSupportedTask implements Task { - - /** - * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} as well as the - * respective {@link HttpServletRequest} and {@link HttpServletResponse}. - * - * @param executionContext - * The execution context (never {@code null}). - * @param request - * The HttpServletRequest (never {@code null}). - * @param response - * The HttpServletResponse (never {@code null}). - * @throws IllegalStateException - * Thrown in case the task is nur being run within the required environment. Refer to javadoc for - * further information. - * @throws Exception - * Thrown in case of error executing the task. - */ - public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws Exception; - - @Override - public void execute(ExecutionContext executionContext) throws Exception { - RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { - HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); - HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse(); - if (request == null || response == null) { - throw new IllegalStateException( - "Spring's RequestContextHolder did not provide HttpServletResponse. Did you forget to set the required org.springframework.web.filter.RequestContextFilter in your web.xml."); - } - execute(executionContext, request, response); - } else { - throw new IllegalStateException("Task needs to be executed within a Spring web environment."); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java new file mode 100644 index 000000000..bae6391ec --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java @@ -0,0 +1,73 @@ +package at.gv.egovernment.moa.id.process.springweb; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.filter.RequestContextFilter; + +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.process.api.Task; + +/** + * Abstract task implementation providing {@link HttpServletRequest} and {@link HttpServletResponse}. + *

              + * Note that this abstract task requires the Spring (web) framework including a {@link RequestContextFilter} to be set + * within {@code web.xml}. + * + *

              + * ...
              + * <filter>
              + *   <filter-name>requestContextFilter</filter-name>
              + *   <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
              + * </filter>
              + * <filter-mapping>
              + *   <filter-name>requestContextFilter</filter-name>
              + *   <url-pattern>/*</url-pattern>
              + * </filter-mapping>
              + * ...
              + * 
              + * + * @author tknall + * + */ +public abstract class MoaIdTask implements Task { + + /** + * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} as well as the + * respective {@link HttpServletRequest} and {@link HttpServletResponse}. + * + * @param executionContext + * The execution context (never {@code null}). + * @param request + * The HttpServletRequest (never {@code null}). + * @param response + * The HttpServletResponse (never {@code null}). + * @throws IllegalStateException + * Thrown in case the task is nur being run within the required environment. Refer to javadoc for + * further information. + * @throws Exception + * Thrown in case of error executing the task. + */ + public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, + HttpServletResponse response) throws Exception; + + @Override + public void execute(ExecutionContext executionContext) throws Exception { + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { + HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); + HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse(); + if (request == null || response == null) { + throw new IllegalStateException( + "Spring's RequestContextHolder did not provide HttpServletResponse. Did you forget to set the required org.springframework.web.filter.RequestContextFilter in your web.xml."); + } + execute(executionContext, request, response); + } else { + throw new IllegalStateException("Task needs to be executed within a Spring web environment."); + } + } + +} -- cgit v1.2.3 From 271e22add71f0260f5d421844a2171a09093f505 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Fri, 6 Feb 2015 11:09:59 +0100 Subject: Code cleanup - Set moa-id version to 2.2.0-SNAPSHOT. - Fix Javadoc syntax issues in newly added classes. - Add warning log when executing deprecated auth sources. --- .../modules/internal/tasks/PrepareAuthBlockSignatureTask.java | 4 ++-- .../gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java | 4 +--- .../egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java | 4 +--- .../gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java | 2 ++ .../moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java | 2 ++ .../moa/id/auth/servlet/ProcessEngineSignalServlet.java | 2 -- .../moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java | 8 ++------ .../egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java | 5 ++--- .../moa/id/auth/servlet/VerifyIdentityLinkServlet.java | 6 ++---- .../main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java | 2 +- .../egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java | 4 ++-- .../moa/id/process/springweb/SpringWebExpressionEvaluator.java | 1 + 12 files changed, 18 insertions(+), 26 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java index 36d6ea555..dcea3a1dd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java @@ -27,7 +27,7 @@ import at.gv.egovernment.moa.logging.Logger; *
                *
              • Renames the moa session id.
              • *
              • Creates {@code CreateXMLSignatureRequest} for auth block signature.
              • - *
              • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
              • + *
              • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code /VerifyAuthBlock}
              • *
              * Expects: *
                @@ -35,7 +35,7 @@ import at.gv.egovernment.moa.logging.Logger; *
              * Result: *
                - *
              • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code {/VerifyAuthBlock}
              • + *
              • Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code /VerifyAuthBlock}
              • *
              * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet}. * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java index 64899565b..41c2a9c6a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java @@ -136,9 +136,7 @@ public class GetForeignIDServlet extends AuthServlet { Logger.debug("POST GetForeignIDServlet"); - if (System.currentTimeMillis() > 0) { - throw new IllegalStateException(getClass().getName() + " should not be called any more."); - } + Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java index ffd01299e..043b660c1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java @@ -137,9 +137,7 @@ public class GetMISSessionIDServlet extends AuthServlet { Logger.debug("POST GetMISSessionIDServlet"); - if (System.currentTimeMillis() > 0) { - throw new IllegalStateException(getClass().getName() + " should not be called any more."); - } + Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index af4b7ffbb..e45418b4b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -138,6 +138,8 @@ public class PEPSConnectorServlet extends AuthServlet { try { + Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); + Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message."); Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request)); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java index c01a356f6..337a9ed31 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java @@ -132,6 +132,8 @@ public class PEPSConnectorWithLocalSigningServlet extends AuthServlet { */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); + String moaSessionID1 = request.getParameter("moaSessionID"); String signResponse = request.getParameter("signresponse"); Logger.info("moaSessionID1:"+moaSessionID1); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java index a40c7982b..a99b7aeef 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -9,11 +9,9 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; -import at.gv.egovernment.moa.id.process.ProcessInstance; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java index 67c42cd07..a8fe71485 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java @@ -153,19 +153,15 @@ public class VerifyAuthenticationBlockServlet extends AuthServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (System.currentTimeMillis() > 0) { - throw new IllegalStateException(getClass().getName() + " should not be called any more."); - } Logger.debug("POST VerifyAuthenticationBlock"); + Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - if (System.currentTimeMillis() > 0) { - throw new IllegalStateException(getClass().getName() + " should not be called any more."); - } String pendingRequestID = null; Map parameters; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java index 82cdb2778..2aa717a65 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java @@ -126,11 +126,10 @@ public class VerifyCertificateServlet extends AuthServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (System.currentTimeMillis() > 0) { - throw new IllegalStateException(getClass().getName() + " should not be called any more."); - } Logger.debug("POST VerifyCertificateServlet"); + Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); + resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES,MOAIDAuthConstants.HEADER_VALUE_EXPIRES); resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA,MOAIDAuthConstants.HEADER_VALUE_PRAGMA); resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java index 6f2ee2d89..b8e57ed43 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java @@ -134,11 +134,9 @@ public class VerifyIdentityLinkServlet extends AuthServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - if (System.currentTimeMillis() > 0) { - throw new IllegalStateException(getClass().getName() + " should not be called any more."); - } - Logger.debug("POST VerifyIdentityLink"); + + Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); Map parameters; String pendingRequestID = null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java index 032cb6369..5cf84abed 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java @@ -50,7 +50,7 @@ public interface ProcessEngine { * Creates a process instance according to the referenced process definition, persists it into the database and returns it identifier. *

              * Note that the method returns the identifier of a process instance which will be needed in order to start a process or to continue - * process execution after asynchronous task execution (refer to {@link #start(String))} and + * process execution after asynchronous task execution (refer to {@link #start(String)} and * {@link #signal(String)} for further information). * * @param processDefinitionId diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java index 92ffe11db..57ce70c08 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java @@ -21,7 +21,7 @@ public interface ProcessInstanceStoreDAO { * {@code processInstanceID} from the database, or {@code null} if the * object could not be found. * - * @param processInstanceID + * @param processInstanceId * the id of the {@code ProcessInstanceStore} to retrieve. * @return a ProcessInstanceStore, or {@code null}. * @throws MOADatabaseException @@ -33,7 +33,7 @@ public interface ProcessInstanceStoreDAO { * Deletes the {@link ProcessInstance} corresponding with the * {@code processInstanceId}. * - * @param processInstanceID + * @param processInstanceId * the id of the {@code ProcessInstance} to be deleted. * @throws MOADatabaseException * is thrown if a problem occurs while accessing the database. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java index 9dd7bc61e..499e86fa0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java @@ -19,6 +19,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.expression.BeanFactoryResolver; import org.springframework.expression.Expression; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; -- cgit v1.2.3 From bceb4fd58c7d17c4fdc6908f77f546c96c0920a4 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 18 Feb 2015 13:29:24 +0100 Subject: update PVP attribute builder --> use mandate annotation as MANDATOR-PROF-REP-DESCRIPTION --- .../MandateProfRepDescAttributeBuilder.java | 40 ++++++++++++++++------ .../moa/id/util/client/mis/simple/MISMandate.java | 8 ++++- 2 files changed, 36 insertions(+), 12 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java index 4c981cb24..1059e324e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java @@ -22,10 +22,14 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; +import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.util.MiscUtil; @@ -37,23 +41,37 @@ public class MandateProfRepDescAttributeBuilder implements IPVPAttributeBuilder public ATT build(OAAuthParameter oaParam, IAuthData authData, IAttributeGenerator g) throws AttributeException { - if(authData.isUseMandate()) { - MISMandate mandate = authData.getMISMandate(); - + if(authData.isUseMandate()) { + Element mandate = authData.getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + } - if(mandate == null) { + Mandate mandateObject = MandateBuilder.buildMandate(authData.getMandate()); + if (mandateObject == null) { throw new NoMandateDataAttributeException(); } + + String text = null; + if (MiscUtil.isNotEmpty(mandateObject.getAnnotation())) { + text = mandateObject.getAnnotation(); + + } else { + MISMandate misMandate = authData.getMISMandate(); - String text = mandate.getTextualDescriptionOfOID(); + if(misMandate == null) { + throw new NoMandateDataAttributeException(); + } - if(MiscUtil.isEmpty(text)) { - return null; - - } else - return g.buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, - MANDATE_PROF_REP_DESC_NAME, text); + text = misMandate.getTextualDescriptionOfOID(); + if(MiscUtil.isEmpty(text)) { + return null; + + } else + return g.buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, + MANDATE_PROF_REP_DESC_NAME, text); + } } return null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISMandate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISMandate.java index 20cabaf4d..1edb8d1f3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISMandate.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISMandate.java @@ -66,6 +66,9 @@ public class MISMandate implements Serializable{ final static public String OID_ORGANWALTER = "1.2.40.0.10.3.4"; final static private String TEXT_ORGANWALTER = "Organwalter"; + final static public String OID_ELGA_OMBUTSSTELLE = "1.2.40.0.34.3.1.3"; + final static public String OID_ELGA_OMBUTSSTELLE_TEST = "1.2.40.0.34.3.1.2.99.9"; + final static private String TEXT_ELGA_OMBUTSSTELLE = "ELGA-Ombudsstelle"; private String oid = null; private byte[] mandate = null; @@ -102,7 +105,10 @@ public class MISMandate implements Serializable{ return TEXT_ZIVILTECHNIKER; if (this.oid.equalsIgnoreCase(OID_ORGANWALTER)) return TEXT_ORGANWALTER; - + if (this.oid.equalsIgnoreCase(OID_ELGA_OMBUTSSTELLE) + || this.oid.equalsIgnoreCase(OID_ELGA_OMBUTSSTELLE_TEST)) + return TEXT_ELGA_OMBUTSSTELLE; + return "Keine textuelle Beschreibung für OID " + oid; } else { -- cgit v1.2.3 From 1679466b77e29ff8181b1b01a320c3548e28a349 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 19 Feb 2015 14:46:06 +0100 Subject: fix some possible problems --- .../main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index d4ce8670e..025c4c652 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -147,8 +147,7 @@ public class MOAIDAuthInitializer { .toString() }, ex); } } - - // FIXME[@tlenz]: iaik.prod:iaik_X509TrustManager requires iaik.IAIKRuntimeException which might have been moved to iaik.server.modules (iaik.prod:iaik_moa:1.51)) + // Initializes IAIKX509TrustManager logging /* String log4jConfigURL = System.getProperty("log4j.configuration"); -- cgit v1.2.3 From 45c5e41898ea4660154d730cf863ee2886f71a03 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 19 Feb 2015 15:25:48 +0100 Subject: modify PVP attribute builder for MANDATE_PROF_REP_DESC --- .../MandateProfRepDescAttributeBuilder.java | 45 +++++++++++----------- 1 file changed, 22 insertions(+), 23 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java index 1059e324e..e7ba26158 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java @@ -41,37 +41,36 @@ public class MandateProfRepDescAttributeBuilder implements IPVPAttributeBuilder public ATT build(OAAuthParameter oaParam, IAuthData authData, IAttributeGenerator g) throws AttributeException { - if(authData.isUseMandate()) { - Element mandate = authData.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); - } + if(authData.isUseMandate()) { + String text = null; + + MISMandate misMandate = authData.getMISMandate(); - Mandate mandateObject = MandateBuilder.buildMandate(authData.getMandate()); - if (mandateObject == null) { + if(misMandate == null) { throw new NoMandateDataAttributeException(); } - - String text = null; - if (MiscUtil.isNotEmpty(mandateObject.getAnnotation())) { - text = mandateObject.getAnnotation(); - - } else { - MISMandate misMandate = authData.getMISMandate(); + + text = misMandate.getTextualDescriptionOfOID(); - if(misMandate == null) { + if (MiscUtil.isEmpty(text)) { + Element mandate = authData.getMandate(); + if (mandate == null) { throw new NoMandateDataAttributeException(); } - text = misMandate.getTextualDescriptionOfOID(); - - if(MiscUtil.isEmpty(text)) { - return null; + Mandate mandateObject = MandateBuilder.buildMandate(authData.getMandate()); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + + text = mandateObject.getAnnotation(); - } else - return g.buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, - MANDATE_PROF_REP_DESC_NAME, text); - } + } + + if(MiscUtil.isNotEmpty(text)) + return g.buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, + MANDATE_PROF_REP_DESC_NAME, text); + } return null; -- cgit v1.2.3 From 6032b2a39960a98b7a4026da1bcc7e8454b4cc53 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 20 Feb 2015 08:47:32 +0100 Subject: add names to worker threads --- .../at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java | 2 +- .../java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java index fe35866b1..104cd8622 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java @@ -45,7 +45,7 @@ public class AuthenticationSessionCleaner implements Runnable { public static void start() { // start the session cleanup thread Thread sessionCleaner = - new Thread(new AuthenticationSessionCleaner()); + new Thread(new AuthenticationSessionCleaner(), "AuthenticationSessionCleaner"); sessionCleaner.setName("SessionCleaner"); sessionCleaner.setDaemon(true); sessionCleaner.setPriority(Thread.MIN_PRIORITY); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java index 593b72658..828bf99ca 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java @@ -77,7 +77,7 @@ public class AuthConfigLoader implements Runnable { public static void start() { // start the session cleanup thread - Thread configLoader = new Thread(new AuthConfigLoader()); + Thread configLoader = new Thread(new AuthConfigLoader(), "AuthConfigLoader"); configLoader.setName("ConfigurationLoader"); configLoader.setDaemon(true); configLoader.setPriority(Thread.MIN_PRIORITY); -- cgit v1.2.3 From 1b476c125248f5790a6c09c2b91a25148d6e57b2 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 20 Feb 2015 08:49:37 +0100 Subject: some minor fixes --- .../moa/id/advancedlogging/StatisticLogger.java | 15 ++++++++++++++- .../gv/egovernment/moa/id/auth/AuthenticationServer.java | 11 +++++++++++ .../moa/id/auth/builder/AuthenticationDataBuilder.java | 3 ++- .../egovernment/moa/id/config/auth/OAAuthParameter.java | 1 + .../moa/id/config/auth/data/BPKDecryptionParameters.java | 14 ++++++++++++-- .../SignedDocAttributeRequestProvider.java | 7 ++++++- 6 files changed, 46 insertions(+), 5 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java index b68db92a4..f45a16780 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java @@ -23,6 +23,7 @@ package at.gv.egovernment.moa.id.advancedlogging; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.util.Date; @@ -160,8 +161,9 @@ public class StatisticLogger { dblog.setPv(false); } + InputStream is = null; try { - InputStream is = new ByteArrayInputStream(mandate.getMandate()); + is = new ByteArrayInputStream(mandate.getMandate()); JAXBContext jc = JAXBContext.newInstance(Mandate.class); Unmarshaller u = jc.createUnmarshaller(); @@ -189,6 +191,17 @@ public class StatisticLogger { } catch (JAXBException e) { Logger.warn("Advancted logging can not parse mandate.", e); + + } finally { + if (is!=null) { + try { + is.close(); + + } catch (IOException e) { + Logger.warn("Close InputStream failed." , e); + + } + } } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index b9ce76d0c..fd7c7f237 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -1058,6 +1058,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { ByteArrayInputStream bais = new ByteArrayInputStream(mandate .getMandate()); Document doc = DOMUtils.parseDocumentSimple(bais); + bais.close(); return doc.getDocumentElement(); } @@ -1952,6 +1953,16 @@ public class AuthenticationServer implements MOAIDAuthConstants { } catch (Throwable e) { throw new CertificateException(e); + + } finally { + try { + is.close(); + + } catch (IOException e) { + Logger.warn("Close InputStream failed." , e); + + } + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 5d816be1b..82e079459 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -610,7 +610,8 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { if (extractor.containsAttribute(PVPConstants.EID_IDENTITY_LINK_NAME)) { try { InputStream idlStream = Base64Utils.decodeToStream(extractor.getSingleAttributeValue(PVPConstants.EID_IDENTITY_LINK_NAME), false); - IdentityLink idl = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); + IdentityLink idl = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); + idlStream.close(); buildOAspecificIdentityLink(oaParam, authData, idl); } catch (ParseException e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java index 90b72b72b..933dddb31 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.config.auth; +import java.io.IOException; import java.security.PrivateKey; import java.util.ArrayList; import java.util.HashMap; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/BPKDecryptionParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/BPKDecryptionParameters.java index 787a480f0..b7d5ebed5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/BPKDecryptionParameters.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/BPKDecryptionParameters.java @@ -55,10 +55,12 @@ public class BPKDecryptionParameters implements Serializable{ /** * @return + * @throws IOException */ - public PrivateKey getPrivateKey() { + public PrivateKey getPrivateKey() { + InputStream in = null; try { - InputStream in = new ByteArrayInputStream(keyStore); + in = new ByteArrayInputStream(keyStore); KeyStore store = KeyStoreUtils.loadKeyStore(in , keyStorePassword); char[] chPassword = " ".toCharArray(); @@ -83,6 +85,14 @@ public class BPKDecryptionParameters implements Serializable{ } catch (NoSuchAlgorithmException e) { Logger.error("Can not load private key from keystore.", e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + Logger.warn("Close InputStream failed." , e); + } + } } return null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java index bb3d8b1fd..2c77db94e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java @@ -189,6 +189,7 @@ public class SignedDocAttributeRequestProvider extends AttributeProvider { IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); Logger.info("SignResponse with error (unmodified):"+signResponseString); + istr.close(); } else { @@ -198,6 +199,7 @@ public class SignedDocAttributeRequestProvider extends AttributeProvider { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), baos); byte[] data = baos.toByteArray(); + baos.close(); //update doc in DTL String docId, dssId = ""; @@ -255,7 +257,8 @@ public class SignedDocAttributeRequestProvider extends AttributeProvider { StringWriter writer = new StringWriter(); IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); - Logger.info("SignResponse overwritten:"+signResponseString); + Logger.info("SignResponse overwritten:"+signResponseString); + istr.close(); } else { @@ -304,6 +307,7 @@ public class SignedDocAttributeRequestProvider extends AttributeProvider { IOUtils.copy(istr, writer, "UTF-8"); signResponseString = writer.toString(); Logger.info("SignResponse overwritten:"+signResponseString); + istr.close(); } } else @@ -424,6 +428,7 @@ public class SignedDocAttributeRequestProvider extends AttributeProvider { signRequestString = writer.toString(); Logger.info("Signrequest overwritten"); Logger.debug("Signrequest overwritten:"+signRequestString); + istr.close(); } catch (Exception e) { e.printStackTrace(); throw new Exception("Could not marshall sign request", e); -- cgit v1.2.3 From fd2752d6cb5a95aca7ed2206a9b8258942f17655 Mon Sep 17 00:00:00 2001 From: Thomas Knall Date: Mon, 23 Feb 2015 18:57:12 +0100 Subject: Improve Process Engine signal servlet (MOAID-73) - Update Process Engine signal servlet in order to allow module to provider their own strategy for providing the moa session id. - Update moa id handbook. - Update javadoc. --- .../moa/id/auth/modules/AuthModule.java | 5 ++-- .../modules/registration/ModuleRegistration.java | 2 +- .../auth/servlet/ProcessEngineSignalServlet.java | 27 +++++++++++++++++----- .../springweb/SpringWebExpressionEvaluator.java | 17 +++++++++----- 4 files changed, 36 insertions(+), 15 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java index a31f3ceb0..8983403d8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java @@ -22,8 +22,9 @@ public interface AuthModule { int getPriority(); /** - * Checks if the module has a process, which is able to perform an authentication with the given - * {@link ExecutionContext}. + * Selects a process (description), referenced by its unique id, which is able to perform authentication with the + * given {@link ExecutionContext}. Returns {@code null} if no appropriate process (description) was available within + * this module. * * @param context * an ExecutionContext for a process. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java index fa1878e74..9c950366c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java @@ -128,7 +128,7 @@ public class ModuleRegistration { } /** - * Returns the process id of the first process, in the highest ranked + * Returns the process description id of the first process, in the highest ranked * module, which is able to work with the given execution context. * * @param context diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java index a99b7aeef..d670cbe8a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -9,6 +9,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; @@ -23,7 +24,7 @@ import at.gv.egovernment.moa.id.util.ParamValidatorUtils; public class ProcessEngineSignalServlet extends AuthServlet { private static final long serialVersionUID = 1L; - + /** * Sets response headers that prevent caching (code taken from {@link AuthServlet}). * @@ -51,14 +52,13 @@ public class ProcessEngineSignalServlet extends AuthServlet { */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); + String sessionID = StringEscapeUtils.escapeHtml(getMoaSessionId(req)); setNoCachingHeaders(resp); try { - - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("ProcessEngineSignal", PARAM_SESSIONID, "auth.12"); + + if (sessionID == null) { + throw new IllegalStateException("Unable to determine MOA session id."); } // retrieve moa session @@ -80,4 +80,19 @@ public class ProcessEngineSignalServlet extends AuthServlet { } + /** + * Retrieves the current MOA session id from the HttpServletRequest parameter + * {@link MOAIDAuthConstants#PARAM_SESSIONID}. + *

              + * Note that this class/method can be overwritten by modules providing their own strategy of retrieving the + * respective MOA session id. + * + * @param request + * The unterlying HttpServletRequest. + * @return The current MOA session id. + */ + public String getMoaSessionId(HttpServletRequest request) { + return StringEscapeUtils.escapeHtml(request.getParameter(PARAM_SESSIONID)); + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java index 499e86fa0..af6822ba6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java @@ -124,12 +124,17 @@ public class SpringWebExpressionEvaluator implements ExpressionEvaluator { log.trace("Evaluating '{}'.", expression); Expression expr = parser.parseExpression(expression); - Boolean result = expr.getValue(evaluationContext, new SpringWebExpressionEvaluationContext(expressionContext), - Boolean.class); - if (result == null) { - log.warn("Evaluation of '{}' results in null-value.", expression); - } else { - log.debug("Expression '{}' -> {}", expression, result); + Boolean result = null; + try { + result = expr.getValue(evaluationContext, new SpringWebExpressionEvaluationContext(expressionContext), + Boolean.class); + if (result == null) { + log.warn("Evaluation of '{}' results in null-value.", expression); + } else { + log.debug("Expression '{}' -> {}", expression, result); + } + } catch (Exception e) { + log.warn("Expression '{}' could not be processed.", expression, e); } return BooleanUtils.isTrue(result); -- cgit v1.2.3 From 6b6c98ae7af48c15e86b189e0db9e39bc1d14edb Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Thu, 5 Mar 2015 12:31:17 +0100 Subject: null safe assignment --- .../main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index fd7c7f237..c638c6324 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -29,6 +29,7 @@ import javax.xml.transform.TransformerException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.BooleanUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; @@ -1729,7 +1730,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { boolean globallyMandatory = false; for (StorkAttribute currentGlobalAttribute : storkConfig.getStorkAttributes()) if (current.getName().equals(currentGlobalAttribute.getName())) { - globallyMandatory = currentGlobalAttribute.isMandatory(); + globallyMandatory = BooleanUtils.isTrue(currentGlobalAttribute.isMandatory()); break; } -- cgit v1.2.3 From 12c3c34ea26ff20e39c9b67f698e9c8b99ef11ee Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Fri, 13 Mar 2015 15:38:31 +0100 Subject: STORK PEPS-conform logging --- .../moa/id/auth/AuthenticationServer.java | 24 ++++++++++++++++++++++ .../moa/id/auth/servlet/PEPSConnectorServlet.java | 20 ++++++++++++++++++ 2 files changed, 44 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index fd7c7f237..c4d6859db 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -11,9 +11,11 @@ import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.math.BigInteger; +import java.net.URL; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.cert.CertificateException; +import java.text.SimpleDateFormat; import java.util.ArrayList; //import java.security.cert.CertificateFactory; import java.util.Calendar; @@ -1845,6 +1847,17 @@ public class AuthenticationServer implements MOAIDAuthConstants { //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()); @@ -1877,6 +1890,17 @@ public class AuthenticationServer implements MOAIDAuthConstants { } Logger.info("STORK AuthnRequest successfully successfully prepared for client with target location: " + 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 static String generateDssSignRequest(String text, String mimeType, String citizenCountry) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index 7357818c8..24daa76a3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -28,8 +28,10 @@ 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; @@ -201,6 +203,15 @@ public class PEPSConnectorServlet extends AuthServlet { 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 @@ -554,6 +565,15 @@ public class PEPSConnectorServlet extends AuthServlet { // 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#" + + "#NA#" + 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 response could be not supported yet // try { // -- cgit v1.2.3 From 9ac6c3342ba7afdd75838230d13ceda70614cedc Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Fri, 13 Mar 2015 16:03:33 +0100 Subject: added fakeidl no-signature option config --- .../moa/id/config/auth/AuthConfigurationProvider.java | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index c746c0888..d33a9ea92 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -1042,6 +1042,16 @@ public class AuthConfigurationProvider extends ConfigurationProvider { return null; } + /** + * Gets the countries for which it is configured to require no signature + * + * @return the stork no signature countries + */ + public List getStorkNoSignatureCountries() { + String prop = props.getProperty("stork.fakeIdL.noSignatureCountries", ""); + return Arrays.asList(prop.replaceAll(" ", "").split(",")); + } + public boolean isMonitoringActive() { String prop = props.getProperty("configuration.monitoring.active", "false"); return Boolean.valueOf(prop); -- cgit v1.2.3 From c0613b08431899c6d97affc570a237b81dfcda80 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Fri, 13 Mar 2015 16:04:09 +0100 Subject: fixed date format issue with fakeIdL creation --- .../gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 82e079459..cd751ce7f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -906,7 +906,7 @@ public class AuthenticationDataBuilder implements MOAIDAuthConstants { } } catch (Exception e) { - Logger.error("Failed to extract country code from certificate", e); + Logger.error("Failed to extract country code from certificate with message: " + e.getMessage()); } -- cgit v1.2.3 From 8d60f92b63ae39c6e9d308938004f77c29078215 Mon Sep 17 00:00:00 2001 From: Alexander Marsalek Date: Tue, 17 Mar 2015 08:44:18 +0100 Subject: Added mapping AT => Other Countries, request from Thomas K. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > · „Other Countries“ (dabei handelt es sich um den > Österreichischen Fall, bei dem MOCCA die Signatur mit ausländischen > Karten durchführt) --- .../src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index db8b4dd80..5223a181d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -149,7 +149,9 @@ public interface MOAIDAuthConstants { Collections.unmodifiableMap(new HashMap() { private static final long serialVersionUID = 1L; { + put("AT", "Other Countries");//"Workaround for PEPS Simulator" put("BE", "België/Belgique"); + //put("CH", "Schweiz"); put("EE", "Eesti"); put("ES", "España"); put("FI", "Suomi"); -- cgit v1.2.3 From 5830752a2142b9664bc46196c1a67250cbedf655 Mon Sep 17 00:00:00 2001 From: Bojan Suzic Date: Mon, 23 Mar 2015 17:01:44 +0100 Subject: adjusting strings for match --- .../moa/id/protocols/stork2/MandateRetrievalRequest.java | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java index ed8480ccb..e6fff76ab 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java @@ -273,13 +273,22 @@ public class MandateRetrievalRequest implements IAction { private String mapPowersType(MandateContainer mandateContainer) { + Logger.debug("Analyzing mandate of type: " + mandateContainer.getAnnotation() + "."); // using if for java 6 compatibility if necessary if (mandateContainer.getAnnotation().equals("ELGABilateral")) { return "6"; // Health Powers } else if (mandateContainer.getAnnotation().equals("ERsB")) { return "0"; // General Powers + } else if (mandateContainer.getAnnotation().equals("Gesetzliche Vollmacht auf Basis Ergäzungsregister für sonstige Betroffene")) { + return "0"; // General Powers + } else if (mandateContainer.getAnnotation().equals("Gesetzliche Vollmacht auf Basis Ergänzungsregister für sonstige Betroffene")) { + return "0"; // General Powers + } else if (mandateContainer.getAnnotation().contains("Gesetzliche Vollmacht auf Basis Erg")) { + return "0"; // General Powers } else if (mandateContainer.getAnnotation().equals("GeneralvollmachtBilateral")) { return "0"; // General Powers + } else if (mandateContainer.getAnnotation().contains("Gesetzliche Vollmacht auf Basis Firmenbuch")) { + return "0"; // General Powers } else if (mandateContainer.getAnnotation().equals("ERsBMitPostvollmacht")) { return "0"; // General Powers } else if (mandateContainer.getAnnotation().equals("ZVR")) { @@ -301,6 +310,7 @@ public class MandateRetrievalRequest implements IAction { } else if (mandateContainer.getAnnotation().equals("Ziviltechniker")) { return "0"; // General Powers } + Logger.debug("Returning other type of mandate"); return "9"; } -- cgit v1.2.3 From e98bdf2b39ecb9100e64c8077752ed7c4ed883b3 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Tue, 24 Mar 2015 12:18:49 +0100 Subject: escaped attribute values for saml1 responses --- .../gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java index ea1526ff0..3809ec4bc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java @@ -39,6 +39,7 @@ 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.AuthenticationServer; import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; @@ -286,6 +287,12 @@ public class STORKResponseProcessor { Object attributeValue = attribute.getValue(); if (null == attributeValue) attributeValue = attribute.getComplexValue(); + + // escape attributeValue + attributeValue = StringEscapeUtils.escapeXml10(attributeValue.toString()); + // and remove trailing and tailing brackets. Might break something but we never saw an array with more than one entry! + attributeValue = ((String) attributeValue).substring(1, ((String) attributeValue).length() - 1); + ExtendedSAMLAttribute extendedSAMLAttribute = new ExtendedSAMLAttributeImpl(attribute.getName(), attributeValue, Constants.STORK_NS_URI, 0); moaExtendedSAMLAttributeList.add(extendedSAMLAttribute); -- cgit v1.2.3 From 8400b9d9734f45d53ac722e85e04c599fdccfe0d Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 9 Apr 2015 12:41:11 +0200 Subject: fix wrong PVP attribute friendly names --- .../java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java index 1f3e86ff6..168f2362a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java @@ -237,12 +237,12 @@ public interface PVPConstants { public static final String MANDATE_PROF_REP_OID_OID = "1.2.40.0.10.2.1.1.261.86"; public static final String MANDATE_PROF_REP_OID_NAME = URN_OID_PREFIX + MANDATE_PROF_REP_OID_OID; - public static final String MANDATE_PROF_REP_OID_FRIENDLY_NAME = "MANDATOR-PROF-REP-OID"; + public static final String MANDATE_PROF_REP_OID_FRIENDLY_NAME = "MANDATE-PROF-REP-OID"; public static final int MANDATE_PROF_REP_OID_MAX_LENGTH = 256; public static final String MANDATE_PROF_REP_DESC_OID = "1.2.40.0.10.2.1.1.261.88"; public static final String MANDATE_PROF_REP_DESC_NAME = URN_OID_PREFIX + MANDATE_PROF_REP_DESC_OID; - public static final String MANDATE_PROF_REP_DESC_FRIENDLY_NAME = "MANDATOR-PROF-REP-DESCRIPTION"; + public static final String MANDATE_PROF_REP_DESC_FRIENDLY_NAME = "MANDATE-PROF-REP-DESCRIPTION"; public static final int MANDATE_PROF_REP_DESC_MAX_LENGTH = 1024; public static final String MANDATE_REFERENCE_VALUE_OID = "1.2.40.0.10.2.1.1.261.90"; -- cgit v1.2.3 From a6189a32a78d2b3ed096356f6b7e0049c8870b21 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 14 Apr 2015 16:59:25 +0200 Subject: update error handling in PVP metadata verification filter implemetations --- .../filter/SchemaValidationException.java | 43 ++++++++++++++++ .../filter/SignatureValidationException.java | 58 ++++++++++++++++++++++ .../pvp2x/metadata/MOAMetadataProvider.java | 14 +++++- .../metadata/MetadataSignatureFilter.java | 5 +- .../metadata/SchemaValidationFilter.java | 7 ++- 5 files changed, 119 insertions(+), 8 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SchemaValidationException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SignatureValidationException.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SchemaValidationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SchemaValidationException.java new file mode 100644 index 000000000..8da5edeed --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SchemaValidationException.java @@ -0,0 +1,43 @@ +/* + * 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.protocols.pvp2x.exceptions.filter; + +import org.opensaml.saml2.metadata.provider.FilterException; + +/** + * @author tlenz + * + */ +public class SchemaValidationException extends FilterException { + + /** + * @param string + */ + public SchemaValidationException(String string) { + super(string); + + } + + private static final long serialVersionUID = 1L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SignatureValidationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SignatureValidationException.java new file mode 100644 index 000000000..86a6a777b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SignatureValidationException.java @@ -0,0 +1,58 @@ +/* + * 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.protocols.pvp2x.exceptions.filter; + +import org.opensaml.saml2.metadata.provider.FilterException; + +/** + * @author tlenz + * + */ +public class SignatureValidationException extends FilterException { + + /** + * @param string + */ + public SignatureValidationException(String string) { + super(string); + + } + + /** + * @param e + */ + public SignatureValidationException(Exception e) { + super(e); + } + + /** + * @param string + * @param object + */ + public SignatureValidationException(String string, Exception e) { + super(string, e); + } + + private static final long serialVersionUID = 1L; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java index 12afa14bc..d493ef9e0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java @@ -55,6 +55,8 @@ import at.gv.egovernment.moa.id.commons.ex.MOAHttpProtocolSocketFactoryException import at.gv.egovernment.moa.id.commons.utils.MOAHttpProtocolSocketFactory; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SchemaValidationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SignatureValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.InterfederatedIDPPublicServiceFilter; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.MetadataFilterChain; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.SchemaValidationFilter; @@ -380,10 +382,18 @@ public class MOAMetadataProvider implements MetadataProvider { return httpProvider; - } catch (Throwable e) { + } catch (Throwable e) { if (e.getCause() != null && e.getCause().getCause() instanceof SSLHandshakeException) { Logger.warn("SSL-Server certificate for metadata " - + metadataURL + " not trusted.", e); + + metadataURL + " not trusted.", e); + + } if (e.getCause() != null && e.getCause().getCause() instanceof SignatureValidationException) { + Logger.warn("Signature verification for metadata" + + metadataURL + " FAILED.", e); + + } if (e.getCause() != null && e.getCause().getCause() instanceof SchemaValidationException) { + Logger.warn("Schema validation for metadata " + + metadataURL + " FAILED.", e); } Logger.error( diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataSignatureFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataSignatureFilter.java index 0405fa114..6dac4bba1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataSignatureFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataSignatureFilter.java @@ -39,6 +39,7 @@ import org.opensaml.xml.security.x509.BasicX509Credential; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoCredentialsException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SignatureValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.EntityVerifier; import at.gv.egovernment.moa.logging.Logger; @@ -126,7 +127,7 @@ public class MetadataSignatureFilter implements MetadataFilter { desc.getEntityDescriptors().addAll(verifiedEntIT); } - public void doFilter(XMLObject metadata) throws FilterException { + public void doFilter(XMLObject metadata) throws SignatureValidationException { try { if (metadata instanceof EntitiesDescriptor) { EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) metadata; @@ -155,7 +156,7 @@ public class MetadataSignatureFilter implements MetadataFilter { Logger.info("Metadata signature policy check done OK"); } catch (MOAIDException e) { Logger.warn("Metadata signature policy check FAILED.", e); - throw new FilterException(e); + throw new SignatureValidationException(e); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java index 382adb108..f73b541bf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java @@ -22,8 +22,6 @@ */ package at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata; -import java.io.IOException; - import org.opensaml.saml2.metadata.provider.FilterException; import org.opensaml.saml2.metadata.provider.MetadataFilter; import org.opensaml.xml.XMLObject; @@ -38,6 +36,7 @@ import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SchemaValidationException; import at.gv.egovernment.moa.logging.Logger; /** @@ -69,7 +68,7 @@ public class SchemaValidationFilter implements MetadataFilter { * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) */ @Override - public void doFilter(XMLObject arg0) throws FilterException { + public void doFilter(XMLObject arg0) throws SchemaValidationException { String errString = null; @@ -100,7 +99,7 @@ public class SchemaValidationFilter implements MetadataFilter { } - throw new FilterException("Metadata Schema validation FAILED with message: "+ errString); + throw new SchemaValidationException("Metadata Schema validation FAILED with message: "+ errString); } else Logger.info("Metadata Schema validation check is DEACTIVATED!"); -- cgit v1.2.3 From e449a5704e520ca00cbb0451e78f69c5bbd0144c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 20 Apr 2015 13:45:24 +0200 Subject: first fix to solve problems with errorhandling and process managment --- .../id/auth/modules/TaskExecutionException.java | 57 ++++++++++++++++++++++ .../internal/tasks/CertificateReadRequestTask.java | 18 ++++--- .../internal/tasks/CreateIdentityLinkFormTask.java | 15 +++--- .../modules/internal/tasks/GetForeignIDTask.java | 11 +++-- .../internal/tasks/GetMISSessionIDTask.java | 14 +++--- .../tasks/PrepareAuthBlockSignatureTask.java | 6 ++- .../tasks/VerifyAuthenticationBlockTask.java | 20 +++++--- .../internal/tasks/VerifyCertificateTask.java | 21 ++++---- .../internal/tasks/VerifyIdentityLinkTask.java | 14 +++--- .../moa/id/auth/servlet/AuthServlet.java | 45 ++++++++++------- .../auth/servlet/ProcessEngineSignalServlet.java | 7 ++- .../moa/id/process/ProcessEngineImpl.java | 1 + .../at/gv/egovernment/moa/id/process/api/Task.java | 4 +- .../moa/id/process/springweb/MoaIdTask.java | 5 +- 14 files changed, 162 insertions(+), 76 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java new file mode 100644 index 000000000..3e9f4cf14 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java @@ -0,0 +1,57 @@ +/* + * 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.modules; + +import at.gv.egovernment.moa.id.process.ProcessExecutionException; + +/** + * @author tlenz + * + */ +public class TaskExecutionException extends ProcessExecutionException { + + private static final long serialVersionUID = 1L; + Throwable originalException = null; + + /** + * @param message + * @param cause + */ + public TaskExecutionException(String message, Throwable cause) { + super(message, cause); + originalException = cause; + + } + + /** + * Get the original internal exception from task + * + * @return the originalException + */ + public Throwable getOriginalException() { + return originalException; + } + + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java index bc73a9f2f..ed3089a41 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java @@ -2,6 +2,8 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import java.io.IOException; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -16,6 +18,7 @@ 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.ConfigurationDBUtils; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; @@ -47,15 +50,12 @@ public class CertificateReadRequestTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { + throws TaskExecutionException { // TODO[branch]: Foreign citizen or mandate mode; respond with IRR for certificates, dataURL = "/VerifyCertificate" Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); - setNoCachingHeaders(resp); - - String pendingRequestID = null; - + setNoCachingHeaders(resp); try { String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); @@ -65,8 +65,6 @@ public class CertificateReadRequestTask extends AbstractAuthServletTask { throw new WrongParametersException("CertificateReadRequestTask", PARAM_SESSIONID, "auth.12"); } - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - AuthenticationSession session = AuthenticationServer.getSession(sessionID); boolean useMandate = session.getUseMandate(); @@ -91,7 +89,11 @@ public class CertificateReadRequestTask extends AbstractAuthServletTask { AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); + + } catch (IOException e) { + throw new TaskExecutionException(e.getMessage(), e); + } finally { ConfigurationDBUtils.closeSession(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java index 4cd1ea94e..ee6f0d5a4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java @@ -15,6 +15,7 @@ import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; 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.auth.servlet.GenerateIFrameTemplateServlet; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; @@ -60,9 +61,8 @@ public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { + throws TaskExecutionException { - String pendingRequestID = null; String moasessionid = StringEscapeUtils.escapeHtml(ObjectUtils.defaultIfNull(req.getParameter(PARAM_SESSIONID), (String) executionContext.get(PARAM_SESSIONID))); AuthenticationSession moasession = null; try { @@ -72,9 +72,7 @@ public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { throw new MOAIDException("auth.18", new Object[] {}); } - try { - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); + try { moasession = AuthenticationSessionStoreage.getSession(moasessionid); AuthenticationSessionStoreage.changeSessionID(moasession); executionContext.remove(PARAM_SESSIONID); @@ -100,14 +98,17 @@ public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { } } catch (WrongParametersException ex) { - handleWrongParameters(ex, req, resp); +// handleWrongParameters(ex, req, resp); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); +// handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (Exception e) { Logger.error("CreateIdentityLinkFormTask has an interal Error.", e); + throw new TaskExecutionException(e.getMessage(), e); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java index 4771628a3..6bf68e2eb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java @@ -24,6 +24,7 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; import at.gv.egovernment.moa.id.client.SZRGWClientException; @@ -66,7 +67,7 @@ public class GetForeignIDTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { + throws TaskExecutionException { Logger.debug("POST GetForeignIDServlet"); @@ -76,9 +77,10 @@ public class GetForeignIDTask extends AbstractAuthServletTask { try { parameters = getParameters(req); - } catch (FileUploadException e) { + + } catch (FileUploadException | IOException e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); + throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); } String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); @@ -170,10 +172,11 @@ public class GetForeignIDTask extends AbstractAuthServletTask { } } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (Exception e) { Logger.error("GetForeignIDServlet has an interal Error.", e); + throw new TaskExecutionException(e.getMessage(), e); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java index f08f96782..4ff5672bd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java @@ -21,6 +21,7 @@ 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.ConfigurationDBUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; @@ -62,7 +63,7 @@ public class GetMISSessionIDTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { + throws TaskExecutionException { Logger.debug("POST GetMISSessionIDServlet"); @@ -154,22 +155,23 @@ public class GetMISSessionIDTask extends AbstractAuthServletTask { Logger.debug("REDIRECT TO: " + redirectURL); } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (GeneralSecurityException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (PKIException e) { - handleError(null, e, req, resp, pendingRequestID); + throw new TaskExecutionException(e.getMessage(), e); } catch (SAXException e) { - handleError(null, e, req, resp, pendingRequestID); + throw new TaskExecutionException(e.getMessage(), e); } catch (ParserConfigurationException e) { - handleError(null, e, req, resp, pendingRequestID); + throw new TaskExecutionException(e.getMessage(), e); } catch (Exception e) { Logger.error("MISMandateValidation has an interal Error.", e); + throw new TaskExecutionException(e.getMessage(), e); } finally { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java index dcea3a1dd..3ae35bc24 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java @@ -12,6 +12,7 @@ import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; 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.ConfigurationDBUtils; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; @@ -45,7 +46,7 @@ public class PrepareAuthBlockSignatureTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { + throws TaskExecutionException { // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet Logger.debug("Process IdentityLink"); @@ -88,10 +89,11 @@ public class PrepareAuthBlockSignatureTask extends AbstractAuthServletTask { "VerifyIdentityLink"); } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (Exception e) { Logger.error("IdentityLinkValidation has an interal Error.", e); + throw new TaskExecutionException(e.getMessage(), e); } finally { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java index 1e1a4df89..64dcb0f41 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java @@ -25,6 +25,7 @@ import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; 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.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConnectionParameter; @@ -77,7 +78,7 @@ public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { + throws TaskExecutionException { // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet @@ -89,12 +90,13 @@ public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { try { parameters = getParameters(req); - } catch (FileUploadException e) + + } catch (FileUploadException | IOException e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - + throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); } + String sessionID = req.getParameter(PARAM_SESSIONID); String createXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); @@ -219,19 +221,21 @@ public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (GeneralSecurityException e) { - handleError(null, e, req, resp, pendingRequestID); + throw new TaskExecutionException(e.getMessage(), e); } catch (PKIException e) { - handleError(null, e, req, resp, pendingRequestID); + throw new TaskExecutionException(e.getMessage(), e); } catch (TransformerException e) { - handleError(null, e, req, resp, pendingRequestID); + throw new TaskExecutionException(e.getMessage(), e); } catch (Exception e) { Logger.error("AuthBlockValidation has an interal Error.", e); + throw new TaskExecutionException(e.getMessage(), e); + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java index 32ea7fe3a..607641532 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java @@ -19,6 +19,7 @@ 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.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; @@ -57,30 +58,26 @@ public class VerifyCertificateTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { + throws TaskExecutionException { // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet Logger.debug("POST VerifyCertificateServlet"); - - String pendingRequestID = null; - + Map parameters; try { parameters = getParameters(req); - } catch (FileUploadException e) + } catch (FileUploadException | IOException e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - } + throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); + } String sessionID = req.getParameter(PARAM_SESSIONID); // escape parameter strings sessionID = StringEscapeUtils.escapeHtml(sessionID); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - + AuthenticationSession session = null; try { // check parameter @@ -148,10 +145,12 @@ public class VerifyCertificateTask extends AbstractAuthServletTask { } } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (Exception e) { Logger.error("CertificateValidation has an interal Error.", e); + throw new TaskExecutionException(e.getMessage(), e); + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java index bf10b3681..44557453a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java @@ -16,6 +16,7 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; @@ -50,7 +51,7 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws Exception { + throws TaskExecutionException { // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet @@ -59,13 +60,12 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { setNoCachingHeaders(resp); Map parameters; - String pendingRequestID = null; try { parameters = getParameters(req); } catch (Exception e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); + throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); } try { @@ -75,8 +75,6 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { if (!ParamValidatorUtils.isValidSessionID(sessionID)) { throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); } - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - AuthenticationSession session = AuthenticationServer.getSession(sessionID); boolean identityLinkAvailable = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters) != null; @@ -85,13 +83,15 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { executionContext.put("identityLinkAvailable", identityLinkAvailable); } catch (ParseException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); + throw new TaskExecutionException(ex.getMessage(), ex); } catch (Exception e) { Logger.error("IdentityLinkValidation has an interal Error.", e); + throw new TaskExecutionException(e.getMessage(), e); + } finally { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java index 331a7653a..c4c4b2691 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java @@ -77,9 +77,11 @@ import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; 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.TaskExecutionException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; import at.gv.egovernment.moa.id.process.ProcessEngine; +import at.gv.egovernment.moa.id.process.ProcessExecutionException; import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; import at.gv.egovernment.moa.id.storage.IExceptionStore; import at.gv.egovernment.moa.id.util.ServletUtils; @@ -185,29 +187,36 @@ public class AuthServlet extends HttpServlet implements MOAIDAuthConstants { protected void handleError(String errorMessage, Throwable exceptionThrown, HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); + Throwable loggedException = null; + + if (exceptionThrown != null + && exceptionThrown instanceof ProcessExecutionException) { + ProcessExecutionException procExc = + (ProcessExecutionException) exceptionThrown; + if (procExc.getCause() != null && + procExc.getCause() instanceof TaskExecutionException) { + TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); + loggedException = taskExc.getOriginalException(); + if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { + Logger.error(exceptionThrown.getMessage(), exceptionThrown); + + } else + Logger.error(exceptionThrown.getMessage()); + + } } + + if (loggedException == null) + loggedException = exceptionThrown; + - if (!(exceptionThrown instanceof MOAIDException)) { - Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown); + if (!(loggedException instanceof MOAIDException)) { + Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); } IExceptionStore store = DBExceptionStoreImpl.getStore(); - String id = store.storeException(exceptionThrown); + String id = store.storeException(loggedException); if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { @@ -228,7 +237,7 @@ public class AuthServlet extends HttpServlet implements MOAIDAuthConstants { } else { //Exception can not be stored in database - handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); + handleErrorNoRedirect(errorMessage, loggedException, req, resp); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java index d670cbe8a..43b6c03d4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -13,6 +13,7 @@ import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; /** @@ -54,7 +55,8 @@ public class ProcessEngineSignalServlet extends AuthServlet { protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String sessionID = StringEscapeUtils.escapeHtml(getMoaSessionId(req)); - setNoCachingHeaders(resp); + setNoCachingHeaders(resp); + String pendingRequestID = null; try { if (sessionID == null) { @@ -62,6 +64,7 @@ public class ProcessEngineSignalServlet extends AuthServlet { } // retrieve moa session + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); AuthenticationSession session = AuthenticationServer.getSession(sessionID); // process instance is mandatory @@ -73,7 +76,7 @@ public class ProcessEngineSignalServlet extends AuthServlet { getProcessEngine().signal(session.getProcessInstanceId()); } catch (Exception ex) { - handleError(null, ex, req, resp, null); + handleError(null, ex, req, resp, pendingRequestID); } finally { MOASessionDBUtils.closeSession(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java index 0ffa22ec3..096e5ee9e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java @@ -13,6 +13,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; +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.process.api.ExecutionContext; import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java index 6401b1d5d..343b8fe0c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java @@ -1,5 +1,7 @@ package at.gv.egovernment.moa.id.process.api; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; + /** * Represents a single task to be performed upon process execution. @@ -16,6 +18,6 @@ public interface Task { * Provides execution related information. * @throws Exception An exception upon task execution. */ - void execute(ExecutionContext executionContext) throws Exception; + void execute(ExecutionContext executionContext) throws TaskExecutionException; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java index bae6391ec..fb75fc8d7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java @@ -8,6 +8,7 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.filter.RequestContextFilter; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.process.api.Task; @@ -52,10 +53,10 @@ public abstract class MoaIdTask implements Task { * Thrown in case of error executing the task. */ public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws Exception; + HttpServletResponse response) throws TaskExecutionException; @Override - public void execute(ExecutionContext executionContext) throws Exception { + public void execute(ExecutionContext executionContext) throws TaskExecutionException { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); -- cgit v1.2.3 From ae570bf65585de05db08dd50d87352fc2027c624 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Tue, 5 May 2015 12:58:29 +0200 Subject: fixed attribute forwarding when using STORK2 SAML for SP --- .../moa/id/protocols/stork2/MOAAttributeProvider.java | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java index 3ab4ec4a1..d3a5a1085 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java @@ -99,6 +99,16 @@ public class MOAAttributeProvider { Logger.error("Could not found MOA extraction method while getting attribute: " + storkAttribute); e.printStackTrace(); } + } else if (authData.getStorkAttributes().containsKey(requestedAttribute.getName())) { + Logger.debug("Trying to get value for attribute directly from STORK2 response [" + storkAttribute + "]"); + try { + PersonalAttribute tmp = authData.getStorkAttributes().get(requestedAttribute.getName()); + attributeList.add((PersonalAttribute) tmp.clone()); + } catch(Exception e) { + Logger.error("Could not retrieve attribute from STORK2 response: " + storkAttribute); + if(Logger.isDebugEnabled()) + e.printStackTrace(); + } } else { Logger.debug("MOA method for extraction of attribute " + storkAttribute + " not defined."); } -- cgit v1.2.3 From 4df561f9f19966c92cd658efa0cd3942a0a091d4 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Tue, 5 May 2015 16:10:56 +0200 Subject: moved consent request before attributes are being collected --- .../id/protocols/stork2/AttributeCollector.java | 12 ++----- .../id/protocols/stork2/AuthenticationRequest.java | 7 +++- .../moa/id/protocols/stork2/ConsentEvaluator.java | 42 ++++++++++++++-------- 3 files changed, 37 insertions(+), 24 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java index 1e6cf6910..704f8b8a9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java @@ -26,12 +26,8 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -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.commons.db.dao.config.AttributeProviderPlugin; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAStorkAttribute; -import at.gv.egovernment.moa.id.commons.db.dao.config.StorkAttribute; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; @@ -186,7 +182,8 @@ public class AttributeCollector implements IAction { List missingAttributes = new ArrayList(); for (PersonalAttribute current : requestAttributeList) if (!responseAttributeList.containsKey(current.getName())) - missingAttributes.add(current); + if(null == current.getStatus() || (null != current.getStatus() && !current.getStatus().equals(AttributeStatusType.WITHHELD.value()))) + missingAttributes.add(current); Logger.info("collecting attributes..."); Logger.debug("found " + missingAttributes.size() + " missing attributes"); @@ -253,10 +250,7 @@ public class AttributeCollector implements IAction { Logger.info("collecting attributes done"); // ask for consent if necessary - if(oaParam.isRequireConsentForStorkAttributes()) - new ConsentEvaluator().requestConsent(container, response, oaParam); - else - new ConsentEvaluator().generateSTORKResponse(response, container); + new ConsentEvaluator().generateSTORKResponse(response, container); return null; // AssertionId // TODO diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java index 859f4900b..e0c4b3d16 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java @@ -163,7 +163,12 @@ public class AuthenticationRequest implements IAction { Logger.debug("Data container prepared"); - return (new AttributeCollector()).processRequest(container, httpReq, httpResp, authData, oaParam); + if(oaParam.isRequireConsentForStorkAttributes()) + new ConsentEvaluator().requestConsent(container, httpReq, httpResp, authData, oaParam); + else + new AttributeCollector().processRequest(container, httpReq, httpResp, authData, oaParam); + + return null; } // // check if we are getting request for citizen of some other country // else if (req instanceof MOASTORKRequest) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java index 2c5728798..51e731e8a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java @@ -23,13 +23,17 @@ package at.gv.egovernment.moa.id.protocols.stork2; import java.io.StringWriter; + +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; + import java.util.ArrayList; import java.util.HashMap; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import java.util.Map.Entry; + import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IAction; @@ -39,14 +43,13 @@ import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import eu.stork.peps.auth.commons.PEPSUtil; import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.STORKAuthnResponse; import eu.stork.peps.auth.engine.STORKSAMLEngine; import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.AttributeStatusType; import eu.stork.peps.exceptions.STORKSAMLEngineException; + import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; -import org.joda.time.DateTime; import org.opensaml.common.impl.SecureRandomIdentifierGenerator; import javax.servlet.http.HttpServletRequest; @@ -72,23 +75,28 @@ public class ConsentEvaluator implements IAction { DataContainer container; try { container = AssertionStorage.getInstance().get(artifactId, DataContainer.class); + req = container.getRequest(); } catch (MOADatabaseException e) { Logger.error("Error fetching incomplete Stork response from temporary storage. Most likely a timeout occured.", e); throw new MOAIDException("stork.17", null); } // evaluate response - for(PersonalAttribute current : container.getResponse().getPersonalAttributeList()) { + for(PersonalAttribute current : container.getRequest().getPersonalAttributeList()) { if(null == httpReq.getParameter(current.getName())) { - current.setStatus(AttributeStatusType.NOT_AVAILABLE.value()); + current.setStatus(AttributeStatusType.WITHHELD.value()); current.setValue(new ArrayList()); current.setComplexValue(new HashMap()); } } - // build and send response - generateSTORKResponse(httpResp, container); - + //TODO: CHECK: req.getOAURL() should return the unique OA identifier + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(req.getOAURL()); + if (oaParam == null) + throw new AuthenticationException("stork.12", new Object[]{req.getOAURL()}); + + new AttributeCollector().processRequest(container, httpReq, httpResp, authData, oaParam); + return null; // AssertionId } @@ -96,12 +104,19 @@ public class ConsentEvaluator implements IAction { * Fills the given HttpResponse with the required web page. * * @param container the container + * @param authData * @param response the response * @param oaParam the oa param * @return the string * @throws MOAIDException the mOAID exception */ - public String requestConsent(DataContainer container, HttpServletResponse response, IOAAuthParameters oaParam) throws MOAIDException { + public String requestConsent(DataContainer container, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData, OAAuthParameter oaParam) throws MOAIDException { + //check if we need to collect consent + if(!oaParam.isRequireConsentForStorkAttributes()) { + (new AttributeCollector()).processRequest(container, httpReq, httpResp, authData, oaParam); + return ""; + } + // prepare redirect String newArtifactId; try { @@ -130,13 +145,12 @@ public class ConsentEvaluator implements IAction { Template template = velocityEngine.getTemplate("/resources/templates/stork2_consent.html"); VelocityContext context = new VelocityContext(); - context.put("action", AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/stork2/CompleteAuthentication?" + ARTIFACT_ID + "=" + newArtifactId); + context.put("action", AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/stork2/GetConsent?" + ARTIFACT_ID + "=" + newArtifactId); // assemble table String table = ""; - for (PersonalAttribute current : container.getResponse().getPersonalAttributeList()) - if ("Available".equals(current.getStatus())) - table += "" + current.getName() + "\n"; + for (PersonalAttribute current : container.getRequest().getPersonalAttributeList()) + table += "" + current.getName() + "\n"; context.put("tablecontent", table); -- cgit v1.2.3 From d086e2f7c278b0b5034d058fe8deff34927bf811 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Tue, 5 May 2015 16:12:06 +0200 Subject: consent request cosmetics --- .../at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java index 51e731e8a..865cec5a3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java @@ -153,6 +153,8 @@ public class ConsentEvaluator implements IAction { table += "" + current.getName() + "\n"; context.put("tablecontent", table); + for(Entry current : oaParam.getFormCustomizaten().entrySet()) + context.put(current.getKey().replace("#", ""), current.getValue()); StringWriter writer = new StringWriter(); template.merge(context, writer); -- cgit v1.2.3 From b4e8abf78acf92e6a40606ddd02d381e73a0d487 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Tue, 5 May 2015 16:34:30 +0200 Subject: added required status to consent list --- .../at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java index 865cec5a3..baa2f1b40 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java @@ -150,7 +150,7 @@ public class ConsentEvaluator implements IAction { // assemble table String table = ""; for (PersonalAttribute current : container.getRequest().getPersonalAttributeList()) - table += "" + current.getName() + "\n"; + table += "" + current.getName() + (current.isRequired() ? "" : " (optional)") + "\n"; context.put("tablecontent", table); for(Entry current : oaParam.getFormCustomizaten().entrySet()) -- cgit v1.2.3 From b110b9d1acd557e103ea4afc88499f2271d4c855 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Tue, 5 May 2015 16:35:38 +0200 Subject: fix: gather any attribute from STORK2 response first if available --- .../id/protocols/stork2/MOAAttributeProvider.java | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java index d3a5a1085..3b2fae0d5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java @@ -79,7 +79,17 @@ public class MOAAttributeProvider { public void populateAttribute(PersonalAttributeList attributeList, PersonalAttribute requestedAttribute ) { String storkAttribute = requestedAttribute.getName(); - if (storkAttributeSimpleMapping.containsKey(storkAttribute)) { + if (authData.getStorkAttributes().containsKey(requestedAttribute.getName())) { + Logger.debug("Trying to get value for attribute directly from STORK2 response [" + storkAttribute + "]"); + try { + PersonalAttribute tmp = authData.getStorkAttributes().get(requestedAttribute.getName()); + attributeList.add((PersonalAttribute) tmp.clone()); + } catch(Exception e) { + Logger.error("Could not retrieve attribute from STORK2 response: " + storkAttribute); + if(Logger.isDebugEnabled()) + e.printStackTrace(); + } + } else if (storkAttributeSimpleMapping.containsKey(storkAttribute)) { Logger.debug("Trying to get value for attribute using simple mapping [" + storkAttribute + "]"); try { Method method = authData.getClass().getDeclaredMethod(storkAttributeSimpleMapping.get(storkAttribute)); @@ -99,16 +109,6 @@ public class MOAAttributeProvider { Logger.error("Could not found MOA extraction method while getting attribute: " + storkAttribute); e.printStackTrace(); } - } else if (authData.getStorkAttributes().containsKey(requestedAttribute.getName())) { - Logger.debug("Trying to get value for attribute directly from STORK2 response [" + storkAttribute + "]"); - try { - PersonalAttribute tmp = authData.getStorkAttributes().get(requestedAttribute.getName()); - attributeList.add((PersonalAttribute) tmp.clone()); - } catch(Exception e) { - Logger.error("Could not retrieve attribute from STORK2 response: " + storkAttribute); - if(Logger.isDebugEnabled()) - e.printStackTrace(); - } } else { Logger.debug("MOA method for extraction of attribute " + storkAttribute + " not defined."); } -- cgit v1.2.3 From 637e57f15061232351b30a53a50825de51522142 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Wed, 6 May 2015 09:15:39 +0200 Subject: fixed nullpointerex during attribute extraction --- .../gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java | 4 ++-- .../gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java index e0c4b3d16..01f84125f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java @@ -499,11 +499,11 @@ public class AuthenticationRequest implements IAction { Logger.debug("Personal attribute found in request: " + personalAttribute.getName() + " isRequired: " + personalAttribute.isRequired()); moaAttributeProvider.populateAttribute(attributeList, personalAttribute); } catch (Exception e) { - Logger.error("Exception, attributes: " + e.getMessage()); + Logger.error("Exception, attributes: " + e.getMessage(), e); } } } catch (Exception e) { - Logger.error("Exception, attributes: " + e.getMessage()); + Logger.error("Exception, attributes: " + e.getMessage(), e); } Logger.trace("AUTHBLOCK " + authData.getAuthBlock()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java index 3b2fae0d5..9a6206947 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java @@ -79,7 +79,7 @@ public class MOAAttributeProvider { public void populateAttribute(PersonalAttributeList attributeList, PersonalAttribute requestedAttribute ) { String storkAttribute = requestedAttribute.getName(); - if (authData.getStorkAttributes().containsKey(requestedAttribute.getName())) { + if (null != authData && null != authData.getStorkAttributes() && authData.getStorkAttributes().containsKey(requestedAttribute.getName())) { Logger.debug("Trying to get value for attribute directly from STORK2 response [" + storkAttribute + "]"); try { PersonalAttribute tmp = authData.getStorkAttributes().get(requestedAttribute.getName()); -- cgit v1.2.3 From e694549a0e77265f77651b68c7b6adfa6d8f1c30 Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Wed, 6 May 2015 09:16:41 +0200 Subject: fixed compilation issues --- .../at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java | 2 +- .../gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java index baa2f1b40..3acd1039f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java @@ -158,7 +158,7 @@ public class ConsentEvaluator implements IAction { StringWriter writer = new StringWriter(); template.merge(context, writer); - response.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8")); + httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8")); } catch (Exception e) { Logger.error("Velocity error: " + e.getMessage()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java index ed8480ccb..b24c0df4f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java @@ -211,7 +211,7 @@ public class MandateRetrievalRequest implements IAction { // ask for consent if necessary if (oaParam.isRequireConsentForStorkAttributes()) - new ConsentEvaluator().requestConsent(container, httpResp, oaParam); + new ConsentEvaluator().requestConsent(container, httpReq, httpResp, authData, oaParam); else new ConsentEvaluator().generateSTORKResponse(httpResp, container); -- cgit v1.2.3 From c621447906a77c5d457ce2ee854c08586509626a Mon Sep 17 00:00:00 2001 From: Florian Reimair Date: Wed, 6 May 2015 09:28:20 +0200 Subject: remove unselected attributes from result set --- .../moa/id/protocols/stork2/AttributeCollector.java | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java index 704f8b8a9..371cfb1d7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java @@ -180,10 +180,21 @@ public class AttributeCollector implements IAction { IPersonalAttributeList requestAttributeList = container.getRequest().getPersonalAttributeList(); IPersonalAttributeList responseAttributeList = container.getResponse().getPersonalAttributeList(); List missingAttributes = new ArrayList(); + Logger.debug("aquire list of missing attributes"); for (PersonalAttribute current : requestAttributeList) - if (!responseAttributeList.containsKey(current.getName())) - if(null == current.getStatus() || (null != current.getStatus() && !current.getStatus().equals(AttributeStatusType.WITHHELD.value()))) + if (!responseAttributeList.containsKey(current.getName())) { + if(null == current.getStatus() || (null != current.getStatus() && !current.getStatus().equals(AttributeStatusType.WITHHELD.value()))) { + // add the ones we need missingAttributes.add(current); + Logger.debug("add " + current.getName() + " to the list of missing attributes"); + } + } else { + // remove the ones we do not want to share from the response list + if(null != current.getStatus() && current.getStatus().equals(AttributeStatusType.WITHHELD.value())) { + responseAttributeList.remove(current.getName()); + Logger.debug("remove " + current.getName() + " from the list of resulting attributes because the user does not want to disclose the data"); + } + } Logger.info("collecting attributes..."); Logger.debug("found " + missingAttributes.size() + " missing attributes"); -- cgit v1.2.3 From 6207deba1c063a20f2ce92f1f09e1d27b3783cec Mon Sep 17 00:00:00 2001 From: Bojan Suzic Date: Tue, 12 May 2015 17:42:09 +0200 Subject: adding attributes, improving moa stork attribute provider --- .../id/protocols/stork2/MOAAttributeProvider.java | 94 ++++++++++++++++------ 1 file changed, 69 insertions(+), 25 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java index 9a6206947..2c7e5b539 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java @@ -26,21 +26,20 @@ import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.data.AuthenticationRole; import at.gv.egovernment.moa.id.data.IAuthData; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import eu.stork.peps.auth.commons.PersonalAttribute; import eu.stork.peps.auth.commons.PersonalAttributeList; import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.AttributeStatusType; +import org.joda.time.Period; + import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; /** * @author bsuzic @@ -55,6 +54,8 @@ public class MOAAttributeProvider { private static final Map storkAttributeFunctionMapping; private final MOASTORKRequest moastorkRequest; + // mappings for attribute population methods + // based on mapping of moa authndata and executing functions to extract attributes static { Map tempSimpleMap = new HashMap(); tempSimpleMap.put("givenName", "getGivenName"); @@ -67,6 +68,9 @@ public class MOAAttributeProvider { tempFunctionMap.put("ECApplicationRole","getECApplicationRole"); tempFunctionMap.put("dateOfBirth", "getFormatedDateOfBirth"); tempFunctionMap.put("MSOrganization", "getMSOrganization"); + tempFunctionMap.put("age", "getAge"); + tempFunctionMap.put("isAgeOver", "getIsAgeOver"); + tempFunctionMap.put("citizenQAALevel", "getQAALevel"); storkAttributeFunctionMapping = Collections.unmodifiableMap(tempFunctionMap); } @@ -79,6 +83,8 @@ public class MOAAttributeProvider { public void populateAttribute(PersonalAttributeList attributeList, PersonalAttribute requestedAttribute ) { String storkAttribute = requestedAttribute.getName(); + + // TODO: check if authData gets populated with stork attributtes during previous steps; it seems it is not if (null != authData && null != authData.getStorkAttributes() && authData.getStorkAttributes().containsKey(requestedAttribute.getName())) { Logger.debug("Trying to get value for attribute directly from STORK2 response [" + storkAttribute + "]"); try { @@ -86,46 +92,78 @@ public class MOAAttributeProvider { attributeList.add((PersonalAttribute) tmp.clone()); } catch(Exception e) { Logger.error("Could not retrieve attribute from STORK2 response: " + storkAttribute); - if(Logger.isDebugEnabled()) - e.printStackTrace(); + Logger.debug(e); } } else if (storkAttributeSimpleMapping.containsKey(storkAttribute)) { Logger.debug("Trying to get value for attribute using simple mapping [" + storkAttribute + "]"); try { Method method = authData.getClass().getDeclaredMethod(storkAttributeSimpleMapping.get(storkAttribute)); - populateAttributeWithMethod(method, authData, attributeList, storkAttribute, requestedAttribute.isRequired()); + populateAttributeWithMethod(method, authData, attributeList, storkAttribute, requestedAttribute); } catch (NoSuchMethodException e) { Logger.error("Could not found MOA extraction method while getting attribute: " + storkAttribute); - e.printStackTrace(); + Logger.debug(e); + } catch (NullPointerException e) { + Logger.error("Error getting MOA extraction method while getting attribute: " + storkAttribute); + Logger.debug(e); } } else if (storkAttributeFunctionMapping.containsKey(storkAttribute)) { Logger.debug("Trying to get value for attribute using function mapping [" + storkAttribute + "]"); try { - Method method = this.getClass().getDeclaredMethod(storkAttributeFunctionMapping.get(storkAttribute)); - populateAttributeWithMethod(method, this, attributeList, storkAttribute, requestedAttribute.isRequired()); + Method method = this.getClass().getDeclaredMethod(storkAttributeFunctionMapping.get(storkAttribute), PersonalAttribute.class); + populateAttributeWithMethod(method, this, attributeList, storkAttribute, requestedAttribute); } catch (NoSuchMethodException e) { Logger.error("Could not found MOA extraction method while getting attribute: " + storkAttribute); - e.printStackTrace(); } } else { Logger.debug("MOA method for extraction of attribute " + storkAttribute + " not defined."); } } - private String geteIdentifier() { + private String getAge(PersonalAttribute personalAttribute) { + if (authData.getDateOfBirth() != null) { + Integer age = new Period(authData.getDateOfBirth().getTime(), Calendar.getInstance().getTime().getTime()).getYears(); + return age >= 0 ? age.toString() : null; + } + return null; // WP4 D4.2, Table 12:age, description - considerations + } + + private String getIsAgeOver(PersonalAttribute personalAttribute) + { + try { + if ((authData.getDateOfBirth() != null) && (personalAttribute.getValue() != null) && (personalAttribute.getValue().size() > 0)) { + Integer ageOver = Integer.parseInt(personalAttribute.getValue().get(0)); + Integer age = new Period(authData.getDateOfBirth().getTime(), Calendar.getInstance().getTime().getTime()).getYears(); + return age >= ageOver ? ageOver.toString() : ""; + } + } catch (Exception ex) { + Logger.error("Error encountered when determining isAgeOver"); + Logger.debug(ex); + } + return null; + } + + public String getQAALevel(PersonalAttribute personalAttribute) { + if (authData.getQAALevel().startsWith(PVPConstants.STORK_QAA_PREFIX)) + return authData.getQAALevel().substring(PVPConstants.STORK_QAA_PREFIX.length()); + else + return null; + } + + + private String geteIdentifier(PersonalAttribute personalAttribute) { Logger.debug("Using base urn for identification value: " + authData.getIdentificationType() + " and target country: " + moastorkRequest.getStorkAuthnRequest().getSpCountry()); try { - return new BPKBuilder().buildStorkeIdentifier(authData.getIdentificationType(), authData.getIdentificationValue(), - moastorkRequest.getStorkAuthnRequest().getSpCountry()); + return new BPKBuilder().buildStorkeIdentifier(authData.getIdentificationType(), authData.getIdentificationValue(), + moastorkRequest.getStorkAuthnRequest().getSpCountry()); } catch (BuildException be) { Logger.error("Stork eid could not be constructed; " + be.getMessage()); return null; // TODO error } } - private List getECApplicationRole() { + private List getECApplicationRole(PersonalAttribute personalAttribute) { List storkRoles = null; if (authData.getAuthenticationRoles() != null @@ -137,29 +175,32 @@ public class MOAAttributeProvider { String storkRole = mapper.map(el); if (MiscUtil.isNotEmpty(storkRole)) storkRoles.add(storkRole); - } } return storkRoles; } - private String getFormatedDateOfBirth() { + private String getFormatedDateOfBirth(PersonalAttribute personalAttribute) { if (authData.getDateOfBirth() != null) { DateFormat fmt = new SimpleDateFormat("yyyyMMdd"); return fmt.format(authData.getDateOfBirth()); } else return null; - } - private void populateAttributeWithMethod(Method method, Object object, PersonalAttributeList attributeList, String storkAttribute, Boolean isRequired) { + private void populateAttributeWithMethod(Method method, Object object, PersonalAttributeList attributeList, String storkAttribute, PersonalAttribute requestedAttribute) { try { - Object attributeValue = method.invoke(object, new Class[]{}); // (Object[]) - + Object attributeValue; + if (storkAttributeSimpleMapping.containsValue(method.getName())) { + attributeValue = method.invoke(object, new Class[]{}); + } else { + attributeValue = method.invoke(object, requestedAttribute); + } + PersonalAttribute newAttribute = new PersonalAttribute(); newAttribute.setName(storkAttribute); - newAttribute.setIsRequired(isRequired); + newAttribute.setIsRequired(requestedAttribute.isRequired()); if (attributeValue != null) { newAttribute.setStatus(AttributeStatusType.AVAILABLE.value()); @@ -192,10 +233,13 @@ public class MOAAttributeProvider { } catch (InvocationTargetException e) { Logger.error("Invocation target exception while getting attribute: " + storkAttribute); - e.printStackTrace(); + Logger.debug(e); } catch (IllegalAccessException e) { Logger.error("Illegal access exception while getting attribute: " + storkAttribute); - e.printStackTrace(); + Logger.debug(e); + } catch (NullPointerException e) { + Logger.error("Could not find method: " + storkAttribute); + Logger.debug(e); } } -- cgit v1.2.3 From b7c5a35d0f5a960bfaf8008ec2661f21764d2e2d Mon Sep 17 00:00:00 2001 From: Bojan Suzic Date: Tue, 19 May 2015 13:45:11 +0200 Subject: integrating attribute correlation check for eidentifier, when present; updating mandate data; extending error messages --- .../id/protocols/stork2/AttributeCollector.java | 22 ++++++-- .../moa/id/protocols/stork2/MandateContainer.java | 3 +- .../protocols/stork2/MandateRetrievalRequest.java | 61 ++++++++++++---------- .../stork2/PhyPersonMandateContainer.java | 3 +- .../MandateAttributeRequestProvider.java | 24 +++++++-- 5 files changed, 75 insertions(+), 38 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java index 371cfb1d7..42e9bf25d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java @@ -50,7 +50,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** - * the AttributeCollector Action tries to get all requested attributes from a set of {@link AttributeProvider} Plugins. + * The AttributeCollector Action tries to get all requested attributes from a set of {@link AttributeProvider} Plugins. * The class is called whenever the {@link AuthenticationRequest} Action is invoked and checks for missing attributes. * Furthermore, the class can handle direct posts. That is when the class triggers an attribute query which needs user * interaction, redirect to another portal, etc. The redirect will hit here and the class can continue to fetch attributes. @@ -80,8 +80,6 @@ public class AttributeCollector implements IAction { } - // TODO extract attribute response and check if it corresponds to the container - if (httpReq.getParameter("SAMLResponse") != null) { Logger.info("Got SAML response from external attribute provider."); @@ -106,7 +104,7 @@ public class AttributeCollector implements IAction { STORKAuthnResponse authnResponse = null; - // check if valid authn request is contained + // check if valid authn response is contained try { authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, httpReq.getRemoteAddr()); } catch (STORKSAMLEngineException ex) { @@ -115,6 +113,22 @@ public class AttributeCollector implements IAction { STORK2Response.setSTORKAuthnResponseToken(decSamlToken); + // check if the attributes are provided for the same person from request + // requires presence of eIdentifier for unambigious correlation + Logger.debug("Checking if the attribute relates to the correct person.."); + try { + String remoteEIdentifier= authnResponse.getPersonalAttributeList().get("eIdentifier").getValue().get(0); + String localEidentifier= container.getResponse().getStorkAuthnResponse().getPersonalAttributeList().get("eIdentifier").getValue().get(0); + if (!remoteEIdentifier.equals(localEidentifier)) { + Logger.error("The attribute is not provided for the same person!"); + throw new MOAIDException("stork.25", null); + } + } catch (NullPointerException ex) { + Logger.warn("Could not check the correlation of attributes from external provider. Ignoring the check."); + //Logger.debug(ex); + //throw new MOAIDException("stork.04", null); // TODO revise message, raise exception when ehvd checked + } + if (authnResponse.getPersonalAttributeList().size() > 0) { Logger.info("Response from external attribute provider contains " + authnResponse.getPersonalAttributeList().size() + " attributes."); container.getResponse().setPersonalAttributeList(addOrUpdateAll(container.getResponse().getPersonalAttributeList(), authnResponse.getPersonalAttributeList())); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java index 9207cc2dc..a3fac0f6e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java @@ -165,7 +165,8 @@ public abstract class MandateContainer { } public void setPhysicalRepresentativeBirthDate(String physicalRepresentativeBirthDate) { - this.physicalRepresentativeBirthDate = physicalRepresentativeBirthDate; + // making it conform to STORK dateOfBirth specifications, removing dash + this.physicalRepresentativeBirthDate = physicalRepresentativeBirthDate.replaceAll("-",""); } public String getAnnotation() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java index 59e1dbeca..c529a8465 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java @@ -41,7 +41,6 @@ import eu.stork.peps.auth.commons.PersonalAttribute; import eu.stork.peps.auth.commons.PersonalAttributeList; import eu.stork.peps.auth.commons.STORKAttrQueryResponse; import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.*; -import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.StringUtils; import javax.servlet.http.HttpServletRequest; @@ -54,14 +53,14 @@ import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import java.io.StringWriter; -import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.regex.Pattern; /** - * + * Entry point for mandate retrieval. Processes MIS data and transforms into STORK mandate attribute. + * Additionally provides eIdentifier attribute (if requested) in order to enable identity correlation */ public class MandateRetrievalRequest implements IAction { @@ -78,8 +77,13 @@ public class MandateRetrievalRequest implements IAction { this.QAALevel = translateQAALevel(authData.getQAALevel()); // preparing original content and removing sensitive data from it - this.originalContent = authData.getMISMandate().getMandate(); // TODO ERROR - //Logger.debug("Original content " + StringUtils.newStringUtf8(authData.getMISMandate().getMandate())); + try { + this.originalContent = authData.getMISMandate().getMandate(); + } catch (Exception e) { + Logger.error("Could not extract mandate"); + Logger.debug(e); + throw new MOAIDException("stork.26", new Object[]{}); + } String originalMandate = StringUtils.newStringUtf8(authData.getMISMandate().getMandate()).replaceAll(".*?==urn:publicid:gv.at:baseid","");; Logger.debug("Removing personal identification value and type from original mandate "); originalContent = StringUtils.getBytesUtf8(originalMandate); @@ -97,13 +101,13 @@ public class MandateRetrievalRequest implements IAction { this.moaStorkRequest = (MOASTORKRequest) req; } else { Logger.error("Internal error - did not receive MOASTORKRequest as expected"); - throw new MOAIDException("stork.16", new Object[]{}); // TODO + throw new MOAIDException("stork.27", new Object[]{}); } if (!(moaStorkRequest.isAttrRequest() || moaStorkRequest.getStorkAttrQueryRequest() == null)) { Logger.error("Did not receive attribute request as expected"); - throw new MOAIDException("stork.16", new Object[]{}); // TODO + throw new MOAIDException("stork.27", new Object[]{}); } MandateContainer mandateContainer = null; @@ -115,7 +119,7 @@ public class MandateRetrievalRequest implements IAction { mandateContainer = new PhyPersonMandateContainer(new String(authData.getMISMandate().getMandate(), "UTF-8")); } catch (Exception ex2) { Logger.error("Could not extract data and create mandate container."); - throw new MOAIDException("stork.16", new Object[]{}); // TODO + throw new MOAIDException("stork.27", new Object[]{}); } } @@ -123,26 +127,21 @@ public class MandateRetrievalRequest implements IAction { IPersonalAttributeList attributeList = new PersonalAttributeList(); + // according to new mapping, only mandate attribute is directly relevant for (PersonalAttribute currentAttribute : sourceAttributeList) { - Logger.debug("Evaluating currentattribute " + currentAttribute.getName()); - if (currentAttribute.getName().equals("mandateContent")) { + Logger.debug("Evaluating attributes, current attribute: " + currentAttribute.getName()); + if (currentAttribute.getName().equals("mandateContent")) { // deprecated MandateContentType mandateContent = getMandateContent(mandateContainer, currentAttribute); attributeList.add(marshallComplexAttribute(currentAttribute, mandateContent)); - } else if (currentAttribute.getName().equals("representative")) { // TODO CHECK IN DETAIL + } else if (currentAttribute.getName().equals("representative")) { // deprecated RepresentationPersonType representative = getRepresentative(mandateContainer, currentAttribute); attributeList.add(marshallComplexAttribute(currentAttribute, representative)); - - //attributeList.add(getRepresentative(mandateContainer, currentAttribute)); } else if (currentAttribute.getName().equals("represented")) { - //attributeList.add(getRepresented(mandateContainer, currentAttribute)); RepresentationPersonType represented = getRepresented(mandateContainer, currentAttribute); attributeList.add(marshallComplexAttribute(currentAttribute, represented)); - } else if (currentAttribute.getName().equals("mandate")) { - //attributeList.add(getMandateType(mandateContainer, currentAttribute)); MandateType mandateType = getMandateType(mandateContainer, currentAttribute); attributeList.add(marshallComplexAttribute(currentAttribute, mandateType)); - } else if (currentAttribute.getName().equals("legalName")) { String legalName = getLegalName(mandateContainer, currentAttribute); if (legalName.length() > 0) { @@ -180,6 +179,11 @@ public class MandateRetrievalRequest implements IAction { } } + if (currentAttribute.getName().equals("eIdentifier")) { + attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(geteIdentifier(authData.getIdentificationType(), authData.getIdentificationValue(), moaStorkRequest.getStorkAttrQueryRequest().getSpCountry())), AttributeStatusType.AVAILABLE.value())); + Logger.info("Adding eIdentifier for mandate holder using SP country: " + moaStorkRequest.getStorkAttrQueryRequest().getSpCountry()); + } + } @@ -228,7 +232,7 @@ public class MandateRetrievalRequest implements IAction { if (qaaLevel.equals(PVPConstants.STORK_QAA_1_4)) return 4; Logger.error("Wrong QAA Number format"); - throw new MOAIDException("stork.16", new Object[]{}); + throw new MOAIDException("stork.28", new Object[]{}); } private String geteLPIdentifier(MandateContainer mandateContainer, PersonalAttribute currentAttribute) throws MOAIDException { @@ -237,11 +241,20 @@ public class MandateRetrievalRequest implements IAction { return represented.getELPIdentifier(); } else if (currentAttribute.isRequired()) { Logger.error("Cannot provide eLPIdentifier for natural person."); - throw new MOAIDException("stork.19", new Object[]{currentAttribute.getName()}); // TODO + throw new MOAIDException("stork.29", new Object[]{currentAttribute.getName()}); } return ""; } + private String geteIdentifier(String identificationType, String identificationValue, String destinationCountry) throws MOAIDException { + BPKBuilder bpkBuilder = new BPKBuilder(); + try { + return bpkBuilder.buildStorkeIdentifier(identificationType, identificationValue, destinationCountry); + } catch (BuildException be) { + Logger.error("Could not build STORK eIdentifier while generating mandate assertion."); + throw new MOAIDException("stork.29", new Object[]{}); + } + } private PersonalAttribute marshallComplexAttribute(PersonalAttribute currentAttribute, Object obj) { // TODO refactor StringWriter stringWriter = new StringWriter(); @@ -456,7 +469,6 @@ public class MandateRetrievalRequest implements IAction { private String getRepresentedStorkeIdentifier(MandateContainer mandateContainer) throws MOAIDException { - //String identificationType, String identificationValue if (!(mandateContainer instanceof PhyPersonMandateContainer)) { Logger.error("Physical person mandate container missing"); throw new MOAIDException("stork.20", new Object[]{}); // TODO @@ -479,13 +491,7 @@ public class MandateRetrievalRequest implements IAction { throw new MOAIDException("stork.20", new Object[]{}); // TODO } - BPKBuilder bpkBuilder = new BPKBuilder(); - try { - return bpkBuilder.buildStorkeIdentifier(phyPersonMandateContainer.getPhyPersMandatorIdentificationType(), phyPersonMandateContainer.getPhyPersMandatorIdentificationValue(), this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry()); - } catch (BuildException be) { - Logger.error("Could not build STORK eIdentifier while generating mandate assertion."); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } + return geteIdentifier(phyPersonMandateContainer.getPhyPersMandatorIdentificationType(), phyPersonMandateContainer.getPhyPersMandatorIdentificationValue(), this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry()); } private String getRepresentingStorkeIdentifier(MandateContainer mandateContainer) throws MOAIDException { @@ -522,6 +528,7 @@ public class MandateRetrievalRequest implements IAction { Logger.error("Could not build STORK eIdentifier while generating mandate assertion."); throw new MOAIDException("stork.20", new Object[]{}); // TODO } + } private RepresentationPersonType getRepresentative(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java index ba89663ab..c715b65eb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java @@ -109,7 +109,8 @@ public class PhyPersonMandateContainer extends MandateContainer { } public void setPhyPersMandatorBirthDate(String phyPersMandatorBirthDate) { - this.phyPersMandatorBirthDate = phyPersMandatorBirthDate; + // making it conform to STORK dateOfBirth specifications, removing dash + this.phyPersMandatorBirthDate = phyPersMandatorBirthDate.replaceAll("-",""); } public String getPhyPersMandatorIdentificationValue() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java index f4d963645..f671f0807 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java @@ -73,6 +73,7 @@ public class MandateAttributeRequestProvider extends AttributeProvider { return "MandateAttributeRequestProvider"; } + // TODO check if used @Override protected IPersonalAttributeList acquire(PersonalAttribute attribute, MOASTORKRequest moastorkRequest, IAuthData authData) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException { Logger.info("Acquiring attribute: " + attribute.getName() + ", by: " + getAttrProviderName()); @@ -85,10 +86,14 @@ public class MandateAttributeRequestProvider extends AttributeProvider { Logger.info("Attribute " + attribute.getName() + " not supported by the provider: " + getAttrProviderName()); throw new UnsupportedAttributeException(); } - PersonalAttributeList result = new PersonalAttributeList(); - //return result; - + // check if there is eIdentifier included and add if necessary +// if (!requestedAttributes.containsKey("eIdentifier")) { +// PersonalAttribute eIdentifier = new PersonalAttribute(); + // eIdentifier.setName("eIdentifier"); +// eIdentifier.setIsRequired(true); +// requestedAttributes.add(eIdentifier); +// } Logger.info("Thrown external request by: " + getAttrProviderName()); throw new ExternalAttributeRequestRequiredException(this); @@ -111,10 +116,12 @@ public class MandateAttributeRequestProvider extends AttributeProvider { // continue with other attribute providers if there are no attributes current provider is able to handle if (requestedAttributes.size() == 0) { - Logger.info("Attribute(s) " + attributes.toString() + " not supported by the provider: " + getAttrProviderName()); + Logger.info("Attribute(s) " + attributes.toString() + " not supported by the provider: " + getAttrProviderName()); throw new UnsupportedAttributeException(); } + + Logger.info("Thrown external request by: " + getAttrProviderName()); throw new ExternalAttributeRequestRequiredException(this); } @@ -144,7 +151,14 @@ public class MandateAttributeRequestProvider extends AttributeProvider { } - + // TODO ensure that other providers request eidentifier + // check if there is eIdentifier included and add if necessary + if (!requestedAttributes.containsKey("eIdentifier")) { + PersonalAttribute eIdentifier = new PersonalAttribute(); + eIdentifier.setName("eIdentifier"); + eIdentifier.setIsRequired(true); + requestedAttributes.add(eIdentifier); + } //generate AttrQueryRequest STORKAttrQueryRequest attributeRequest = new STORKAttrQueryRequest(); -- cgit v1.2.3 From 1d577f0587f7d77b1c54a3ebc22bf20c5cb9aa13 Mon Sep 17 00:00:00 2001 From: Bojan Suzic Date: Tue, 19 May 2015 14:32:37 +0200 Subject: enable usage of http locally when proxied on the same machine; hidden option, LU specific --- .../moa/id/auth/parser/StartAuthentificationParameterParser.java | 4 ++-- .../moa/id/config/auth/AuthConfigurationProvider.java | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java index a123569d5..a0584e1e9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java @@ -212,8 +212,8 @@ public class StartAuthentificationParameterParser implements MOAIDAuthConstants{ authURL = authURL.concat(":" + req.getServerPort()); } authURL = authURL.concat(req.getContextPath() + "/"); - - if (!authURL.startsWith("https:")) + boolean auth = AuthConfigurationProvider.getInstance().isHTTPAuthAllowed(); + if (!authURL.startsWith("https:") && !AuthConfigurationProvider.getInstance().isHTTPAuthAllowed()) throw new AuthenticationException("auth.07", new Object[] { authURL + "*" }); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index d33a9ea92..6a2f2db44 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -1072,7 +1072,14 @@ public class AuthConfigurationProvider extends ConfigurationProvider { else return null; } - + + // allow http to be used in call, used in systems proxied on the same instance + public boolean isHTTPAuthAllowed() { + String prop = props.getProperty("configuration.localhttpallowed.active", "false"); + return Boolean.valueOf(prop); + } + + public boolean isAdvancedLoggingActive() { String prop = props.getProperty("configuration.advancedlogging.active", "false"); return Boolean.valueOf(prop); -- cgit v1.2.3 From 2319e2712bc5a82c86222202792b7806625fb651 Mon Sep 17 00:00:00 2001 From: Bojan Suzic Date: Tue, 19 May 2015 14:33:15 +0200 Subject: enable usage of http locally when proxied on the same machine; hidden option, LU specific --- .../moa/id/auth/parser/StartAuthentificationParameterParser.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java index a0584e1e9..f538d2d12 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java @@ -212,7 +212,7 @@ public class StartAuthentificationParameterParser implements MOAIDAuthConstants{ authURL = authURL.concat(":" + req.getServerPort()); } authURL = authURL.concat(req.getContextPath() + "/"); - boolean auth = AuthConfigurationProvider.getInstance().isHTTPAuthAllowed(); + if (!authURL.startsWith("https:") && !AuthConfigurationProvider.getInstance().isHTTPAuthAllowed()) throw new AuthenticationException("auth.07", new Object[] { authURL + "*" }); -- cgit v1.2.3