aboutsummaryrefslogtreecommitdiff
path: root/id/server/modules
diff options
context:
space:
mode:
Diffstat (limited to 'id/server/modules')
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/pom.xml62
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java1371
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationAssertionBuilder.java125
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java584
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/Builder.java105
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/CertInfoVerifyXMLSignatureRequestBuilder.java130
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java172
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java246
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetVerifyAuthBlockFormBuilder.java128
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java195
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java124
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginConfirmationBuilder.java101
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java105
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java137
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java70
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java408
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java142
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java36
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java103
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java138
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java192
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java184
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java189
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java101
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java207
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java160
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java175
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java111
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java285
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/ErrorResponseParser.java115
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/ExtendedInfoboxReadResponseParser.java203
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java274
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java211
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java671
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java209
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/InfoboxValidator.java128
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java303
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/ParepUtils.java762
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClientException.java88
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWSecureSocketFactory.java170
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/CitizenCardServletUtils.java171
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSessionId.java68
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java359
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.auth.modules.AuthModule2
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml53
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/AllTests.java79
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilderTest.java93
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureBuilderTest.java151
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilderTest.java119
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderTest.java75
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilderTest.java97
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/AllTests.java75
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParserTest.java179
-rw-r--r--id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParserTest.java113
-rw-r--r--id/server/modules/moa-id-module-openID/pom.xml86
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java76
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java70
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java74
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java111
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java45
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java299
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAudiencesAttribute.java48
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java47
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java51
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java49
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java47
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java58
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java47
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java47
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java47
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java47
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java34
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java34
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java71
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java34
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java34
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java35
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20OANotSupportedException.java44
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java34
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java34
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java34
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java34
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java121
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java84
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java116
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java49
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java63
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java29
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java214
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java243
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java148
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java215
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java124
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java166
-rw-r--r--id/server/modules/moa-id-module-openID/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo1
-rw-r--r--id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/CertTest.java131
-rw-r--r--id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20ErrorsTests.java184
-rw-r--r--id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20GoogleClientTestCase.java158
-rw-r--r--id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20UtilTest.java70
-rw-r--r--id/server/modules/moa-id-modules-saml1/pom.xml44
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataAssertionBuilder.java458
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilder.java167
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParser.java104
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java141
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java213
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationData.java177
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java635
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java226
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java108
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo1
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilderTest.java98
-rw-r--r--id/server/modules/moa-id-modules-saml1/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParserTest.java101
-rw-r--r--id/server/modules/module-monitoring/pom.xml9
-rw-r--r--id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java2
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java4
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java11
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java4
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java4
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java5
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java64
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java286
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAgeAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAttributHelper.java69
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKFiscalNumberAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKGenderAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKIsAgeOverAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKMaritalStatusAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKNationalityCodeAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKPseudonymAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKResidencePermitAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTextResidenceAddressAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTitleAttributBuilder.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java367
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java101
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java531
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java249
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java115
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java100
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java53
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java248
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java265
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java308
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java182
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java602
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java132
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java66
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java49
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java233
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java83
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/UnsupportedAttributeException.java29
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java139
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java254
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java231
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java238
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java688
-rw-r--r--id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java193
-rw-r--r--id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo1
-rw-r--r--id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder14
-rw-r--r--id/server/modules/pom.xml5
163 files changed, 23716 insertions, 18 deletions
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/pom.xml b/id/server/modules/moa-id-modul-citizencard_authentication/pom.xml
new file mode 100644
index 000000000..49293420c
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/pom.xml
@@ -0,0 +1,62 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>MOA.id.server.modules</groupId>
+ <artifactId>moa-id-modules</artifactId>
+ <version>${moa-id-version}</version>
+ </parent>
+ <artifactId>moa-id-modul-citizencard_authentication</artifactId>
+
+ <packaging>jar</packaging>
+ <name>MOA ID-Module Citizen-Card Authentication</name>
+
+ <properties>
+ <repositoryPath>${basedir}/../../../../repository</repositoryPath>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>MOA.id.server</groupId>
+ <artifactId>moa-id-lib</artifactId>
+ <scope>test</scope>
+ <type>test-jar</type>
+ <version>3.0.3-Snapshot</version>
+ </dependency>
+
+ <dependency>
+ <groupId>MOA</groupId>
+ <artifactId>moa-common</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>MOA.id.server</groupId>
+ <artifactId>moa-id-lib</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>xalan-bin-dist</groupId>
+ <artifactId>xalan</artifactId>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </dependency>
+
+ </dependencies>
+
+</project> \ No newline at end of file
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java
new file mode 100644
index 000000000..93ac33524
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java
@@ -0,0 +1,1371 @@
+package at.gv.egovernment.moa.id.auth;
+
+
+import iaik.asn1.ObjectID;
+import iaik.x509.X509Certificate;
+import iaik.x509.X509ExtensionInitException;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.Principal;
+import java.security.cert.CertificateException;
+import java.util.Calendar;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.TransformerException;
+
+import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.xpath.XPathAPI;
+import org.opensaml.xml.util.Base64;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
+import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
+import at.gv.egovernment.moa.id.auth.builder.AuthenticationBlockAssertionBuilder;
+import at.gv.egovernment.moa.id.auth.builder.BPKBuilder;
+import at.gv.egovernment.moa.id.auth.builder.CreateXMLSignatureRequestBuilder;
+import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
+import at.gv.egovernment.moa.id.auth.builder.GetIdentityLinkFormBuilder;
+import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilder;
+import at.gv.egovernment.moa.id.auth.builder.VerifyXMLSignatureRequestBuilder;
+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.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttributeImpl;
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse;
+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.exception.ValidateException;
+import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
+import at.gv.egovernment.moa.id.auth.invoke.SignatureVerificationInvoker;
+import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser;
+import at.gv.egovernment.moa.id.auth.parser.InfoboxReadResponseParser;
+import at.gv.egovernment.moa.id.auth.parser.VerifyXMLSignatureResponseParser;
+import at.gv.egovernment.moa.id.auth.validator.CreateXMLSignatureResponseValidator;
+import at.gv.egovernment.moa.id.auth.validator.IdentityLinkValidator;
+import at.gv.egovernment.moa.id.auth.validator.VerifyXMLSignatureResponseValidator;
+import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWConstants;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.MISMandate;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.id.util.XMLUtil;
+import at.gv.egovernment.moa.logging.LogMsg;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.DateTimeUtils;
+import at.gv.egovernment.moa.util.FileUtils;
+import at.gv.egovernment.moa.util.MiscUtil;
+import at.gv.egovernment.moa.util.StringUtils;
+
+/**
+ * API for MOA ID Authentication Service.<br> {@link AuthenticationSession} is
+ * stored in a session store and retrieved by giving the session ID.
+ *
+ * @author Paul Ivancsics
+ * @version $Id: AuthenticationServer.java 1273 2012-02-27 14:50:18Z kstranacher
+ * $
+ */
+public class AuthenticationServer extends BaseAuthenticationServer {
+
+ /**
+ * single instance
+ */
+ private static AuthenticationServer instance;
+
+ /**
+ * Returns the single instance of <code>AuthenticationServer</code>.
+ *
+ * @return the single instance of <code>AuthenticationServer</code>
+ */
+ public static AuthenticationServer getInstance() {
+ if (instance == null)
+ instance = new AuthenticationServer();
+ return instance;
+ }
+
+ /**
+ * Constructor for AuthenticationServer.
+ */
+ public AuthenticationServer() {
+ super();
+ }
+
+
+ /**
+ * Processes the beginning of an authentication session.
+ * <ul>
+ * <li>Starts an authentication session</li>
+ * <li>Creates an <code>&lt;InfoboxReadRequest&gt;</code></li>
+ * <li>Creates an HTML form for querying the identity link from the security
+ * layer implementation. <br>
+ * Form parameters include
+ * <ul>
+ * <li>the <code>&lt;InfoboxReadRequest&gt;</code></li>
+ * <li>the data URL where the security layer implementation sends it
+ * response to</li>
+ * </ul>
+ * </ul>
+ *
+ * @param authURL URL of the servlet to be used as data URL
+ * @param target "Gesch&auml;ftsbereich" of the online application requested
+ * @param targetFriendlyName Friendly name of the target if the target is configured via
+ * configuration
+ * @param oaURL online application URL requested
+ * @param bkuURL URL of the "B&uuml;rgerkartenumgebung" to be used; may be
+ * <code>null</code>; in this case, the default location will be
+ * used
+ * @param useMandate Indicates if mandate is used or not
+ * @param templateURL URL providing an HTML template for the HTML form generated
+ * @param templateMandteURL URL providing an HTML template for the HTML form generated
+ * (for signing in mandates mode)
+ * @param req determines the protocol used
+ * @param sourceID
+ * @return HTML form
+ * @throws AuthenticationException
+ * @see GetIdentityLinkFormBuilder
+ * @see InfoboxReadRequestBuilder
+ */
+ public String startAuthentication(AuthenticationSession session, HttpServletRequest req) throws WrongParametersException,
+ AuthenticationException, ConfigurationException, BuildException {
+
+ if (session == null) {
+ throw new AuthenticationException("auth.18", new Object[]{});
+ }
+
+ //load OnlineApplication configuration
+ OAAuthParameter oaParam =
+ AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+ if (oaParam == null)
+ throw new AuthenticationException("auth.00", new Object[]{session.getPublicOAURLPrefix()});
+
+ //load Template
+ String template = null;
+ if (session.getTemplateURL() != null) {
+ try {
+
+ template = new String(FileUtils.readURL(session.getTemplateURL()));
+ } catch (IOException ex) {
+ throw new AuthenticationException("auth.03", new Object[]{
+ session.getTemplateURL(), ex.toString()}, ex);
+ }
+ }
+
+ String infoboxReadRequest = "";
+
+ String domainIdentifier = AuthConfigurationProviderFactory.getInstance().getSSOTagetIdentifier().trim();
+ if (MiscUtil.isEmpty(domainIdentifier) && session.isSsoRequested()) {
+ //do not use SSO if no Target is set
+ Logger.warn("NO SSO-Target found in configuration. Single Sign-On is deaktivated!");
+ session.setSsoRequested(false);
+
+ }
+
+ if (session.isSsoRequested()) {
+ Logger.info("SSO Login requested");
+ //load identityLink with SSO Target
+ boolean isbuisness = false;
+
+ if (domainIdentifier.startsWith(PREFIX_WPBK)) {
+
+ isbuisness = true;
+
+ } else {
+ isbuisness = false;
+
+ }
+
+ //build ReadInfobox request
+ infoboxReadRequest = new InfoboxReadRequestBuilder().build(
+ isbuisness, domainIdentifier);
+
+ } else {
+ Logger.info("Non-SSO Login requested");
+ //build ReadInfobox request
+ infoboxReadRequest = new InfoboxReadRequestBuilder().build(
+ oaParam.getBusinessService(), oaParam
+ .getIdentityLinkDomainIdentifier());
+
+ }
+
+
+ String dataURL = new DataURLBuilder().buildDataURL(
+ session.getAuthURL(), REQ_VERIFY_IDENTITY_LINK, session
+ .getSessionID());
+
+ //removed in MOAID 2.0
+ String pushInfobox = "";
+
+ // VerifyInfoboxParameters verifyInfoboxParameters = oaParam
+ // .getVerifyInfoboxParameters();
+ // if (verifyInfoboxParameters != null) {
+ // pushInfobox = verifyInfoboxParameters.getPushInfobox();
+ // session.setPushInfobox(pushInfobox);
+ // }
+
+ //build CertInfo request
+ //removed in MOA-ID 2.0
+ // String certInfoRequest = new CertInfoVerifyXMLSignatureRequestBuilder()
+ // .build();
+ // String certInfoDataURL = new DataURLBuilder()
+ // .buildDataURL(session.getAuthURL(), REQ_START_AUTHENTICATION,
+ // session.getSessionID());
+
+ //get Applet Parameters
+ String appletwidth = req.getParameter(PARAM_APPLET_WIDTH);
+ String appletheigth = req.getParameter(PARAM_APPLET_HEIGTH);
+ appletheigth = StringEscapeUtils.escapeHtml(appletheigth);
+ appletwidth = StringEscapeUtils.escapeHtml(appletwidth);
+
+ //TODO: cleanup before MOA-ID 2.1 release
+ try {
+ String htmlForm = new GetIdentityLinkFormBuilder().build(template,
+ session.getBkuURL(), infoboxReadRequest, dataURL, null,
+ null, pushInfobox, oaParam, appletheigth, appletwidth);
+
+ return htmlForm;
+
+ } catch (BuildException e) {
+ throw new BuildException("builder.07", null, e);
+
+ }
+ }
+
+ /**
+ * Processes an <code>&lt;InfoboxReadResponse&gt;</code> sent by the security layer implementation.<br>
+ * <ul>
+ * <li>Validates given <code>&lt;InfoboxReadResponse&gt;</code></li>
+ * <li>Parses identity link enclosed in <code>&lt;InfoboxReadResponse&gt;</code></li>
+ * <li>Verifies identity link by calling the MOA SP component</li>
+ * <li>Checks certificate authority of identity link</li>
+ * <li>Stores identity link in the session</li>
+ * <li>Verifies all additional infoboxes returned from the BKU</li>
+ * <li>Creates an authentication block to be signed by the user</li>
+ * <li>Creates and returns a <code>&lt;CreateXMLSignatureRequest&gt;</code> containg the authentication block, meant
+ * to be returned to the security layer implementation</li>
+ * </ul>
+ *
+ * @param sessionID
+ * ID of associated authentication session data
+ * @param infoboxReadResponseParameters
+ * The parameters from the response returned from the BKU including the
+ * <code>&lt;InfoboxReadResponse&gt;</code>
+ * @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(IRequest pendingReq, AuthenticationSession session,
+ Map<String, String> infoboxReadResponseParameters) throws AuthenticationException,
+ BuildException, ParseException, ConfigurationException,
+ ValidateException, ServiceException, BKUException {
+
+ if (session == null)
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_IDENTITY_LINK, PARAM_SESSIONID});
+
+ String xmlInfoboxReadResponse = (String) infoboxReadResponseParameters
+ .get(PARAM_XMLRESPONSE);
+
+ if (isEmpty(xmlInfoboxReadResponse))
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_IDENTITY_LINK, PARAM_XMLRESPONSE});
+
+ AuthConfiguration authConf = AuthConfigurationProviderFactory
+ .getInstance();
+
+ // check if an identity link was found
+ // Errorcode 2911 von Trustdesk BKU (nicht spezifikationskonform
+ // (SL1.2))
+ // CharSequence se = "ErrorCode>2911".substring(0);
+ // boolean b = xmlInfoboxReadResponse.contains(se);
+ String se = "ErrorCode>2911";
+ int b = xmlInfoboxReadResponse.indexOf(se);
+ if (b != -1) { // no identity link found
+ Logger
+ .info("Es konnte keine Personenbindung auf der Karte gefunden werden. Versuche Anmeldung als auslaendische eID.");
+ return null;
+ }
+ // spezifikationsgemaess (SL1.2) Errorcode
+ se = "ErrorCode>4002";
+ // b = xmlInfoboxReadResponse.contains(se);
+ b = xmlInfoboxReadResponse.indexOf(se);
+ if (b != -1) { // Unbekannter Infoboxbezeichner
+ Logger
+ .info("Unbekannter Infoboxbezeichner. Versuche Anmeldung als auslaendische eID.");
+ return null;
+ }
+
+ // parses the <InfoboxReadResponse>
+ IdentityLink identityLink = new InfoboxReadResponseParser(
+ xmlInfoboxReadResponse).parseIdentityLink();
+ // validates the identity link
+ IdentityLinkValidator.getInstance().validate(identityLink);
+ // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP
+ Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder()
+ .build(identityLink, authConf
+ .getMoaSpIdentityLinkTrustProfileID(pendingReq.getOnlineApplicationConfiguration().isUseIDLTestTrustStore()));
+
+ // invokes the call
+ Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker()
+ .verifyXMLSignature(domVerifyXMLSignatureRequest);
+ // parses the <VerifyXMLSignatureResponse>
+ VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser(
+ domVerifyXMLSignatureResponse).parseData();
+
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+
+ // validates the <VerifyXMLSignatureResponse>
+ VerifyXMLSignatureResponseValidator.getInstance().validate(
+ verifyXMLSignatureResponse,
+ authConf.getIdentityLinkX509SubjectNames(),
+ VerifyXMLSignatureResponseValidator.CHECK_IDENTITY_LINK,
+ oaParam);
+
+ session.setIdentityLink(identityLink);
+ // now validate the extended infoboxes
+
+ //Removed in MOA-ID 2.0
+ //verifyInfoboxes(session, infoboxReadResponseParameters, false);
+
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_IDL_VALIDATED);
+
+ return "found!";
+ }
+
+ /**
+ * Processes an <code>&lt;InfoboxReadResponse&gt;</code> sent by the
+ * security layer implementation.<br>
+ * <ul>
+ * <li>Validates given <code>&lt;InfoboxReadResponse&gt;</code></li>
+ * <li>Parses identity link enclosed in
+ * <code>&lt;InfoboxReadResponse&gt;</code></li>
+ * <li>Verifies identity link by calling the MOA SP component</li>
+ * <li>Checks certificate authority of identity link</li>
+ * <li>Stores identity link in the session</li>
+ * <li>Verifies all additional infoboxes returned from the BKU</li>
+ * <li>Creates an authentication block to be signed by the user</li>
+ * <li>Creates and returns a <code>&lt;CreateXMLSignatureRequest&gt;</code>
+ * containg the authentication block, meant to be returned to the security
+ * layer implementation</li>
+ * </ul>
+ *
+ * @param sessionID ID of associated authentication session data
+ * @param infoboxReadResponseParameters The parameters from the response returned from the BKU
+ * including the <code>&lt;InfoboxReadResponse&gt;</code>
+ * @return String representation of the
+ * <code>&lt;CreateXMLSignatureRequest&gt;</code>
+ */
+ public String verifyCertificate(AuthenticationSession session,
+ X509Certificate certificate) throws AuthenticationException,
+ BuildException, ParseException, ConfigurationException,
+ ValidateException, ServiceException, MOAIDException {
+
+ if (session == null)
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID});
+
+ // check if person is a Organwalter
+ // if true - don't show bPK in AUTH Block
+ try {
+ for (ObjectID OWid : MOAIDAuthConstants.OW_LIST) {
+ if (certificate.getExtension(OWid) != null) {
+ session.setOW(true);
+ }
+
+ }
+
+ } catch (X509ExtensionInitException e) {
+ Logger.warn("Certificate extension is not readable.");
+ session.setOW(false);
+ }
+
+ AuthConfiguration authConf = AuthConfigurationProviderFactory
+ .getInstance();
+
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+
+ String returnvalue = getCreateXMLSignatureRequestAuthBlockOrRedirect(session,
+ authConf, oaParam);
+
+ return returnvalue;
+ }
+
+ /**
+ * Processes an <code>Mandate</code> sent by the MIS.<br>
+ * <ul>
+ * <li>Validates given <code>Mandate</code></li>
+ * <li>Verifies Mandate by calling the MOA SP component</li>
+ * <li>Creates an authentication block to be signed by the user</li>
+ * <li>Creates and returns a <code>&lt;CreateXMLSignatureRequest&gt;</code>
+ * containg the authentication block, meant to be returned to the security
+ * layer implementation</li>
+ * </ul>
+ * @param pendingReq
+ *
+ * @param sessionID ID of associated authentication session data
+ * @param infoboxReadResponseParameters The parameters from the response returned from the BKU
+ * including the <code>&lt;InfoboxReadResponse&gt;</code>
+ * @return String representation of the
+ * <code>&lt;CreateXMLSignatureRequest&gt;</code>
+ */
+ public void verifyMandate(AuthenticationSession session, MISMandate mandate)
+ throws AuthenticationException, BuildException, ParseException,
+ ConfigurationException, ValidateException, ServiceException {
+
+ if (session == null)
+ throw new AuthenticationException("auth.10", new Object[]{
+ GET_MIS_SESSIONID, PARAM_SESSIONID});
+
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+
+ try {
+ // sets the extended SAML attributes for OID (Organwalter)
+ setExtendedSAMLAttributeForMandatesOID(session, mandate, oaParam
+ .getBusinessService());
+
+ validateExtendedSAMLAttributeForMandates(session, mandate, oaParam.getBusinessService());
+
+
+ } catch (SAXException e) {
+ throw new AuthenticationException("auth.15",
+ new Object[]{GET_MIS_SESSIONID}, e);
+ } catch (IOException e) {
+ throw new AuthenticationException("auth.15",
+ new Object[]{GET_MIS_SESSIONID}, e);
+ } catch (ParserConfigurationException e) {
+ throw new AuthenticationException("auth.15",
+ new Object[]{GET_MIS_SESSIONID}, e);
+ } catch (TransformerException e) {
+ throw new AuthenticationException("auth.15",
+ new Object[]{GET_MIS_SESSIONID}, e);
+ }
+
+ }
+
+ /**
+ * @param session
+ * @param authConf
+ * @param oaParam
+ * @return
+ * @throws ConfigurationException
+ * @throws BuildException
+ * @throws ValidateException
+ */
+ public String getCreateXMLSignatureRequestAuthBlockOrRedirect(
+ AuthenticationSession session, AuthConfiguration authConf,
+ OAAuthParameter oaParam) throws ConfigurationException,
+ BuildException, ValidateException {
+
+ // // check for intermediate processing of the infoboxes
+ // if (session.isValidatorInputPending())
+ // return "Redirect to Input Processor";
+
+ if (authConf == null)
+ authConf = AuthConfigurationProviderFactory.getInstance();
+ if (oaParam == null)
+ oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(
+ session.getPublicOAURLPrefix());
+
+ // builds the AUTH-block
+ String authBlock = buildAuthenticationBlock(session, oaParam);
+
+ // builds the <CreateXMLSignatureRequest>
+ List<String> transformsInfos = authConf.getTransformsInfos();
+
+ String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder()
+ .build(authBlock, oaParam.getKeyBoxIdentifier(),
+ transformsInfos);
+ return createXMLSignatureRequest;
+ }
+
+ /**
+ * Returns an CreateXMLSignatureRequest for signing the ERnP statement.<br>
+ * <ul>
+ * <li>Creates an CreateXMLSignatureRequest to be signed by the user</li>
+ * </ul>
+ *
+ * @param sessionID ID of associated authentication session data
+ * @param cert The certificate from the user
+ * @return String representation of the
+ * <code>&lt;CreateXMLSignatureRequest&gt;</code>
+ */
+ public String createXMLSignatureRequestForeignID(AuthenticationSession session,
+ X509Certificate cert) throws AuthenticationException,
+ BuildException, ParseException, ConfigurationException,
+ ValidateException, ServiceException {
+
+ if (session == null)
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID});
+
+ AuthConfiguration authConf = AuthConfigurationProviderFactory
+ .getInstance();
+
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+
+ return getCreateXMLSignatureRequestForeigID(session, authConf, oaParam,
+ cert);
+ }
+
+ public String getCreateXMLSignatureRequestForeigID(
+ AuthenticationSession session, AuthConfiguration authConf,
+ OAAuthParameter oaParam, X509Certificate cert)
+ throws ConfigurationException {
+
+ // // check for intermediate processing of the infoboxes
+ // if (session.isValidatorInputPending())
+ // return "Redirect to Input Processor";
+
+ if (authConf == null)
+ authConf = AuthConfigurationProviderFactory.getInstance();
+ if (oaParam == null)
+ oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(
+ session.getPublicOAURLPrefix());
+
+ Principal subject = cert.getSubjectDN();
+
+ String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder()
+ .buildForeignID(subject.toString(), oaParam, session);
+ return createXMLSignatureRequest;
+ }
+
+// /**
+// * Processes an <code>&lt;CreateXMLSignatureResponse&gt;</code> sent by the
+// * security layer implementation.<br>
+// * <ul>
+// * <li>Validates given <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
+// * <li>Parses response enclosed in
+// * <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
+// * <li>Verifies signature by calling the MOA SP component</li>
+// * <li>Returns the signer certificate</li>
+// * </ul>
+// *
+// * @param sessionID ID of associated authentication session data
+// * @param createXMLSignatureResponseParameters The parameters from the response returned from the BKU
+// * including the <code>&lt;CreateXMLSignatureResponse&gt;</code>
+// * @throws BKUException
+// */
+// public X509Certificate verifyXMLSignature(String sessionID,
+// Map<String, String> createXMLSignatureResponseParameters)
+// throws AuthenticationException, BuildException, ParseException,
+// ConfigurationException, ValidateException, ServiceException, BKUException {
+//
+// if (isEmpty(sessionID))
+// throw new AuthenticationException("auth.10", new Object[]{
+// REQ_GET_FOREIGN_ID, PARAM_SESSIONID});
+//
+// String xmlCreateXMLSignatureResponse = (String) createXMLSignatureResponseParameters
+// .get(PARAM_XMLRESPONSE);
+//
+// if (isEmpty(xmlCreateXMLSignatureResponse))
+// throw new AuthenticationException("auth.10", new Object[]{
+// REQ_GET_FOREIGN_ID, PARAM_XMLRESPONSE});
+//
+// AuthConfiguration authConf = AuthConfigurationProviderFactory
+// .getInstance();
+//
+// // parses the <CreateXMLSignatureResponse>
+// CreateXMLSignatureResponseParser p = new CreateXMLSignatureResponseParser(
+// xmlCreateXMLSignatureResponse);
+// CreateXMLSignatureResponse createXMLSignatureResponse = p
+// .parseResponseDsig();
+//
+// // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP
+// Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder()
+// .buildDsig(createXMLSignatureResponse, authConf
+// .getMoaSpAuthBlockTrustProfileID());
+//
+// // invokes the call
+// Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker()
+// .verifyXMLSignature(domVerifyXMLSignatureRequest);
+//
+// // parses the <VerifyXMLSignatureResponse>
+// VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser(
+// domVerifyXMLSignatureResponse).parseData();
+//
+// return verifyXMLSignatureResponse.getX509certificate();
+//
+// }
+
+ /**
+ * Processes an <code>&lt;CreateXMLSignatureResponse&gt;</code> sent by the
+ * security layer implementation.<br>
+ * <ul>
+ * <li>Validates given <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
+ * <li>Parses response enclosed in
+ * <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
+ * <li>Verifies signature by calling the MOA SP component</li>
+ * <li>Returns the signer certificate</li>
+ * </ul>
+ * @param pendingReq
+ *
+ * @param sessionID ID of associated authentication session data
+ * @param readInfoboxResponseParameters The parameters from the response returned from the BKU
+ * including the <code>&lt;ReadInfoboxResponse&gt;</code>
+ * @throws BKUException
+ */
+ public X509Certificate getCertificate(IRequest pendingReq, String sessionID,
+ Map<String, String> readInfoboxResponseParameters) throws AuthenticationException,
+ BuildException, ParseException, ConfigurationException,
+ ValidateException, ServiceException, BKUException {
+
+ if (isEmpty(sessionID))
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID});
+
+ String xmlReadInfoboxResponse = (String) readInfoboxResponseParameters
+ .get(PARAM_XMLRESPONSE);
+
+ if (isEmpty(xmlReadInfoboxResponse))
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_CERTIFICATE, PARAM_XMLRESPONSE});
+
+ // parses the <CreateXMLSignatureResponse>
+ InfoboxReadResponseParser p = new InfoboxReadResponseParser(
+ xmlReadInfoboxResponse);
+ X509Certificate cert = p.parseCertificate();
+
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_CERTIFICATE_VALIDATED);
+
+ return cert;
+
+ }
+
+ /**
+ * Builds an authentication block <code>&lt;saml:Assertion&gt;</code> from
+ * given session data.
+ *
+ * @param session authentication session
+ * @return <code>&lt;saml:Assertion&gt;</code> as a String
+ * @throws BuildException If an error occurs on serializing an extended SAML attribute
+ * to be appended to the AUTH-Block.
+ */
+ private String buildAuthenticationBlock(AuthenticationSession session,
+ OAAuthParameter oaParam) throws BuildException {
+
+ IdentityLink identityLink = session.getIdentityLink();
+ String issuer = identityLink.getName();
+ String gebDat = identityLink.getDateOfBirth();
+
+ String identificationValue = null;
+ String identificationType = null;
+
+ //set empty AuthBlock BPK in case of OW or SSO or bpk is not requested
+ if (session.isOW() || session.isSsoRequested() || oaParam.isRemovePBKFromAuthBlock()) {
+ identificationType = "";
+ identificationValue = "";
+
+ } else if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) {
+
+ if (oaParam.getBusinessService()) {
+
+ String bpkBase64 = new BPKBuilder().buildWBPK(identityLink
+ .getIdentificationValue(), oaParam.getIdentityLinkDomainIdentifier());
+ identificationValue = bpkBase64;
+
+ if (oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_WBPK + "+"))
+ identificationType = oaParam.getIdentityLinkDomainIdentifier();
+ else
+ identificationType = Constants.URN_PREFIX_WBPK + "+" + oaParam.getIdentityLinkDomainIdentifier();
+
+ } else {
+ String bpkBase64 = new BPKBuilder().buildBPK(identityLink
+ .getIdentificationValue(), session.getTarget());
+ identificationValue = bpkBase64;
+ identificationType = Constants.URN_PREFIX_CDID + "+" + session.getTarget();
+ }
+
+
+ } else {
+ identificationValue = identityLink.getIdentificationValue();
+ identificationType = identityLink.getIdentificationType();
+
+ }
+
+ String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar
+ .getInstance());
+ session.setIssueInstant(issueInstant);
+ String authURL = session.getAuthURL();
+ String target = session.getTarget();
+ String targetFriendlyName = session.getTargetFriendlyName();
+
+ // Bug #485
+ // (https://egovlabs.gv.at/tracker/index.php?func=detail&aid=485&group_id=6&atid=105)
+ // String oaURL = session.getPublicOAURLPrefix();
+
+ List<ExtendedSAMLAttribute> extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH();
+
+
+ if (session.isSsoRequested()) {
+ String oaURL = new String();
+ try {
+ oaURL = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix().get(0);
+
+ if (MiscUtil.isNotEmpty(oaURL))
+ oaURL = oaURL.replaceAll("&", "&amp;");
+
+ } catch (ConfigurationException e) {
+ }
+ String authBlock = new AuthenticationBlockAssertionBuilder()
+ .buildAuthBlockSSO(issuer, issueInstant, authURL, target,
+ targetFriendlyName, identificationValue,
+ identificationType, oaURL, gebDat,
+ extendedSAMLAttributes, session, oaParam);
+ return authBlock;
+
+ } else {
+ String oaURL = session.getPublicOAURLPrefix().replaceAll("&", "&amp;");
+ String authBlock = new AuthenticationBlockAssertionBuilder()
+ .buildAuthBlock(issuer, issueInstant, authURL, target,
+ targetFriendlyName, identificationValue,
+ identificationType, oaURL, gebDat,
+ extendedSAMLAttributes, session, oaParam);
+ return authBlock;
+ }
+ }
+
+
+ /**
+ * Verifies the infoboxes (except of the identity link infobox) returned by
+ * the BKU by calling appropriate validator classes.
+ *
+ * @param session The actual authentication session.
+ * @param mandate The Mandate from the MIS
+ * @throws AuthenticationException
+ * @throws ConfigurationException
+ * @throws TransformerException
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ */
+ private void validateExtendedSAMLAttributeForMandates(
+ AuthenticationSession session, MISMandate mandate,
+ boolean business)
+ throws ValidateException, ConfigurationException, SAXException,
+ IOException, ParserConfigurationException, TransformerException {
+
+ ExtendedSAMLAttribute[] extendedSAMLAttributes = addExtendedSamlAttributes(
+ mandate, business, false);
+
+ int length = extendedSAMLAttributes.length;
+ for (int i = 0; i < length; i++) {
+ ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i];
+
+ verifySAMLAttribute(samlAttribute, i, "MISService",
+ "MISService");
+
+ }
+ }
+
+ /**
+ * Verifies the infoboxes (except of the identity link infobox) returned by
+ * the BKU by calling appropriate validator classes.
+ *
+ * @param session The actual authentication session.
+ * @param mandate The Mandate from the MIS
+ * @throws AuthenticationException
+ * @throws ConfigurationException
+ * @throws TransformerException
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ */
+ private void setExtendedSAMLAttributeForMandatesOID(
+ AuthenticationSession session, MISMandate mandate, boolean business)
+ throws ValidateException, ConfigurationException, SAXException,
+ IOException, ParserConfigurationException, TransformerException {
+
+ ExtendedSAMLAttribute[] extendedSamlAttributes = addExtendedSamlAttributesOID(
+ mandate, business);
+
+ AddAdditionalSAMLAttributes(session, extendedSamlAttributes,
+ "MISService", "MISService");
+
+ }
+
+ /**
+ * Adds given SAML Attributes to the current session. They will be appended
+ * to the final SAML Assertion or the AUTH block. If the attributes are
+ * already in the list, they will be replaced.
+ *
+ * @param session The current session
+ * @param extendedSAMLAttributes The SAML attributes to add
+ * @param identifier The infobox identifier for debug purposes
+ * @param friendlyNam The friendly name of the infobox for debug purposes
+ */
+ private static void AddAdditionalSAMLAttributes(
+ AuthenticationSession session,
+ ExtendedSAMLAttribute[] extendedSAMLAttributes, String identifier,
+ String friendlyName) throws ValidateException {
+ if (extendedSAMLAttributes == null)
+ return;
+ List<ExtendedSAMLAttribute> oaAttributes = session.getExtendedSAMLAttributesOA();
+ if (oaAttributes == null)
+ oaAttributes = new Vector<ExtendedSAMLAttribute>();
+ List<ExtendedSAMLAttribute> authAttributes = session.getExtendedSAMLAttributesAUTH();
+ if (authAttributes == null)
+ authAttributes = new Vector<ExtendedSAMLAttribute>();
+ int length = extendedSAMLAttributes.length;
+ for (int i = 0; i < length; i++) {
+ ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i];
+
+ Object value = verifySAMLAttribute(samlAttribute, i, identifier,
+ friendlyName);
+
+ if ((value instanceof String) || (value instanceof Element)) {
+ switch (samlAttribute.getAddToAUTHBlock()) {
+ case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY:
+ replaceExtendedSAMLAttribute(authAttributes, samlAttribute);
+ break;
+ case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK:
+ replaceExtendedSAMLAttribute(authAttributes, samlAttribute);
+ replaceExtendedSAMLAttribute(oaAttributes, samlAttribute);
+ break;
+ case ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK:
+ replaceExtendedSAMLAttribute(oaAttributes, samlAttribute);
+ break;
+ default:
+ Logger
+ .info("Invalid return value from method \"getAddToAUTHBlock()\" ("
+ + samlAttribute.getAddToAUTHBlock()
+ + ") in SAML attribute number "
+ + (i + 1)
+ + " for infobox " + identifier);
+ throw new ValidateException("validator.47", new Object[]{
+ friendlyName, String.valueOf((i + 1))});
+ }
+ } else {
+ Logger
+ .info("The type of SAML-Attribute number "
+ + (i + 1)
+ + " returned from "
+ + identifier
+ + "-infobox validator is not valid. Must be either \"java.Lang.String\""
+ + " or \"org.w3c.dom.Element\"");
+ throw new ValidateException("validator.46", new Object[]{
+ identifier, String.valueOf((i + 1))});
+ }
+ }
+ session.setExtendedSAMLAttributesAUTH(authAttributes);
+ session.setExtendedSAMLAttributesOA(oaAttributes);
+ }
+
+ /**
+ * Adds the AUTH block related SAML attributes to the validation result.
+ * This is needed always before the AUTH block is to be signed, because the
+ * name of the mandator has to be set
+ *
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ * @throws TransformerException
+ */
+
+ protected static ExtendedSAMLAttribute[] addExtendedSamlAttributes(
+ MISMandate mandate, boolean business, boolean provideStammzahl)
+ throws SAXException, IOException, ParserConfigurationException,
+ TransformerException {
+ Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>();
+
+ extendedSamlAttributes.clear();
+
+ // Name
+ Element domMandate = mandateToElement(mandate);
+ Element nameSpaceNode = domMandate.getOwnerDocument().createElement(
+ "NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX,
+ Constants.PD_NS_URI);
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX,
+ SZRGWConstants.MANDATE_NS);
+
+ Element mandator = (Element) XPathAPI.selectSingleNode(domMandate,
+ "//md:Mandate/md:Mandator", nameSpaceNode);
+
+ // Mandate
+ extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl(
+ EXT_SAML_MANDATE_RAW, domMandate,
+ SZRGWConstants.MANDATE_NS,
+ ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK));
+
+ // (w)bpk
+ String wbpk = ParepUtils.extractMandatorWbpk(mandator);
+ if (!ParepUtils.isEmpty(wbpk)) {
+ if (!ParepUtils.isPhysicalPerson(mandator)) {
+ String idType = ParepUtils
+ .extractMandatorIdentificationType(mandator);
+ if (!ParepUtils.isEmpty(idType)
+ && idType.startsWith(Constants.URN_PREFIX_BASEID)) {
+ extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl(
+ EXT_SAML_MANDATE_CB_BASE_ID,
+ ParepUtils.getRegisterString(idType) + ": " + wbpk,
+ SZRGWConstants.MANDATE_NS,
+ ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY));
+ }
+ } else if (business) {
+ extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl(
+ EXT_SAML_MANDATE_WBPK, wbpk,
+ SZRGWConstants.MANDATE_NS,
+ ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY));
+ }
+ }
+
+ ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes
+ .size()];
+ extendedSamlAttributes.copyInto(ret);
+ Logger.debug("ExtendedSAML Attributes: " + ret.length);
+ return ret;
+
+ }
+
+ /**
+ * Adds the AUTH block related SAML attributes to the validation result.
+ * This is needed always before the AUTH block is to be signed, because the
+ * name of the mandator has to be set
+ *
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ * @throws TransformerException
+ */
+ private static ExtendedSAMLAttribute[] addExtendedSamlAttributesOID(
+ MISMandate mandate, boolean business) throws SAXException,
+ IOException, ParserConfigurationException, TransformerException {
+
+ Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>();
+
+ extendedSamlAttributes.clear();
+
+ // RepresentationType
+ extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl(
+ EXT_SAML_MANDATE_REPRESENTATIONTYPE,
+ EXT_SAML_MANDATE_REPRESENTATIONTEXT,
+ SZRGWConstants.MANDATE_NS,
+ ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK));
+
+ String oid = mandate.getProfRep();
+
+ if (oid != null) {
+ extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl(
+ EXT_SAML_MANDATE_OID, oid,
+ SZRGWConstants.MANDATE_NS,
+ ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK));
+ String oidDescription = mandate.getTextualDescriptionOfOID();
+ extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl(
+ EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION,
+ oidDescription, SZRGWConstants.MANDATE_NS,
+ ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK));
+
+ }
+
+ ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes
+ .size()];
+ extendedSamlAttributes.copyInto(ret);
+ Logger.debug("ExtendedSAML Attributes: " + ret.length);
+ return ret;
+
+ }
+
+ /**
+ * @param mandate
+ * @return
+ * @throws ParserConfigurationException
+ * @throws IOException
+ * @throws SAXException
+ */
+ private static Element mandateToElement(MISMandate mandate)
+ throws SAXException, IOException, ParserConfigurationException {
+ ByteArrayInputStream bais = new ByteArrayInputStream(mandate
+ .getMandate());
+ Document doc = DOMUtils.parseDocumentSimple(bais);
+ bais.close();
+ return doc.getDocumentElement();
+ }
+
+ protected static void replaceExtendedSAMLAttribute(List<ExtendedSAMLAttribute> attributes,
+ ExtendedSAMLAttribute samlAttribute) {
+ if (null == attributes) {
+ attributes = new Vector<ExtendedSAMLAttribute>();
+ } else {
+ String id = samlAttribute.getName();
+ int length = attributes.size();
+ for (int i = 0; i < length; i++) {
+ ExtendedSAMLAttribute att = (ExtendedSAMLAttribute) attributes
+ .get(i);
+ if (id.equals(att.getName())) {
+ // replace attribute
+ attributes.set(i, samlAttribute);
+ return;
+ }
+ }
+ attributes.add(samlAttribute);
+ }
+ }
+
+ /**
+ * Processes a <code>&lt;CreateXMLSignatureResponse&gt;</code> sent by the
+ * security layer implementation.<br>
+ * <ul>
+ * <li>Validates given <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
+ * <li>Parses <code>&lt;CreateXMLSignatureResponse&gt;</code> for error
+ * codes</li>
+ * <li>Parses authentication block enclosed in
+ * <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
+ * <li>Verifies authentication block by calling the MOA SP component</li>
+ * <li>Creates authentication data</li>
+ * <li>Creates a corresponding SAML artifact</li>
+ * <li>Stores authentication data in the authentication data store indexed
+ * by the SAML artifact</li>
+ * <li>Deletes authentication session</li>
+ * <li><strike>Returns the SAML artifact, encoded BASE64</strike><br/>New id of the authenticated MOA session or {@code null} in case of mandate mode (???)</li>
+ * </ul>
+ * @param pendingReq
+ *
+ * @param sessionID session ID of the running authentication session
+ * @param xmlCreateXMLSignatureReadResponse String representation of the
+ * <code>&lt;CreateXMLSignatureResponse&gt;</code>
+ * @return <strike>SAML artifact needed for retrieving authentication data, encoded
+ * BASE64</strike><br/>New id of the authenticated MOA session or {@code null} in case of mandate mode (???)
+ * @throws BKUException
+ */
+ public void verifyAuthenticationBlock(IRequest pendingReq, AuthenticationSession session,
+ String xmlCreateXMLSignatureReadResponse)
+ throws AuthenticationException, BuildException, ParseException,
+ ConfigurationException, ServiceException, ValidateException, BKUException {
+
+ if (session == null)
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID});
+ if (isEmpty(xmlCreateXMLSignatureReadResponse))
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE});
+
+ AuthConfiguration authConf = AuthConfigurationProviderFactory
+ .getInstance();
+ // parses <CreateXMLSignatureResponse>
+ CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser(
+ xmlCreateXMLSignatureReadResponse).parseResponse();
+
+ try {
+ String serializedAssertion = DOMUtils.serializeNode(csresp
+ .getSamlAssertion());
+ 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});
+ }
+ // validates <CreateXMLSignatureResponse>
+ if (session.isSsoRequested())
+ new CreateXMLSignatureResponseValidator().validateSSO(csresp, session);
+ else
+ new CreateXMLSignatureResponseValidator().validate(csresp, session);
+
+ // builds a <VerifyXMLSignatureRequest> for a MOA-SPSS call
+ List<String> vtids = authConf.getMoaSpAuthBlockVerifyTransformsInfoIDs();
+ String tpid = authConf.getMoaSpAuthBlockTrustProfileID(pendingReq.getOnlineApplicationConfiguration().isUseAuthBlockTestTestStore());
+ Element domVsreq = new VerifyXMLSignatureRequestBuilder().build(csresp,
+ vtids, tpid);
+ // debug output
+
+ Element domVsresp = null;
+
+ // try {
+ // invokes the call
+ domVsresp = new SignatureVerificationInvoker()
+ .verifyXMLSignature(domVsreq);
+
+ // parses the <VerifyXMLSignatureResponse>
+ VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponseParser(
+ domVsresp).parseData();
+
+ if (Logger.isTraceEnabled()) {
+ if (domVsresp != null) {
+ try {
+ String xmlVerifyXMLSignatureResponse = DOMUtils
+ .serializeNode(domVsresp, true);
+ Logger.trace(new LogMsg(xmlCreateXMLSignatureReadResponse));
+ Logger.trace(new LogMsg(xmlVerifyXMLSignatureResponse));
+ } catch (Throwable t) {
+ t.printStackTrace();
+ Logger.info(new LogMsg(t.getStackTrace()));
+ }
+ }
+ }
+
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+
+ // validates the <VerifyXMLSignatureResponse>
+ VerifyXMLSignatureResponseValidator.getInstance().validate(vsresp,
+ null, VerifyXMLSignatureResponseValidator.CHECK_AUTH_BLOCK,
+ oaParam);
+
+ // Compare AuthBlock Data with information stored in session, especially
+ // date and time
+ CreateXMLSignatureResponseValidator.getInstance().validateSigningDateTime(csresp);
+
+ try {
+ // compares the public keys from the identityLink with the AuthBlock
+ VerifyXMLSignatureResponseValidator.getInstance().validateCertificate(
+ vsresp, session.getIdentityLink());
+
+ } catch ( ValidateException e) {
+ Logger.error("Signature verification error. ", e);
+ Logger.error("Signed Data: " + session.getAuthBlock());
+ try {
+ Logger.error("VerifyRequest: " + DOMUtils.serializeNode(domVsreq));
+ Logger.error("VerifyResponse: " + DOMUtils.serializeNode(domVsresp));
+ } catch (TransformerException e1) {
+ e1.printStackTrace();
+
+ } catch (IOException e1) {
+ e1.printStackTrace();
+
+ }
+
+ throw e;
+ }
+
+ session.setXMLVerifySignatureResponse(vsresp);
+ session.setSignerCertificate(vsresp.getX509certificate());
+ vsresp.setX509certificate(null);
+ session.setForeigner(false);
+
+ //set QAA Level four in case of card authentifcation
+ session.setQAALevel(PVPConstants.STORK_QAA_1_4);
+
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_AUTHBLOCK_VALIDATED);
+
+ MOAReversionLogger.getInstance().logPersonalInformationEvent(pendingReq, session.getIdentityLink()
+ );
+ }
+
+ /**
+ * Processes a <code>&lt;CreateXMLSignatureResponse&gt;</code> sent by the
+ * security layer implementation.<br>
+ * <ul>
+ * <li>Validates given <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
+ * <li>Parses <code>&lt;CreateXMLSignatureResponse&gt;</code> for error
+ * codes</li>
+ * <li>Parses authentication block enclosed in
+ * <code>&lt;CreateXMLSignatureResponse&gt;</code></li>
+ * <li>Verifies authentication block by calling the MOA SP component</li>
+ * <li>Creates authentication data</li>
+ * <li>Creates a corresponding SAML artifact</li>
+ * <li>Stores authentication data in the authentication data store indexed
+ * by the SAML artifact</li>
+ * <li>Deletes authentication session</li>
+ * <li>Returns the SAML artifact, encoded BASE64</li>
+ * </ul>
+ *
+ * @param sessionID session ID of the running authentication session
+ * @param xmlCreateXMLSignatureReadResponse String representation of the
+ * <code>&lt;CreateXMLSignatureResponse&gt;</code>
+ * @return SAML artifact needed for retrieving authentication data, encoded
+ * BASE64
+ */
+
+ protected Element createIdentificationBPK(Element mandatePerson,
+ String baseid, String target) throws BuildException {
+ Element identificationBpK = mandatePerson.getOwnerDocument()
+ .createElementNS(Constants.PD_NS_URI, "Identification");
+ Element valueBpK = mandatePerson.getOwnerDocument().createElementNS(
+ Constants.PD_NS_URI, "Value");
+
+ String bpkBase64 = new BPKBuilder().buildBPK(baseid, target);
+ valueBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode(
+ bpkBase64));
+ Element typeBpK = mandatePerson.getOwnerDocument().createElementNS(
+ Constants.PD_NS_URI, "Type");
+ typeBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode(
+ "urn:publicid:gv.at:cdid+bpk"));
+ identificationBpK.appendChild(valueBpK);
+ identificationBpK.appendChild(typeBpK);
+
+ return identificationBpK;
+
+ }
+
+ protected String getBaseId(Element mandatePerson)
+ throws TransformerException, IOException {
+ NodeList list = mandatePerson.getElementsByTagNameNS(
+ Constants.PD_NS_URI, "Identification");
+ for (int i = 0; i < list.getLength(); i++) {
+ Element identification = (Element) list.item(i);
+ Element type = (Element) identification.getElementsByTagNameNS(
+ Constants.PD_NS_URI, "Type").item(0);
+ if (type.getTextContent().compareToIgnoreCase(
+ "urn:publicid:gv.at:baseid") == 0) {
+ Element value = (Element) identification
+ .getElementsByTagNameNS(Constants.PD_NS_URI, "Value")
+ .item(0);
+ return value.getTextContent();
+ }
+ }
+ return null;
+
+ }
+
+ /**
+ * Gets the foreign authentication data.<br>
+ * <ul>
+ * <li><strong>Creates authentication data</strong></li>
+ * <li>Creates a corresponding SAML artifact</li>
+ * <li>Stores authentication data in the authentication data store indexed
+ * by the SAML artifact</li>
+ * <li>Deletes authentication session</li>
+ * <li><strike>Returns the SAML artifact, encoded BASE64</strike></li>
+ * </ul>
+ *
+ * @param sessionID session ID of the running authentication session
+ * @return String "new Session"
+ */
+ public void getForeignAuthenticationData(AuthenticationSession session)
+ throws AuthenticationException, BuildException, ParseException,
+ ConfigurationException, ServiceException, ValidateException {
+
+ if (session == null)
+ throw new AuthenticationException("auth.10", new Object[]{
+ REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID});
+ VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponse();
+ X509Certificate cert = session.getSignerCertificate();
+ vsresp.setX509certificate(cert);
+
+ session.setXMLVerifySignatureResponse(vsresp);
+ session.setSignerCertificate(vsresp.getX509certificate());
+ vsresp.setX509certificate(null);
+ session.setForeigner(true);
+ }
+
+ /**
+ * Checks a parameter.
+ *
+ * @param param parameter
+ * @return true if the parameter is null or empty
+ */
+ private boolean isEmpty(String param) {
+ return param == null || param.length() == 0;
+ }
+
+ /**
+ * Checks the correctness of SAML attributes and returns its value.
+ *
+ * @param param samlAttribute
+ * @param i the number of the verified attribute for messages
+ * @param identifier the infobox identifier for messages
+ * @param friendlyname the friendly name of the infobox for messages
+ * @return the SAML attribute value (Element or String)
+ */
+ protected static Object verifySAMLAttribute(
+ ExtendedSAMLAttribute samlAttribute, int i, String identifier,
+ String friendlyName) throws ValidateException {
+ String name = samlAttribute.getName();
+
+ if (name == null) {
+ Logger.info("The name of SAML-Attribute number " + (i + 1)
+ + " returned from " + identifier
+ + "-infobox validator is null.");
+ throw new ValidateException("validator.45", new Object[]{
+ friendlyName, "Name", String.valueOf((i + 1)), "null"});
+ }
+ if (name == "") {
+ Logger.info("The name of SAML-Attribute number " + (i + 1)
+ + " returned from " + identifier
+ + "-infobox validator is empty.");
+ throw new ValidateException("validator.45", new Object[]{
+ friendlyName, "Name", String.valueOf((i + 1)), "leer"});
+ }
+ if (samlAttribute.getNameSpace() == null) {
+ Logger.info("The namespace of SAML-Attribute number " + (i + 1)
+ + " returned from " + identifier
+ + "-infobox validator is null.");
+ throw new ValidateException("validator.45",
+ new Object[]{friendlyName, "Namespace",
+ String.valueOf((i + 1)), "null"});
+ }
+ Object value = samlAttribute.getValue();
+ if (value == null) {
+ Logger.info("The value of SAML-Attribute number " + (i + 1)
+ + " returned from " + identifier
+ + "-infobox validator is null.");
+ throw new ValidateException("validator.45", new Object[]{
+ friendlyName, "Wert", String.valueOf((i + 1)), "null"});
+ }
+
+ return value;
+ }
+
+ /**
+ * Extracts an X509 Certificate out of an XML signagture element
+ *
+ * @param signedXML XML signature element
+ * @return X509Certificate
+ * @throws CertificateException
+ */
+ public static X509Certificate getCertificateFromXML(Element signedXML) throws CertificateException {
+
+ NodeList nList = signedXML.getElementsByTagNameNS(Constants.DSIG_NS_URI, "X509Certificate");
+
+ String base64CertString = XMLUtil.getFirstTextValueFromNodeList(nList);
+
+ if (StringUtils.isEmpty(base64CertString)) {
+ String msg = "XML does not contain a X509Certificate element.";
+ Logger.error(msg);
+ throw new CertificateException(msg);
+ }
+
+ InputStream is = new ByteArrayInputStream(Base64.decode(base64CertString));
+
+ X509Certificate cert;
+ try {
+ cert = new X509Certificate(is);
+ return cert;
+
+ } 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/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationAssertionBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationAssertionBuilder.java
new file mode 100644
index 000000000..89f42ab7d
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationAssertionBuilder.java
@@ -0,0 +1,125 @@
+/*******************************************************************************
+ * 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.builder;
+
+import java.io.IOException;
+import java.text.MessageFormat;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.xml.transform.TransformerException;
+
+import org.w3c.dom.Element;
+
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.StringUtils;
+
+/**
+ * Base class for building authentication the AUTHBlock and final OA data SAML assertions.
+ * Encapsulates methods used by the two specific builders
+ * {@link at.gv.egovernment.moa.id.auth.builder.AuthenticationBlockAssertionBuilder AuthenticationBlockAssertionBuilder}
+ * and
+ * {@link at.gv.egovernment.moa.id.auth.builder.AuthenticationDataAssertionBuilder AuthenticationDataAssertionBuilder}
+ *
+ * @author Harald Bratko
+ */
+public class AuthenticationAssertionBuilder {
+
+ /** the NewLine representation in Java*/
+ protected static String NL = "\n";
+
+ protected static String SAML_ATTRIBUTE =
+ " <saml:Attribute AttributeName=''{0}'' AttributeNamespace=''{1}''>" + NL +
+ " <saml:AttributeValue>{2}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>"+ NL;
+
+ protected static String SAML_ATTRIBUTE_NO_NAMESPACE =
+ " <saml:Attribute AttributeName=''{0}''>" + NL +
+ " <saml:AttributeValue>{1}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>"+ NL;
+
+ /**
+ * Empty constructor
+ */
+ public AuthenticationAssertionBuilder() {
+ }
+
+ /**
+ * Builds the SAML attributes to be appended to the AUTHBlock or to the SAML assertion
+ * delivered to the online application.
+ * The method traverses through the list of given SAML attribute objects and builds an
+ * XML structure (String representation) for each of the attributes.
+ *
+ * @param extendedSAMLAttributes The SAML attributes to be appended to the AUTHBlock or
+ * to the SAML assertion delivered to the online application.
+ * @return A string representation including the XML structures of
+ * the SAML attributes.
+ *
+ * @throws ParseException If an error occurs on serializing an SAML attribute.
+ */
+ protected String buildExtendedSAMLAttributes(List<ExtendedSAMLAttribute> extendedSAMLAttributes) throws ParseException
+ {
+ StringBuffer sb = new StringBuffer();
+ if (extendedSAMLAttributes!=null) {
+ Iterator<ExtendedSAMLAttribute> it = extendedSAMLAttributes.iterator();
+ while (it.hasNext()) {
+ ExtendedSAMLAttribute extendedSAMLAttribute = (ExtendedSAMLAttribute)it.next();
+ Object value = extendedSAMLAttribute.getValue();
+ String name = extendedSAMLAttribute.getName();
+ String namespace = extendedSAMLAttribute.getNameSpace();
+ if (value instanceof String) {
+ sb.append(MessageFormat.format( SAML_ATTRIBUTE, new Object[] {name, namespace, value}));
+
+ } else if (value instanceof List<?>) {
+ if (!((List<?>)value).isEmpty()) {
+ Object firstEl = ((List<?>)value).get(0);
+ if (firstEl instanceof String) {
+ sb.append(MessageFormat.format( SAML_ATTRIBUTE, new Object[] {name, namespace, ((String)firstEl)}));
+ }
+ }
+
+ } else if (value instanceof Element) {
+ try {
+ String serializedValue = DOMUtils.serializeNode((Element)(value));
+ serializedValue = StringUtils.removeXMLDeclaration(serializedValue);
+ sb.append(MessageFormat.format( SAML_ATTRIBUTE, new Object[] {name, namespace, serializedValue}));
+ } catch (TransformerException e) {
+ Logger.error("Error on serializing SAML attribute \"" + name +
+ " (namespace: \"" + namespace + "\".");
+ throw new ParseException("parser.05", new Object[] { name, namespace});
+ } catch (IOException e) {
+ Logger.error("Error on serializing SAML attribute \"" + name +
+ " (namespace: \"" + namespace + "\".");
+ throw new ParseException("parser.05", new Object[] { name, namespace});
+ }
+ }
+ }
+ }
+ return sb.toString();
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java
new file mode 100644
index 000000000..760d28d5b
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java
@@ -0,0 +1,584 @@
+/*******************************************************************************
+ * 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.builder;
+
+import java.io.StringWriter;
+import java.text.MessageFormat;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.List;
+
+import javax.xml.bind.DatatypeConverter;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttributeImpl;
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.util.Random;
+import at.gv.egovernment.moa.logging.Logger;
+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;
+
+/**
+ * Builder for the authentication block <code>&lt;saml:Assertion&gt;</code>
+ * to be included in a <code>&lt;CreateXMLSignatureResponse&gt;</code>.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class AuthenticationBlockAssertionBuilder extends AuthenticationAssertionBuilder implements Constants {
+
+ /** template for the Auth-Block */
+ private static String AUTH_BLOCK =
+ "<saml:Assertion xmlns:saml=''" + SAML_NS_URI + "''{0} MajorVersion=''1'' MinorVersion=''0'' AssertionID=''any'' Issuer=''{1}'' IssueInstant=''{2}''>" + NL +
+ " <saml:AttributeStatement>" + NL +
+ " <saml:Subject>" + NL +
+ " <saml:NameIdentifier>{3}</saml:NameIdentifier>" + NL +
+ " </saml:Subject>" + NL +
+ "{4}" +
+ " <saml:Attribute AttributeName=''OA'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{5}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''Geburtsdatum'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{6}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ "{7}" +
+ "{8}" +
+ "{9}" +
+ " </saml:AttributeStatement>" + NL +
+ "</saml:Assertion>";
+
+ private static String GESCHAEFTS_BEREICH_ATTRIBUTE =
+ " <saml:Attribute AttributeName=''Geschaeftsbereich'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{0}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL;
+
+ private static String WBPK_ATTRIBUTE =
+ " <saml:Attribute AttributeName=''wbPK'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>" + NL +
+ " <pr:Identification>" + NL +
+ " <pr:Value>{0}</pr:Value>" + NL +
+ " <pr:Type>{1}</pr:Type>" + NL +
+ " </pr:Identification>" + NL +
+ " </saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL;
+
+ private static String SPECIAL_TEXT_ATTRIBUTE =
+ " <saml:Attribute AttributeName=''SpecialText'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{0}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL;
+
+ private static String AUTHBLOCKTOKKEN_ATTRIBUTE =
+ " <saml:Attribute AttributeName=''UniqueTokken'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{0}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL;
+
+
+ private static String PR_IDENTIFICATION_ATTRIBUTE =
+ " <pr:Identification xmlns:pr=\"" + PD_NS_URI + "\">" + NL +
+ " <pr:Value>{0}</pr:Value>" + NL +
+ " <pr:Type>{1}</pr:Type>" + NL +
+ " </pr:Identification>" + NL;
+
+ /**
+ * The number of SAML attributes included in this AUTH-Block (without the extended SAML attributes).
+ */
+ public static final int NUM_OF_SAML_ATTRIBUTES = 5;
+ public static final int NUM_OF_SAML_ATTRIBUTES_SSO = 4;
+
+ /**
+ * Constructor for AuthenticationBlockAssertionBuilder.
+ */
+ public AuthenticationBlockAssertionBuilder() {
+ super();
+ }
+
+ /**
+ * Builds the authentication block <code>&lt;saml:Assertion&gt;</code>
+ *
+ * @param issuer authentication block issuer; <code>"GivenName FamilyName"</code>
+ * @param issueInstant current timestamp
+ * @param authURL URL of MOA-ID authentication component
+ * @param target "Gesch&auml;ftsbereich"; maybe <code>null</code> if the application
+ * is a business application
+ * @param identityLinkValue the content of the <code>&lt;pr:Value&gt;</code>
+ * child element of the <code>&lt;pr:Identification&gt;</code>
+ * element derived from the Identitylink; this is the
+ * value of the <code>wbPK</code>;
+ * maybe <code>null</code> if the application is a public service
+ * @param identityLinkType the content of the <code>&lt;pr:Type&gt;</code>
+ * child element of the <code>&lt;pr:Identification&gt;</code>
+ * element derived from the Identitylink; this includes the
+ * URN prefix and the identification number of the business
+ * application used as input for wbPK computation;
+ * maybe <code>null</code> if the application is a public service
+ * @param oaURL public URL of online application requested
+ * @param gebDat The date of birth from the identity link.
+ * @param extendedSAMLAttributes The SAML attributes to be appended to the AUTHBlock.
+ *
+ * @return String representation of authentication block
+ * <code>&lt;saml:Assertion&gt;</code> built
+ *
+ * @throws BuildException If an error occurs on serializing an extended SAML attribute
+ * to be appended to the AUTH-Block.
+ */
+ public String buildAuthBlock(
+ String issuer,
+ String issueInstant,
+ String authURL,
+ String target,
+ String targetFriendlyName,
+ String identityLinkValue,
+ String identityLinkType,
+ String oaURL,
+ String gebDat,
+ List<ExtendedSAMLAttribute> extendedSAMLAttributes,
+ AuthenticationSession session,
+ OAAuthParameter oaParam)
+ throws BuildException
+
+ {
+ session.setSAMLAttributeGebeORwbpk(true);
+ String gebeORwbpk = "";
+ String wbpkNSDeclaration = "";
+
+ if (target == null) {
+
+ // OA is a business application
+ if (!Constants.URN_PREFIX_HPI.equals(identityLinkType)) {
+ // Only add wbPKs to AUTH-Block. HPIs can be added to the AUTH-Block by the corresponding Validator
+ gebeORwbpk = MessageFormat.format(WBPK_ATTRIBUTE, new Object[] { identityLinkValue, identityLinkType });
+ wbpkNSDeclaration = " xmlns:pr=\"" + PD_NS_URI + "\"";
+
+ //adding type of wbPK domain identifier
+ ExtendedSAMLAttribute idLinkDomainIdentifierTypeAttribute =
+ new ExtendedSAMLAttributeImpl("IdentityLinkDomainIdentifierType", oaParam.getIdentityLinkDomainIdentifierType(), Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY);
+
+ extendedSAMLAttributes.add(idLinkDomainIdentifierTypeAttribute);
+
+ } else {
+ // We do not have a wbPK, therefore no SAML-Attribute is provided
+ session.setSAMLAttributeGebeORwbpk(false);
+ }
+
+ } else {
+ // OA is a govermental application
+ String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(target);
+ if (StringUtils.isEmpty(sectorName)) {
+ if (targetFriendlyName != null)
+ sectorName = targetFriendlyName;
+ }
+
+
+ //gebeORwbpk = MessageFormat.format(GESCHAEFTS_BEREICH_ATTRIBUTE, new Object[] { target });
+ gebeORwbpk = MessageFormat.format(GESCHAEFTS_BEREICH_ATTRIBUTE, new Object[] { target + " (" + sectorName + ")" });
+
+ //no business service, adding bPK
+
+ if (identityLinkValue != null) {
+ Element bpkSamlValueElement;
+ try {
+ bpkSamlValueElement = DOMUtils.parseDocument(MessageFormat.format(PR_IDENTIFICATION_ATTRIBUTE, new Object[] { identityLinkValue, Constants.URN_PREFIX_BPK }), false, null, null).getDocumentElement();
+ } catch (Exception e) {
+ Logger.error("Error on building AUTH-Block: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()});
+ }
+
+ // String s = xmlToString(bpkSamlValueElement);
+ // System.out.println("bpkSamlValueElement: " + s);
+
+ ExtendedSAMLAttribute bpkAttribute =
+ new ExtendedSAMLAttributeImpl("bPK", bpkSamlValueElement, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY);
+ extendedSAMLAttributes.add(bpkAttribute);
+ }
+
+ boolean useMandate = session.getUseMandate();
+ if (useMandate) {
+ String mandateReferenceValue = Random.nextRandom();
+ // remove leading "-"
+ if (mandateReferenceValue.startsWith("-"))
+ mandateReferenceValue = mandateReferenceValue.substring(1);
+
+ session.setMandateReferenceValue(mandateReferenceValue);
+
+ ExtendedSAMLAttribute mandateReferenceValueAttribute =
+ new ExtendedSAMLAttributeImpl("mandateReferenceValue", mandateReferenceValue, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK);
+
+ extendedSAMLAttributes.add(mandateReferenceValueAttribute);
+ }
+
+
+
+ //gebeORwbpk = gebeORwbpk + MessageFormat.format(BPK_ATTRIBUTE, new Object[] { identityLinkValue, identityLinkType });
+ wbpkNSDeclaration = " xmlns:pr=\"" + PD_NS_URI + "\"";
+ }
+
+ //adding friendly name of OA
+ String oaFriendlyName = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "" : oaParam.getFriendlyName();
+
+ ExtendedSAMLAttribute oaFriendlyNameAttribute =
+ new ExtendedSAMLAttributeImpl("oaFriendlyName", oaFriendlyName, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY);
+
+ extendedSAMLAttributes.add(oaFriendlyNameAttribute);
+
+
+ String text = "";
+ try {
+ OAAuthParameter oaparam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+ if (MiscUtil.isNotEmpty(oaparam.getAditionalAuthBlockText())) {
+ Logger.debug("Use addional AuthBlock Text from OA=" + oaparam.getPublicURLPrefix());
+ text = oaparam.getAditionalAuthBlockText();
+ }
+
+ } catch (ConfigurationException e) {
+ Logger.warn("Addional AuthBlock Text can not loaded from OA!", e);
+ }
+
+ String specialText = MessageFormat.format(SPECIAL_TEXT_ATTRIBUTE,
+ new Object[] { generateSpecialText(text, issuer, gebDat, issueInstant) });
+
+ //generate unique AuthBlock tokken
+ String uniquetokken = Random.nextRandom();
+ session.setAuthBlockTokken(uniquetokken);
+
+ String assertion;
+ try {
+ assertion = MessageFormat.format(
+ AUTH_BLOCK, new Object[] {
+ wbpkNSDeclaration,
+ issuer,
+ issueInstant,
+ authURL,
+ gebeORwbpk,
+ oaURL,
+ gebDat,
+ specialText,
+ MessageFormat.format(AUTHBLOCKTOKKEN_ATTRIBUTE,
+ new Object[] { uniquetokken }),
+ buildExtendedSAMLAttributes(extendedSAMLAttributes)});
+ } catch (ParseException e) {
+ Logger.error("Error on building AUTH-Block: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()});
+ }
+
+ return assertion;
+
+ }
+
+ /**
+ * Builds the authentication block <code>&lt;saml:Assertion&gt;</code>
+ *
+ * @param issuer authentication block issuer; <code>"GivenName FamilyName"</code>
+ * @param issueInstant current timestamp
+ * @param authURL URL of MOA-ID authentication component
+ * @param target "Gesch&auml;ftsbereich"; maybe <code>null</code> if the application
+ * is a business application
+ * @param identityLinkValue the content of the <code>&lt;pr:Value&gt;</code>
+ * child element of the <code>&lt;pr:Identification&gt;</code>
+ * element derived from the Identitylink; this is the
+ * value of the <code>wbPK</code>;
+ * maybe <code>null</code> if the application is a public service
+ * @param identityLinkType the content of the <code>&lt;pr:Type&gt;</code>
+ * child element of the <code>&lt;pr:Identification&gt;</code>
+ * element derived from the Identitylink; this includes the
+ * URN prefix and the identification number of the business
+ * application used as input for wbPK computation;
+ * maybe <code>null</code> if the application is a public service
+ * @param oaURL public URL of online application requested
+ * @param gebDat The date of birth from the identity link.
+ * @param extendedSAMLAttributes The SAML attributes to be appended to the AUTHBlock.
+ *
+ * @return String representation of authentication block
+ * <code>&lt;saml:Assertion&gt;</code> built
+ *
+ * @throws BuildException If an error occurs on serializing an extended SAML attribute
+ * to be appended to the AUTH-Block.
+ */
+ public String buildAuthBlockForeignID(
+ String issuer,
+ String issueInstant,
+ String authURL,
+ String target,
+ String identityLinkValue,
+ String identityLinkType,
+ String oaURL,
+ String gebDat,
+ List<ExtendedSAMLAttribute> extendedSAMLAttributes,
+ AuthenticationSession session)
+ throws BuildException
+ {
+ session.setSAMLAttributeGebeORwbpk(true);
+ String gebeORwbpk = "";
+ String wbpkNSDeclaration = "";
+
+ //BZ.., reading OA parameters
+ OAAuthParameter oaParam;
+ try {
+ oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(
+ session.getPublicOAURLPrefix());
+ } catch (ConfigurationException e) {
+ Logger.error("Error on building AUTH-Block: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()});
+ }
+ //..BZ
+
+
+ if (target == null) {
+ // OA is a business application
+ if (!Constants.URN_PREFIX_HPI.equals(identityLinkType)) {
+ // Only add wbPKs to AUTH-Block. HPIs can be added to the AUTH-Block by the corresponding Validator
+ gebeORwbpk = MessageFormat.format(WBPK_ATTRIBUTE, new Object[] { identityLinkValue, identityLinkType });
+ wbpkNSDeclaration = " xmlns:pr=\"" + PD_NS_URI + "\"";
+
+ //BZ.., adding type of wbPK domain identifier
+ ExtendedSAMLAttribute idLinkDomainIdentifierTypeAttribute =
+ new ExtendedSAMLAttributeImpl("IdentityLinkDomainIdentifierType", oaParam.getIdentityLinkDomainIdentifierType(), Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY);
+
+ extendedSAMLAttributes.add(idLinkDomainIdentifierTypeAttribute);
+ //..BZ
+
+ } else {
+ // We do not have a wbPK, therefore no SAML-Attribute is provided
+ session.setSAMLAttributeGebeORwbpk(false);
+ }
+ } else {
+ // OA is a govermental application
+ //BZ..
+ String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(target);
+ //gebeORwbpk = MessageFormat.format(GESCHAEFTS_BEREICH_ATTRIBUTE, new Object[] { target });
+ gebeORwbpk = MessageFormat.format(GESCHAEFTS_BEREICH_ATTRIBUTE, new Object[] { target + " (" + sectorName + ")" });
+ //..BZ
+
+ //BZ.., no business service, adding bPK
+
+ Element bpkSamlValueElement;
+ try {
+ bpkSamlValueElement = DOMUtils.parseDocument(MessageFormat.format(PR_IDENTIFICATION_ATTRIBUTE, new Object[] { identityLinkValue, Constants.URN_PREFIX_BPK }), false, null, null).getDocumentElement();
+ } catch (Exception e) {
+ Logger.error("Error on building AUTH-Block: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()});
+ }
+
+ ExtendedSAMLAttribute bpkAttribute =
+ new ExtendedSAMLAttributeImpl("bPK", bpkSamlValueElement, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY);
+
+ extendedSAMLAttributes.add(bpkAttribute);
+ //gebeORwbpk = gebeORwbpk + MessageFormat.format(BPK_ATTRIBUTE, new Object[] { identityLinkValue, identityLinkType });
+ wbpkNSDeclaration = " xmlns:pr=\"" + PD_NS_URI + "\"";
+ //..BZ
+ }
+
+ //BZ.., adding friendly name of OA
+ String oaFriendlyName = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "" : oaParam.getFriendlyName();
+
+ ExtendedSAMLAttribute oaFriendlyNameAttribute =
+ new ExtendedSAMLAttributeImpl("oaFriendlyName", oaFriendlyName, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY);
+
+ extendedSAMLAttributes.add(oaFriendlyNameAttribute);
+ //..BZ
+
+ String text = "";
+ try {
+ OAAuthParameter oaparam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+ if (MiscUtil.isNotEmpty(oaparam.getAditionalAuthBlockText())) {
+ Logger.debug("Use addional AuthBlock Text from OA=" + oaparam.getPublicURLPrefix());
+ text = oaparam.getAditionalAuthBlockText();
+ }
+ } catch (ConfigurationException e) {
+ Logger.warn("Addional AuthBlock Text can not loaded from OA!", e);
+ }
+
+ String specialText = MessageFormat.format(SPECIAL_TEXT_ATTRIBUTE,
+ new Object[] { generateSpecialText(text, issuer, gebDat, issueInstant) });
+
+ //generate unique AuthBlock tokken
+ String uniquetokken = Random.nextRandom();
+ session.setAuthBlockTokken(uniquetokken);
+
+ String assertion;
+ try {
+ assertion = MessageFormat.format(
+ AUTH_BLOCK, new Object[] {
+ wbpkNSDeclaration,
+ issuer,
+ issueInstant,
+ authURL,
+ gebeORwbpk,
+ oaURL,
+ gebDat,
+ specialText,
+ MessageFormat.format(AUTHBLOCKTOKKEN_ATTRIBUTE,
+ new Object[] { uniquetokken }),
+ buildExtendedSAMLAttributes(extendedSAMLAttributes)});
+ } catch (ParseException e) {
+ Logger.error("Error on building AUTH-Block: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()});
+ }
+
+ return assertion;
+
+ }
+
+ public static String generateSpecialText(String inputtext, String issuer, String gebDat, String issueInstant) {
+ Calendar datetime = DatatypeConverter.parseDateTime(issueInstant);
+ SimpleDateFormat dateformat = new SimpleDateFormat("dd.MM.yyyy");
+ SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm:ss");
+
+ String text = inputtext.replaceAll("#NAME#", issuer);
+ text = text.replaceAll("#BIRTHDAY#", gebDat);
+ text = text.replaceAll("#DATE#", dateformat.format(datetime.getTime()));
+ text = text.replaceAll("#TIME#", timeformat.format(datetime.getTime()));
+
+ return text;
+ }
+
+ public static String xmlToString(Node node) {
+ try {
+ Source source = new DOMSource(node);
+ StringWriter stringWriter = new StringWriter();
+ Result result = new StreamResult(stringWriter);
+ TransformerFactory factory = TransformerFactory.newInstance();
+ Transformer transformer = factory.newTransformer();
+ transformer.transform(source, result);
+ return stringWriter.getBuffer().toString();
+ } catch (TransformerConfigurationException e) {
+ e.printStackTrace();
+ } catch (TransformerException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ public String buildAuthBlockSSO(
+ String issuer,
+ String issueInstant,
+ String authURL,
+ String target,
+ String targetFriendlyName,
+ String identityLinkValue,
+ String identityLinkType,
+ String oaURL,
+ String gebDat,
+ List<ExtendedSAMLAttribute> extendedSAMLAttributes,
+ AuthenticationSession session,
+ IOAAuthParameters oaParam)
+ throws BuildException
+ {
+ session.setSAMLAttributeGebeORwbpk(true);
+ String gebeORwbpk = "";
+ String wbpkNSDeclaration = "";
+
+ if (target != null) {
+
+ boolean useMandate = session.getUseMandate();
+ if (useMandate) {
+ String mandateReferenceValue = Random.nextRandom();
+ // remove leading "-"
+ if (mandateReferenceValue.startsWith("-"))
+ mandateReferenceValue = mandateReferenceValue.substring(1);
+
+ session.setMandateReferenceValue(mandateReferenceValue);
+
+ ExtendedSAMLAttribute mandateReferenceValueAttribute =
+ new ExtendedSAMLAttributeImpl("mandateReferenceValue", mandateReferenceValue, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK);
+
+ extendedSAMLAttributes.add(mandateReferenceValueAttribute);
+ }
+ }
+
+ //adding friendly name of OA
+ String friendlyname;
+ try {
+ friendlyname = AuthConfigurationProviderFactory.getInstance().getSSOFriendlyName();
+
+ ExtendedSAMLAttribute oaFriendlyNameAttribute =
+ new ExtendedSAMLAttributeImpl("oaFriendlyName", friendlyname, Constants.MOA_NS_URI, ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY);
+
+ extendedSAMLAttributes.add(oaFriendlyNameAttribute);
+
+
+ String text = AuthConfigurationProviderFactory.getInstance().getSSOSpecialText();
+
+ if (MiscUtil.isEmpty(text))
+ text="";
+ String specialText = MessageFormat.format(SPECIAL_TEXT_ATTRIBUTE,
+ new Object[] { generateSpecialText(text, issuer, gebDat, issueInstant) });
+
+ //generate unique AuthBlock tokken
+ String uniquetokken = Random.nextRandom();
+ session.setAuthBlockTokken(uniquetokken);
+
+ String assertion;
+
+ assertion = MessageFormat.format(
+ AUTH_BLOCK, new Object[] {
+ wbpkNSDeclaration,
+ issuer,
+ issueInstant,
+ authURL,
+ gebeORwbpk,
+ oaURL,
+ gebDat,
+ specialText,
+ MessageFormat.format(AUTHBLOCKTOKKEN_ATTRIBUTE,
+ new Object[] { uniquetokken }),
+ buildExtendedSAMLAttributes(extendedSAMLAttributes)});
+
+ return assertion;
+
+ } catch (ParseException e) {
+ Logger.error("Error on building AUTH-Block: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()});
+
+ } catch (ConfigurationException e) {
+ Logger.error("Error on building AUTH-Block: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()});
+ }
+
+
+
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/Builder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/Builder.java
new file mode 100644
index 000000000..ca9bf2080
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/Builder.java
@@ -0,0 +1,105 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.util.StringUtils;
+
+/**
+ * Base class for HTML/XML builders providing commonly useful functions.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class Builder {
+
+ /**
+ * Replaces a given number of occurences of a special tag in an XML or HTML template by a value.
+ * @param template html template
+ * @param tag special tag
+ * @param value value replacing the tag
+ * @param expected specifies if the tag is expected to present; if <code>true</code> and the tag
+ * is not present, an exception is thrown; if <code>false</code> and the tag is
+ * not present, the original string is returned
+ * @param maxreplacements Set -1 to replace each occurence of tag, or limit replacements by a given positive number
+ * @return XML or HTML code, the tag replaced
+ * @throws BuildException when template does not contain the tag
+ */
+ protected String replaceTag(
+ String template,
+ String tag,
+ String value,
+ boolean expected,
+ int maxreplacements)
+ throws BuildException
+ {
+ String result = template;
+ int index = result.indexOf(tag);
+ if (index < 0) {
+ if (expected) {
+ // Substring not found but should
+ throw new BuildException(
+ "builder.01",
+ new Object[] {"&lt;" + tag.substring(1, tag.length() - 1) + "&gt;"});
+ }
+ } else {
+ // replace each occurence
+ if (maxreplacements == -1) {
+ return StringUtils.replaceAll(template, tag, value);
+ } else {
+ int found = 1;
+ while (index > -1 && (found <= maxreplacements)) {
+ result = result.substring(0, index) + value + result.substring(index + tag.length());
+ index = result.indexOf(tag);
+ if (index > -1) found += 1;
+ }
+ }
+ }
+ return result;
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/CertInfoVerifyXMLSignatureRequestBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/CertInfoVerifyXMLSignatureRequestBuilder.java
new file mode 100644
index 000000000..a904242e1
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/CertInfoVerifyXMLSignatureRequestBuilder.java
@@ -0,0 +1,130 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import java.io.IOException;
+import java.text.MessageFormat;
+
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.FileUtils;
+
+/**
+ * Builder for the <code>&lt;VerifyXMLSignatureRequest&gt;</code> structure
+ * used for presenting certificate information in the secure viewer of the security layer implementation.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class CertInfoVerifyXMLSignatureRequestBuilder extends Builder implements Constants {
+
+ /** special tag in the VerifyXMLRequest template to be substituted for a <code>&lt;dsig:Signature&gt;</code> */
+ private static final String SIGNATURE_TAG = "<dsig:Signature/>";
+
+ /** private static String nl contains the NewLine representation in Java*/
+ private static final String nl = "\n";
+
+ /**
+ * XML template for the CertInfoVerifyXMLSignatureRequest to be built
+ */
+ static final String CERTINFO_REQUEST =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + nl +
+ "<{0}:VerifyXMLSignatureRequest {2} xmlns:dsig=\"" + DSIG_NS_URI + "\">" + nl +
+ " <{0}:SignatureInfo>" + nl +
+ " <{0}:SignatureEnvironment>" + nl +
+ " <{1}:XMLContent xml:space=\"preserve\"><dsig:Signature/></{1}:XMLContent>" + nl +
+ " </{0}:SignatureEnvironment>" + nl +
+ " <{0}:SignatureLocation>//dsig:Signature</{0}:SignatureLocation>" + nl +
+ " </{0}:SignatureInfo>" + nl +
+ "</{0}:VerifyXMLSignatureRequest>";
+
+ /**
+ * Constructor
+ */
+ public CertInfoVerifyXMLSignatureRequestBuilder() {
+ super();
+ }
+ /**
+ * Builds the <code>&lt;VerifyXMLSignatureRequest&gt;</code> structure.
+ * @return the XML structure
+ * @throws BuildException
+ */
+ public String build() throws BuildException {
+
+ String sl10Prefix;
+ String sl11Prefix;
+ String slNsDeclaration;
+
+// if (slVersion12) {
+
+ sl10Prefix = SL12_PREFIX;
+ sl11Prefix = SL12_PREFIX;
+ slNsDeclaration = "xmlns:" + SL12_PREFIX + "=\"" + SL12_NS_URI + "\"";
+
+// } else {
+//
+// sl10Prefix = SL10_PREFIX;
+// sl11Prefix = SL11_PREFIX;
+// slNsDeclaration = "xmlns:" + sl11Prefix + "=\"" + SL11_NS_URI + "\" xmlns:" + sl10Prefix + "=\"" + SL10_NS_URI + "\"";
+//
+// }
+
+ String certInfoRequest = MessageFormat.format(CERTINFO_REQUEST, new Object[] {sl11Prefix, sl10Prefix, slNsDeclaration});
+ String resDsigSignature = "resources/xmldata/CertInfoDsigSignature.xml";
+
+
+ try {
+ String dsigSignature = FileUtils.readResource(resDsigSignature, "UTF-8");
+ certInfoRequest = replaceTag(certInfoRequest, SIGNATURE_TAG, dsigSignature, true, 1);
+ return certInfoRequest;
+ }
+ catch (IOException ex) {
+ throw new BuildException("auth.04", new Object[] {resDsigSignature, ex.toString()});
+ }
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java
new file mode 100644
index 000000000..76cf9addb
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java
@@ -0,0 +1,172 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+
+
+/**
+ * Builder for CreateXMLSignatureRequest to sign data from a foreign
+ * eID card.
+ *
+ */
+
+public class CreateXMLSignatureRequestBuilderForeign extends Builder {
+
+ /** special tag in the XML template to be substituted for the KeyboxIdentifier */
+ private static final String KEYBOXID_TAG = "<KEYBOXID>";
+ /** special tag in the XML template to be substituted for the content */
+ private static final String XMLCONTENT_TAG = "<XMLContent>";
+ /** private static int all contains the representation to replace all tags*/
+ private static final int ALL = -1;
+
+// /** default HTML template */
+// private static final String DEFAULT_XML_TEMPLATE =
+// "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+// "<sl:CreateXMLSignatureRequest xmlns:sl=\"http://www.buergerkarte.at/namespaces/securitylayer/1.2#\">" +
+// "<sl:KeyboxIdentifier>" + KEYBOXID_TAG + "</sl:KeyboxIdentifier>" +
+// "<sl:DataObjectInfo Structure=\"enveloping\">" +
+// "<sl:DataObject>" +
+// "<sl:XMLContent>" + XMLCONTENT_TAG + "</sl:XMLContent>" +
+// "</sl:DataObject>" +
+// "<sl:TransformsInfo>" +
+// "<sl:FinalDataMetaInfo>" +
+// "<sl:MimeType>text/plain</sl:MimeType>" +
+// "</sl:FinalDataMetaInfo>" +
+// "</sl:TransformsInfo>" +
+// "</sl:DataObjectInfo>" +
+// "</sl:CreateXMLSignatureRequest>";
+
+ /** default HTML template */
+ private static final String DEFAULT_XHTML_TEMPLATE =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
+ "<sl:CreateXMLSignatureRequest xmlns:sl=\"http://www.buergerkarte.at/namespaces/securitylayer/1.2#\">" +
+ "<sl:KeyboxIdentifier>" + KEYBOXID_TAG + "</sl:KeyboxIdentifier>" +
+ "<sl:DataObjectInfo Structure=\"enveloping\">" +
+ "<sl:DataObject>" +
+ "<sl:XMLContent>" + XMLCONTENT_TAG + "</sl:XMLContent>" +
+ "</sl:DataObject>" +
+ "<sl:TransformsInfo>" +
+ "<sl:FinalDataMetaInfo>" +
+ "<sl:MimeType>application/xhtml+xml</sl:MimeType>" +
+ "</sl:FinalDataMetaInfo>" +
+ "</sl:TransformsInfo>" +
+ "</sl:DataObjectInfo>" +
+ "</sl:CreateXMLSignatureRequest>";
+
+ /**
+ * Constructor for CreateXMLSignatureRequestBuilderForeign.
+ */
+ public CreateXMLSignatureRequestBuilderForeign() {
+ super();
+ }
+ /**
+ * Builds the XML request.
+ *
+ * @param xmlRequest XML Request to be sent as a parameter in the form
+ * @param bkuURL URL of the "B&uuml;rgerkartenumgebung" the form will be submitted to;
+ * may be <code>null</code>, in this case the default URL will be used
+ * @param dataURL DataURL to be sent as a parameter in the form
+ */
+ public String build(
+ String keyboxIdentifier,
+ String xmlContent)
+ throws BuildException
+ {
+ String xmlRequest = DEFAULT_XHTML_TEMPLATE;
+ xmlRequest = replaceTag(xmlRequest, KEYBOXID_TAG, keyboxIdentifier, true, ALL);
+ //htmlForm = replaceTag(htmlForm, XMLREQUEST_TAG, encodeParameter(xmlRequest), true, ALL);
+ xmlRequest = replaceTag(xmlRequest, XMLCONTENT_TAG, xmlContent, true, ALL);
+ return xmlRequest;
+ }
+ /**
+ * Encodes a string for inclusion as a parameter in the form.
+ * Double quotes are substituted by <code>"&amp;quot;"</code>.
+ * @param s the string to be encoded
+ * @return the string encoded
+ * @throws BuildException on any exception encountered
+ */
+ public static String encodeParameter(String s) throws BuildException {
+ StringReader in = new StringReader(s);
+ StringWriter out = new StringWriter();
+ try {
+ for (int ch = in.read(); ch >= 0; ch = in.read()) {
+ if (ch == '"')
+ out.write("&quot;");
+ else if (ch == '<')
+ out.write("&lt;");
+ else if (ch == '>')
+ out.write("&gt;");
+ else if (ch == 'ä')
+ out.write("&auml;");
+ else if (ch == 'ö')
+ out.write("&ouml;");
+ else if (ch == 'ü')
+ out.write("&uuml;");
+ else if (ch == 'Ä')
+ out.write("&Auml;");
+ else if (ch == 'Ö')
+ out.write("&Ouml;");
+ else if (ch == 'Ü')
+ out.write("&Uuml;");
+ else if (ch == 'ß')
+ out.write("&szlig;");
+ else
+ out.write(ch);
+ }
+ }
+ catch (IOException ex) {
+ throw new BuildException("builder.00", new Object[] {"CreateXMLSignatureRequest", ex.toString()});
+ }
+ return out.toString();
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java
new file mode 100644
index 000000000..dc981ba33
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java
@@ -0,0 +1,246 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.Map;
+
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters;
+import at.gv.egovernment.moa.id.util.FormBuildUtils;
+import at.gv.egovernment.moa.util.MiscUtil;
+
+/**
+ * Builder for HTML form requesting the security layer implementation
+ * to get the identity link from smartcard by a <code>&lt;InfoboxReadRequest&gt;</code>.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class GetIdentityLinkFormBuilder extends Builder {
+ /** private static String NL contains the NewLine representation in Java*/
+ private static final String nl = "\n";
+ /** special tag in the HTML template to be substituted for the BKU URL */
+ private static final String BKU_TAG = "<BKU>";
+ /** special tag in the HTML template to be substituted for the XML request */
+ private static final String XMLREQUEST_TAG = "<XMLRequest>";
+ /** special tag in the HTML template to be substituted for the data URL */
+ private static final String DATAURL_TAG = "<DataURL>";
+// /** special tag in the HTML template to be substituted for certificate info XML request */
+// private static final String CERTINFO_XMLREQUEST_TAG = "<CertInfoXMLRequest>";
+// /** special tag in the HTML template to be substituted for the certificate info data URL */
+// private static final String CERTINFO_DATAURL_TAG = "<CertInfoDataURL>";
+ /** special tag in the HTML template to be substituted for the infoboxes to be pushed from the BKU */
+ private static final String PUSHINFOBOX_TAG = "<PushInfobox>";
+ /** special tag in the HTML template to be substituted for the BKU URL */
+ /** private static int all contains the representation to replace all tags*/
+ private static final int ALL = -1;
+
+ private static final String COLOR_TAG = "<COLOR>";
+ private static final String REDIRECTTARGETTAG = "<REDIRECTTARGET>";
+ private static final String APPLETWIDTH_TAG = "<APPLETWIDTH>";
+ private static final String APPLETHEIGHT_TAG = "<APPLETHEIGHT>";
+
+ /** default HTML template */
+ private static final String DEFAULT_HTML_TEMPLATE =
+ "<html>" + nl +
+ "<head>" + nl +
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" + nl +
+ "<title>Anmeldung mit B&uuml;rgerkarte</title>" + nl +
+ "</head>" + nl +
+ "<body>" + nl +
+ "<form name=\"GetIdentityLinkForm\"" + nl +
+ " action=\"" + BKU_TAG + "\"" + nl +
+ " method=\"post\">" + nl +
+ " <input type=\"hidden\" " + nl +
+ " name=\"XMLRequest\"" + nl +
+ " value=\"" + XMLREQUEST_TAG + "\"/>" + nl +
+ " <input type=\"hidden\" " + nl +
+ " name=\"DataURL\"" + nl +
+ " value=\"" + DATAURL_TAG + "\"/>" + nl +
+ " <input type=\"hidden\" " + nl +
+ " name=\"PushInfobox\"" + nl +
+ " value=\"" + PUSHINFOBOX_TAG + "\"/>" + nl +
+ " <input type=\"submit\" value=\"Anmeldung mit B&uuml;rgerkarte\"/>" + nl +
+ "</form>" + nl +
+// "<form name=\"CertificateInfoForm\"" + nl +
+// " action=\"" + BKU_TAG + "\"" + nl +
+// " method=\"post\">" + nl +
+// " <input type=\"hidden\" " + nl +
+// " name=\"XMLRequest\"" + nl +
+// " value=\"" + CERTINFO_XMLREQUEST_TAG + "\"/>" + nl +
+// " <input type=\"hidden\" " + nl +
+// " name=\"DataURL\"" + nl +
+// " value=\"" + CERTINFO_DATAURL_TAG + "\"/>" + nl +
+//// " <input type=\"submit\" value=\"Information zu Wurzelzertifikaten\"/>" + nl +
+// " <input type=\"hidden\" value=\"Information zu Wurzelzertifikaten\"/>" + nl +
+// "</form>" + nl +
+ "</body>" + nl +
+ "</html>";
+
+
+
+
+ /**
+ * Constructor for GetIdentityLinkFormBuilder.
+ */
+ public GetIdentityLinkFormBuilder() {
+ super();
+ }
+ /**
+ * Builds the HTML form, including XML Request and data URL as parameters.
+ *
+ * @param htmlTemplate template to be used for the HTML form;
+ * may be <code>null</code>, in this case a default layout will be produced
+ * @param xmlRequest XML Request to be sent as a parameter in the form
+ * @param bkuURL URL of the "B&uuml;rgerkartenumgebung" the form will be submitted to;
+ * may be <code>null</code>, in this case the default URL will be used
+ * @param dataURL DataURL to be sent as a parameter in the form
+ * @param oaParam
+ * @param appletwidth
+ * @param appletheigth
+ */
+ public String build(
+ String htmlTemplate,
+ String bkuURL,
+ String xmlRequest,
+ String dataURL,
+ String certInfoXMLRequest,
+ String certInfoDataURL,
+ String pushInfobox, IOAAuthParameters oaParam,
+ String appletheigth,
+ String appletwidth)
+ throws BuildException
+ {
+ String htmlForm = htmlTemplate == null ? DEFAULT_HTML_TEMPLATE : htmlTemplate;
+ htmlForm = replaceTag(htmlForm, BKU_TAG, bkuURL, true, ALL);
+ htmlForm = replaceTag(htmlForm, XMLREQUEST_TAG, encodeParameter(xmlRequest), true, ALL);
+ htmlForm = replaceTag(htmlForm, DATAURL_TAG, dataURL, true, ALL);
+ htmlForm = replaceTag(htmlForm, PUSHINFOBOX_TAG, pushInfobox, false, ALL);
+//new:wird oben mitreplaced htmlForm = replaceTag(htmlForm, BKU_TAG, bkuURL);
+
+ //removed in MOA-ID 2.0
+// htmlForm = replaceTag(htmlForm, CERTINFO_XMLREQUEST_TAG, encodeParameter(certInfoXMLRequest), true, ALL);
+// htmlForm = replaceTag(htmlForm, CERTINFO_DATAURL_TAG, certInfoDataURL, true, ALL);
+
+ Map<String, String> map = null;
+
+ if (oaParam != null) {
+ map = oaParam.getFormCustomizaten();
+ htmlForm = replaceTag(htmlForm, COLOR_TAG, map.get(FormBuildUtils.MAIN_BACKGROUNDCOLOR), false, ALL);
+ htmlForm = replaceTag(htmlForm, REDIRECTTARGETTAG, map.get(FormBuildUtils.REDIRECTTARGET), false, ALL);
+
+ } else {
+ htmlForm = replaceTag(htmlForm, COLOR_TAG, FormBuildUtils.getDefaultMap().get(FormBuildUtils.MAIN_BACKGROUNDCOLOR), false, ALL);
+ htmlForm = replaceTag(htmlForm, REDIRECTTARGETTAG, FormBuildUtils.getDefaultMap().get(FormBuildUtils.REDIRECTTARGET), false, ALL);
+ }
+
+ if (map != null && MiscUtil.isNotEmpty(map.get(FormBuildUtils.APPLET_HEIGHT)))
+ htmlForm = replaceTag(htmlForm, APPLETHEIGHT_TAG, map.get(FormBuildUtils.APPLET_HEIGHT), false, ALL);
+ else if (MiscUtil.isNotEmpty(appletheigth))
+ htmlForm = replaceTag(htmlForm, APPLETHEIGHT_TAG, appletheigth, false, ALL);
+ else
+ htmlForm = replaceTag(htmlForm, APPLETHEIGHT_TAG, "160", false, ALL);
+
+ if (map != null && MiscUtil.isNotEmpty(map.get(FormBuildUtils.APPLET_WIDTH)))
+ htmlForm = replaceTag(htmlForm, APPLETWIDTH_TAG, map.get(FormBuildUtils.APPLET_WIDTH), false, ALL);
+ else if (MiscUtil.isNotEmpty(appletwidth))
+ htmlForm = replaceTag(htmlForm, APPLETWIDTH_TAG, appletwidth, false, ALL);
+ else
+ htmlForm = replaceTag(htmlForm, APPLETWIDTH_TAG, "250", false, ALL);
+
+ return htmlForm;
+ }
+
+
+
+ /**
+ * Encodes a string for inclusion as a parameter in the form.
+ * Double quotes are substituted by <code>"&amp;quot;"</code>.
+ * @param s the string to be encoded
+ * @return the string encoded
+ * @throws BuildException on any exception encountered
+ */
+ public static String encodeParameter(String s) throws BuildException {
+ StringReader in = new StringReader(s);
+ StringWriter out = new StringWriter();
+ try {
+ for (int ch = in.read(); ch >= 0; ch = in.read()) {
+ if (ch == '"') {
+ out.write("&quot;");
+ } else if (ch == '<') {
+ out.write("&lt;");
+ } else if (ch == '>') {
+ out.write("&gt;");
+ } else if (ch == 'ä') {
+ out.write("&auml;");
+ } else if (ch == 'ö') {
+ out.write("&ouml;");
+ } else if (ch == 'ü') {
+ out.write("&uuml;");
+ } else if (ch == 'Ä') {
+ out.write("&Auml;");
+ } else if (ch == 'Ö') {
+ out.write("&Ouml;");
+ } else if (ch == 'Ü') {
+ out.write("&Uuml;");
+ } else if (ch == 'ß') {
+ out.write("&szlig;");
+ } else {
+ out.write(ch);
+ }
+ }
+ }
+ catch (IOException ex) {
+ throw new BuildException("builder.00", new Object[] {"GetIdentityLinkForm", ex.toString()});
+ }
+ return out.toString();
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetVerifyAuthBlockFormBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetVerifyAuthBlockFormBuilder.java
new file mode 100644
index 000000000..45e5edf2c
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetVerifyAuthBlockFormBuilder.java
@@ -0,0 +1,128 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+
+/**
+ * Builder for HTML form requesting a security layer request
+ *
+ * @author Peter Danner
+ * @version $Id: GetIdentityLinkFormBuilder.java 769 2007-01-10 15:37:52Z peter.danner $
+ */
+public class GetVerifyAuthBlockFormBuilder extends Builder {
+ /** private static String NL contains the NewLine representation in Java*/
+ private static final String nl = "\n";
+ /** special tag in the HTML template to be substituted for the BKU URL */
+ private static final String BKU_TAG = "<BKU>";
+ /** special tag in the HTML template to be substituted for the XML request */
+ private static final String XMLREQUEST_TAG = "<XMLRequest>";
+ /** special tag in the HTML template to be substituted for the data URL */
+ private static final String DATAURL_TAG = "<DataURL>";
+ /** special tag in the HTML template to be substituted for the infoboxes to be pushed from the BKU */
+ private static final String PUSHINFOBOX_TAG = "<PushInfobox>";
+ /** private static int all contains the representation to replace all tags*/
+ private static final int ALL = -1;
+
+ /** default HTML template */
+ private static final String DEFAULT_HTML_TEMPLATE =
+ "<html>" + nl +
+ " <head>" + nl +
+ " <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>" + nl +
+ " <title>Signatur der Anmeldedaten</title>" + nl +
+ " </head>" + nl +
+ " <body onLoad=\"autoSubmit()\">" + nl +
+ " <script type=\"text/javascript\">" + nl +
+ " //<!-- " + nl +
+ " function autoSubmit() { " + nl +
+ " document.VerifyAuthBlockForm.submitButton.disabled=true;" + nl +
+ " document.VerifyAuthBlockForm.submit(); " + nl +
+ " } //-->" + nl +
+ " </script>" + nl +
+ " <form name=\"VerifyAuthBlockForm\" action=\"" + BKU_TAG + "\" method=\"post\" enctype=\"application/x-www-form-urlencoded\">" + nl +
+ " <input type=\"hidden\" name=\"XMLRequest\" value=\"" + XMLREQUEST_TAG + "\"/>" + nl +
+ " <input type=\"hidden\" name=\"DataURL\" value=\"" + DATAURL_TAG + "\"/>" + nl +
+ " <input type=\"hidden\" name=\"PushInfobox\" value=\"" + PUSHINFOBOX_TAG + "\"/>" + nl +
+ " <input type=\"submit\" value=\"Signieren der Anmeldedaten\" id=\"submitButton\"/>" + nl +
+ " </form>" + nl +
+ " </body>" + nl +
+ "</html>";
+
+ /**
+ * Constructor for GetVerifyAuthBlockFormBuilder.
+ */
+ public GetVerifyAuthBlockFormBuilder() {
+ super();
+ }
+ /**
+ * Builds the HTML form, including XML Request and data URL as parameters.
+ *
+ * @param htmlTemplate template to be used for the HTML form;
+ * may be <code>null</code>, in this case a default layout will be produced
+ * @param xmlRequest XML Request to be sent as a parameter in the form
+ * @param bkuURL URL of the "B&uuml;rgerkartenumgebung" the form will be submitted to;
+ * may be <code>null</code>, in this case the default URL will be used
+ * @param dataURL DataURL to be sent as a parameter in the form
+ */
+ public String build(
+ String htmlTemplate,
+ String bkuURL,
+ String xmlRequest,
+ String dataURL,
+ String pushInfobox)
+ throws BuildException
+ {
+ String htmlForm = htmlTemplate == null ? DEFAULT_HTML_TEMPLATE : htmlTemplate;
+ htmlForm = replaceTag(htmlForm, BKU_TAG, bkuURL, true, ALL);
+ htmlForm = replaceTag(htmlForm, XMLREQUEST_TAG, GetIdentityLinkFormBuilder.encodeParameter(xmlRequest), true, ALL);
+ htmlForm = replaceTag(htmlForm, DATAURL_TAG, dataURL, true, ALL);
+ if (null==pushInfobox) pushInfobox="";
+ htmlForm = replaceTag(htmlForm, PUSHINFOBOX_TAG, pushInfobox, false, ALL);
+ return htmlForm;
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java
new file mode 100644
index 000000000..81ef5e408
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java
@@ -0,0 +1,195 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Constants;
+
+/**
+ * Builder for the <code>&lt;InfoboxReadRequest&gt;</code> structure
+ * used for requesting the identity link from the security layer implementation.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class InfoboxReadRequestBuilder implements Constants {
+
+
+ /**
+ * Constructor for InfoboxReadRequestBuilder.
+ */
+ public InfoboxReadRequestBuilder() {
+ }
+
+
+ /**
+ * Builds an <code>&lt;InfoboxReadRequest&gt;</code>.
+ *
+ * @param slVersion12 specifies whether the Security Layer version is
+ * version 1.2 or not
+ * @param businessService specifies whether the online application is a
+ * business service or not
+ * @param identityLinkDomainIdentifier the identification number of the business
+ * company; maybe <code>null</code> if the OA
+ * is a public service; must not be <code>null</code>
+ * if the OA is a business service
+ * @return <code>&lt;InfoboxReadRequest&gt;</code> as String
+ */
+ public String build(boolean businessService, String identityLinkDomainIdentifier) {
+ Logger.info("Building InfoBoxReadRequest");
+ String slPrefix;
+ String slNsDeclaration;
+
+// if (slVersion12) {
+ slPrefix = SL12_PREFIX;
+ slNsDeclaration = SL12_NS_URI;
+// } else {
+// slPrefix = SL10_PREFIX;
+// slNsDeclaration = SL10_NS_URI;
+// }
+
+ StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadRequest xmlns:");
+ sb.append(slPrefix);
+ sb.append("=\"");
+ sb.append(slNsDeclaration);
+ sb.append("\">");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":InfoboxIdentifier>IdentityLink</");
+ sb.append(slPrefix);
+ sb.append(":InfoboxIdentifier>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":BinaryFileParameters ContentIsXMLEntity=\"true\"/>");
+ if (businessService) {
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":BoxSpecificParameters>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":IdentityLinkDomainIdentifier>");
+ sb.append(identityLinkDomainIdentifier);
+ sb.append("</sl:IdentityLinkDomainIdentifier>");
+ sb.append("</");
+ sb.append(slPrefix);
+ sb.append(":BoxSpecificParameters>");
+ }
+ sb.append("</");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadRequest>");
+
+ return sb.toString();
+
+ }
+
+
+ /**
+ * Builds an <code>&lt;InfoboxReadRequest&gt;</code>.
+ *
+ * @param slVersion12 specifies whether the Security Layer version is
+ * version 1.2 or not
+ * @param businessService specifies whether the online application is a
+ * business service or not
+ * @param identityLinkDomainIdentifier the identification number of the business
+ * company; maybe <code>null</code> if the OA
+ * is a public service; must not be <code>null</code>
+ * if the OA is a business service
+ * @return <code>&lt;InfoboxReadRequest&gt;</code> as String
+ *
+ */
+ public String buildStorkReadRequest(String identityLinkDomainIdentifier) {
+ Logger.info("Building Stork InfoBoxReadRequest for " + identityLinkDomainIdentifier);
+
+ String slPrefix;
+ String slNsDeclaration;
+
+ slPrefix = SL12_PREFIX;
+ slNsDeclaration = SL12_NS_URI;
+
+ StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadRequest xmlns:");
+ sb.append(slPrefix);
+ sb.append("=\"");
+ sb.append(slNsDeclaration);
+ sb.append("\">");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":InfoboxIdentifier>IdentityLink</");
+ sb.append(slPrefix);
+ sb.append(":InfoboxIdentifier>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":BinaryFileParameters ContentIsXMLEntity=\"true\"/>");
+
+ // append box parameters - necessary for stork?
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":BoxSpecificParameters>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":IdentityLinkDomainIdentifier>");
+ sb.append(identityLinkDomainIdentifier);
+ sb.append("</sl:IdentityLinkDomainIdentifier>");
+ sb.append("</");
+ sb.append(slPrefix);
+ sb.append(":BoxSpecificParameters>");
+ // end appending box parameters
+
+ sb.append("</");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadRequest>");
+
+ return sb.toString();
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java
new file mode 100644
index 000000000..bb3533664
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java
@@ -0,0 +1,124 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import at.gv.egovernment.moa.util.Constants;
+
+/**
+ * Builder for the <code>&lt;InfoboxReadRequest&gt;</code> structure
+ * used for requesting the identity link from the security layer implementation.
+ *
+ * @author Paul Ivancsics
+ * @version $Id: InfoboxReadRequestBuilder.java 1087 2008-08-28 07:55:59Z mcentner $
+ */
+public class InfoboxReadRequestBuilderCertificate implements Constants {
+
+
+ /**
+ * Constructor for InfoboxReadRequestBuilder.
+ */
+ public InfoboxReadRequestBuilderCertificate() {
+ }
+
+
+ /**
+ * Builds an <code>&lt;InfoboxReadRequest&gt;</code>.
+ *
+ * @param slVersion12 specifies whether the Security Layer version is
+ * version 1.2 or not
+ * @param businessService specifies whether the online application is a
+ * business service or not
+ * @param identityLinkDomainIdentifier the identification number of the business
+ * company; maybe <code>null</code> if the OA
+ * is a public service; must not be <code>null</code>
+ * if the OA is a business service
+ *
+ * @return <code>&lt;InfoboxReadRequest&gt;</code> as String
+ */
+ public String build(boolean slVersion12) {
+
+ String slPrefix;
+ String slNsDeclaration;
+
+ if (slVersion12) {
+ slPrefix = SL12_PREFIX;
+ slNsDeclaration = SL12_NS_URI;
+ } else {
+ slPrefix = SL10_PREFIX;
+ slNsDeclaration = SL10_NS_URI;
+ }
+
+ StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadRequest xmlns:");
+ sb.append(slPrefix);
+ sb.append("=\"");
+ sb.append(slNsDeclaration);
+ sb.append("\">");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":InfoboxIdentifier>Certificates</");
+ sb.append(slPrefix);
+ sb.append(":InfoboxIdentifier>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":AssocArrayParameters>");
+ sb.append("<");
+ sb.append(slPrefix);
+ sb.append(":ReadValue Key=\"SecureSignatureKeypair\"/>");
+ sb.append("</");
+ sb.append(slPrefix);
+ sb.append(":AssocArrayParameters>");
+ sb.append("</");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadRequest>");
+
+ return sb.toString();
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginConfirmationBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginConfirmationBuilder.java
new file mode 100644
index 000000000..31e4c0578
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginConfirmationBuilder.java
@@ -0,0 +1,101 @@
+/*******************************************************************************
+ * 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.builder;
+
+
+public class LoginConfirmationBuilder {
+ /** private static String NL contains the NewLine representation in Java*/
+ private static final String nl = "\n";
+
+ private static final String OA_URL_TAG = "<OA_URL>";
+ private static final String FORM_METHOD_TAG = "<FORM_METHOD_URL>";
+ private static final String ATTR_NAME_TAG = "<ATTR_NAME_URL>";
+ private static final String ATTR_VALUE_TAG = "<ATTR_VALUE_URL>";
+ private static final String ATTR_TEMP_TAG = "<ATTR_TEMP_URL>";
+ private static final String OA_TAG = "<OA_TAG>";
+ private static final String NAME_TAG = "<NAME_URL>";
+
+ private static final String METHOD_GET = "GET";
+ private static final String METHOD_POST = "POST";
+
+
+ private static final String ATTR_TEMPLATE =
+ " <input type=\"hidden\" " + nl +
+ " name=\"" + ATTR_NAME_TAG + "\"" + nl +
+ " value=\"" + ATTR_VALUE_TAG + "\"/>" + nl;
+
+ /** default HTML template */
+ private static final String DEFAULT_HTML_TEMPLATE =
+ "<html>" + nl +
+ "<head>" + nl +
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" + nl +
+ "<title>Anmeldung mit B&uuml;rgerkarte</title>" + nl +
+ "</head>" + nl +
+ "<body>" + nl +
+ "<p>Wollen Sie sich als <b>"+NAME_TAG+"</b> bei <b>"+OA_TAG+
+ "</b> anmelden?</p>" + nl +
+ "<form name=\"GetIdentityLinkForm\"" + nl +
+ " action=\"" + OA_URL_TAG + "\"" + nl +
+ " method=\"" + FORM_METHOD_TAG + "\">" + nl +
+ ATTR_TEMP_TAG +
+ " <input type=\"submit\" value=\"Anmeldung durchf&uuml;hren\"/>" + nl +
+ "</form>" + nl +
+ "</body>" + nl +
+ "</html>";
+
+ private String template;
+
+ public LoginConfirmationBuilder(){
+ init(METHOD_GET);
+ }
+
+ public LoginConfirmationBuilder(String method) {
+ init(method);
+ }
+
+ public void init(String method) {
+ if(method.equals(METHOD_POST)) {
+ template = DEFAULT_HTML_TEMPLATE.replace(FORM_METHOD_TAG, METHOD_POST);
+ } else {
+ template = DEFAULT_HTML_TEMPLATE.replace(FORM_METHOD_TAG, METHOD_GET);
+ }
+ }
+
+ public void addParameter(String name, String value) {
+ String attr_template = ATTR_TEMPLATE + ATTR_TEMP_TAG;
+ //Logger.info("Attr Template: " + attr_template);
+ attr_template = attr_template.replace(ATTR_NAME_TAG, name);
+ //Logger.info("Attr Template: " + attr_template);
+ attr_template = attr_template.replace(ATTR_VALUE_TAG, value);
+ //Logger.info("Attr Template: " + attr_template);
+ template = template.replace(ATTR_TEMP_TAG, attr_template);
+ //Logger.info("Template: " + template);
+ }
+
+ public String finish(String oaURL, String userName, String oa) {
+ template = template.replace(NAME_TAG, userName);
+ template = template.replace(OA_TAG, oa);
+ template = template.replace(OA_URL_TAG, oaURL);
+ return template.replace(ATTR_TEMP_TAG, "");
+ }
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java
new file mode 100644
index 000000000..333d8680c
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java
@@ -0,0 +1,105 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.XPathUtils;
+
+/**
+ * Builder for the <code>lt;pr:Person&gt;</code> element to be inserted
+ * in the authentication data <code>lt;saml:Assertion&gt;</code>.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class PersonDataBuilder {
+
+ /**
+ * Constructor for PersonDataBuilder.
+ */
+ public PersonDataBuilder() {
+ super();
+ }
+ /**
+ * Builds the <code>&lt;pr:Person&gt;</code> element.<br/>
+ * Utilizes the parsed <code>&lt;prPerson&gt;</code> from the identity link
+ * and the information regarding inclusion of <code>"Stammzahl"</code> in the
+ * <code>&lt;pr:Person&gt;</code> data.
+ *
+ * @param identityLink <code>IdentityLink</code> containing the
+ * attribute <code>prPerson</code>
+ * @param provideStammzahl true if <code>"Stammzahl"</code> is to be included;
+ * false otherwise
+ * @return the <code>&lt;pr:Person&gt;</code> element as a String
+ * @throws BuildException on any error
+ */
+ public String build(IdentityLink identityLink, boolean provideStammzahl)
+ throws BuildException {
+
+ try {
+ Element prPerson = (Element)identityLink.getPrPerson().cloneNode(true);
+ if (! provideStammzahl) {
+ Node prIdentification = XPathUtils.selectSingleNode(prPerson, "pr:Identification/pr:Value");
+ //remove IdentificationValue
+ prIdentification.getFirstChild().setNodeValue("");
+ }
+ String xmlString = DOMUtils.serializeNode(prPerson);
+ return xmlString;
+ }
+ catch (Exception ex) {
+ throw new BuildException(
+ "builder.00",
+ new Object[] {"PersonData", ex.toString()},
+ ex);
+ }
+ }
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java
new file mode 100644
index 000000000..8b0d906fe
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java
@@ -0,0 +1,137 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import java.text.MessageFormat;
+
+import org.w3c.dom.Element;
+
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.StringUtils;
+
+/**
+ * Builder for the <code>lt;samlp:Response&gt;</code> used for passing
+ * result and status information from the <code>GetAuthenticationData</code>
+ * web service.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class SAMLResponseBuilder implements Constants {
+ /** XML - Template for samlp:Response */
+ private static final String RESPONSE =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" +
+ "<samlp:Response xmlns:samlp=\"" + SAMLP_NS_URI + "\" xmlns:saml=\"" + SAML_NS_URI + "\"" +
+ " ResponseID=\"{0}\" InResponseTo=\"{1}\" MajorVersion=\"1\" MinorVersion=\"0\" IssueInstant=\"{2}\">" +
+ " <samlp:Status>" +
+ " <samlp:StatusCode Value=\"{3}\">" +
+ " {4}" +
+ " </samlp:StatusCode>" +
+ " <samlp:StatusMessage>{5}</samlp:StatusMessage>" +
+ " </samlp:Status>" +
+ " {6}" +
+ "</samlp:Response>";
+ /** XML - Template for samlp:StatusCode */
+ private static final String SUB_STATUS_CODE =
+ "<samlp:StatusCode Value=\"{0}\"></samlp:StatusCode>";
+
+ /**
+ * Constructor for SAMLResponseBuilder.
+ */
+ public SAMLResponseBuilder() {
+ super();
+ }
+ /**
+ * Builds the SAML response.
+ * @param responseID response ID
+ * @param inResponseTo request ID of <code>lt;samlp:Request&gt;</code> responded to
+ * @param issueInstant current timestamp
+ * @param statusCode status code
+ * @param subStatusCode sub-status code refining the status code; may be <code>null</code>
+ * @param statusMessage status message
+ * @param samlAssertion SAML assertion representing authentication data
+ * @return SAML response as a DOM element
+ */
+ public Element build(
+ String responseID,
+ String inResponseTo,
+ String issueInstant,
+ String statusCode,
+ String subStatusCode,
+ String statusMessage,
+ String samlAssertion)
+ throws BuildException {
+
+ try {
+ String xmlSubStatusCode =
+ subStatusCode == null ?
+ "" :
+ MessageFormat.format(SUB_STATUS_CODE, new Object[] {subStatusCode});
+
+ String xmlResponse = MessageFormat.format(RESPONSE, new Object[] {
+ responseID,
+ inResponseTo,
+ issueInstant,
+ statusCode,
+ xmlSubStatusCode,
+ statusMessage,
+ StringUtils.removeXMLDeclaration(samlAssertion) });
+ Element domResponse = DOMUtils.parseDocument(xmlResponse, false, ALL_SCHEMA_LOCATIONS, null).getDocumentElement();
+ return domResponse;
+ }
+ catch (Throwable ex) {
+ throw new BuildException(
+ "builder.00",
+ new Object[] { "samlp:Response", ex.toString() },
+ ex);
+ }
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java
new file mode 100644
index 000000000..5c1b12e0d
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * 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.builder;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+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.AuthenticationException;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
+import at.gv.egovernment.moa.logging.Logger;
+
+public class StartAuthenticationBuilder {
+
+ private static StartAuthenticationBuilder instance = null;
+
+ public static StartAuthenticationBuilder getInstance() {
+ if (instance == null) {
+ instance = new StartAuthenticationBuilder();
+ }
+ return instance;
+ }
+
+
+ /**
+ * Depending on the selected citizen's country ({@code moasession.ccc}):
+ * <ul>
+ * <li><strong>Either</strong> creates an "IdentityLinkForm" with embedded {@code InfoBoxReadRequest} to be submitted to a citizen card
+ * environment for reading the subject's IdentityLink</li>
+ * </ul>
+ *
+ * @return The IdentityLinkForm.
+ */
+ public String build(AuthenticationSession moasession, HttpServletRequest req,
+ HttpServletResponse resp) throws WrongParametersException, MOAIDException {
+
+ if (moasession == null) {
+ throw new AuthenticationException("auth.18", new Object[] { });
+ }
+
+ //normal MOA-ID authentication
+ Logger.debug("Starting normal MOA-ID authentication");
+
+ String getIdentityLinkForm = AuthenticationServer.getInstance().startAuthentication(moasession, req);
+
+ return getIdentityLinkForm;
+ }
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java
new file mode 100644
index 000000000..d2ea53011
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java
@@ -0,0 +1,408 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import java.util.List;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+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.BuildException;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.util.Base64Utils;
+import at.gv.egovernment.moa.util.Constants;
+
+/**
+ * Builder for the <code>&lt;VerifyXMLSignatureRequestBuilder&gt;</code> structure
+ * used for sending the DSIG-Signature of the Security Layer card for validating to MOA-SP.
+ *
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+public class VerifyXMLSignatureRequestBuilder {
+
+ /** shortcut for XMLNS namespace URI */
+ private static final String XMLNS_NS_URI = Constants.XMLNS_NS_URI;
+ /** shortcut for MOA namespace URI */
+ private static final String MOA_NS_URI = Constants.MOA_NS_URI;
+ /** The DSIG-Prefix */
+ private static final String DSIG = Constants.DSIG_PREFIX + ":";
+
+ /** The document containing the <code>VerifyXMLsignatureRequest</code> */
+ private Document requestDoc_;
+ /** the <code>VerifyXMLsignatureRequest</code> root element */
+ private Element requestElem_;
+
+
+ /**
+ * Builds the body for a <code>VerifyXMLsignatureRequest</code> including the root
+ * element and namespace declarations.
+ *
+ * @throws BuildException If an error occurs on building the document.
+ */
+ public VerifyXMLSignatureRequestBuilder() throws BuildException {
+ try {
+ DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ requestDoc_ = docBuilder.newDocument();
+ requestElem_ = requestDoc_.createElementNS(MOA_NS_URI, "VerifyXMLSignatureRequest");
+ requestElem_.setAttributeNS(XMLNS_NS_URI, "xmlns", MOA_NS_URI);
+ requestElem_.setAttributeNS(XMLNS_NS_URI, "xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI);
+ requestDoc_.appendChild(requestElem_);
+ } catch (Throwable t) {
+ throw new BuildException(
+ "builder.00",
+ new Object[] {"VerifyXMLSignatureRequest", t.toString()},
+ t);
+ }
+ }
+
+
+ /**
+ * Builds a <code>&lt;VerifyXMLSignatureRequest&gt;</code>
+ * from an IdentityLink with a known trustProfileID which
+ * has to exist in MOA-SP
+ * @param identityLink - The IdentityLink
+ * @param trustProfileID - a preconfigured TrustProfile at MOA-SP
+ *
+ * @return Element - The complete request as Dom-Element
+ *
+ * @throws ParseException
+ */
+ public Element build(IdentityLink identityLink, String trustProfileID)
+ throws ParseException
+ {
+ try {
+ // build the request
+ Element dateTimeElem = requestDoc_.createElementNS(MOA_NS_URI, "DateTime");
+ requestElem_.appendChild(dateTimeElem);
+ Node dateTime = requestDoc_.createTextNode(identityLink.getIssueInstant());
+ dateTimeElem.appendChild(dateTime);
+ Element verifiySignatureInfoElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo");
+ requestElem_.appendChild(verifiySignatureInfoElem);
+ Element verifySignatureEnvironmentElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment");
+ verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem);
+ Element base64ContentElem = requestDoc_.createElementNS(MOA_NS_URI, "Base64Content");
+ verifySignatureEnvironmentElem.appendChild(base64ContentElem);
+ // insert the base64 encoded identity link SAML assertion
+ String serializedAssertion = identityLink.getSerializedSamlAssertion();
+ String base64EncodedAssertion = Base64Utils.encode(serializedAssertion.getBytes("UTF-8"));
+ //replace all '\r' characters by no char.
+ StringBuffer replaced = new StringBuffer();
+ for (int i = 0; i < base64EncodedAssertion.length(); i ++) {
+ char c = base64EncodedAssertion.charAt(i);
+ if (c != '\r') {
+ replaced.append(c);
+ }
+ }
+ base64EncodedAssertion = replaced.toString();
+ Node base64Content = requestDoc_.createTextNode(base64EncodedAssertion);
+ base64ContentElem.appendChild(base64Content);
+ // specify the signature location
+ Element verifySignatureLocationElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation");
+ verifiySignatureInfoElem.appendChild(verifySignatureLocationElem);
+ Node signatureLocation = requestDoc_.createTextNode(DSIG + "Signature");
+ verifySignatureLocationElem.appendChild(signatureLocation);
+ // signature manifest params
+ Element signatureManifestCheckParamsElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams");
+ requestElem_.appendChild(signatureManifestCheckParamsElem);
+ signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "false");
+ // add the transforms
+ Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo");
+ signatureManifestCheckParamsElem.appendChild(referenceInfoElem);
+ Element[] dsigTransforms = identityLink.getDsigReferenceTransforms();
+
+ for (int i = 0; i < dsigTransforms.length; i++) {
+ Element verifyTransformsInfoProfileElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfile");
+ referenceInfoElem.appendChild(verifyTransformsInfoProfileElem);
+ verifyTransformsInfoProfileElem.appendChild(requestDoc_.importNode(dsigTransforms[i], true));
+ }
+ Element returnHashInputDataElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData");
+ requestElem_.appendChild(returnHashInputDataElem);
+ Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID");
+ trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID));
+ requestElem_.appendChild(trustProfileIDElem);
+ } catch (Throwable t) {
+ throw new ParseException("builder.00",
+ new Object[] { "VerifyXMLSignatureRequest (IdentityLink)" }, t);
+ }
+
+ return requestElem_;
+ }
+
+ /**
+ * Builds a <code>&lt;VerifyXMLSignatureRequest&gt;</code>
+ * from an IdentityLink with a known trustProfileID which
+ * has to exist in MOA-SP
+ * @param identityLink - The IdentityLink
+ * @param trustProfileID - a preconfigured TrustProfile at MOA-SP
+ *
+ * @return Element - The complete request as Dom-Element
+ *
+ * @throws ParseException
+ */
+ public Element build(byte[]mandate, String trustProfileID)
+ throws ParseException
+ {
+ try {
+ // build the request
+// Element dateTimeElem = requestDoc_.createElementNS(MOA_NS_URI, "DateTime");
+// requestElem_.appendChild(dateTimeElem);
+// Node dateTime = requestDoc_.createTextNode(identityLink.getIssueInstant());
+// dateTimeElem.appendChild(dateTime);
+ Element verifiySignatureInfoElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo");
+ requestElem_.appendChild(verifiySignatureInfoElem);
+ Element verifySignatureEnvironmentElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment");
+ verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem);
+ Element base64ContentElem = requestDoc_.createElementNS(MOA_NS_URI, "Base64Content");
+ verifySignatureEnvironmentElem.appendChild(base64ContentElem);
+ // insert the base64 encoded identity link SAML assertion
+ //String serializedAssertion = identityLink.getSerializedSamlAssertion();
+ //String base64EncodedAssertion = Base64Utils.encode(mandate.getBytes("UTF-8"));
+ String base64EncodedAssertion = Base64Utils.encode(mandate);
+ //replace all '\r' characters by no char.
+ StringBuffer replaced = new StringBuffer();
+ for (int i = 0; i < base64EncodedAssertion.length(); i ++) {
+ char c = base64EncodedAssertion.charAt(i);
+ if (c != '\r') {
+ replaced.append(c);
+ }
+ }
+ base64EncodedAssertion = replaced.toString();
+ Node base64Content = requestDoc_.createTextNode(base64EncodedAssertion);
+ base64ContentElem.appendChild(base64Content);
+ // specify the signature location
+ Element verifySignatureLocationElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation");
+ verifiySignatureInfoElem.appendChild(verifySignatureLocationElem);
+ Node signatureLocation = requestDoc_.createTextNode(DSIG + "Signature");
+ verifySignatureLocationElem.appendChild(signatureLocation);
+ // signature manifest params
+ Element signatureManifestCheckParamsElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams");
+ requestElem_.appendChild(signatureManifestCheckParamsElem);
+ signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "false");
+// // add the transforms
+// Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo");
+// signatureManifestCheckParamsElem.appendChild(referenceInfoElem);
+// Element[] dsigTransforms = identityLink.getDsigReferenceTransforms();
+//
+// for (int i = 0; i < dsigTransforms.length; i++) {
+// Element verifyTransformsInfoProfileElem =
+// requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfile");
+// referenceInfoElem.appendChild(verifyTransformsInfoProfileElem);
+// verifyTransformsInfoProfileElem.appendChild(requestDoc_.importNode(dsigTransforms[i], true));
+// }
+ Element returnHashInputDataElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData");
+ requestElem_.appendChild(returnHashInputDataElem);
+ Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID");
+ trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID));
+ requestElem_.appendChild(trustProfileIDElem);
+ } catch (Throwable t) {
+ throw new ParseException("builder.00",
+ new Object[] { "VerifyXMLSignatureRequest (IdentityLink)" }, t);
+ }
+
+ return requestElem_;
+ }
+
+
+ /**
+ * Builds a <code>&lt;VerifyXMLSignatureRequest&gt;</code>
+ * from the signed AUTH-Block with a known trustProfileID which
+ * has to exist in MOA-SP
+ * @param csr - signed AUTH-Block
+ * @param verifyTransformsInfoProfileID - allowed verifyTransformsInfoProfileID
+ * @param trustProfileID - a preconfigured TrustProfile at MOA-SP
+ * @return Element - The complete request as Dom-Element
+ * @throws ParseException
+ */
+ public Element build(
+ CreateXMLSignatureResponse csr,
+ List<String> verifyTransformsInfoProfileID,
+ String trustProfileID)
+ throws BuildException { //samlAssertionObject
+
+ try {
+ // build the request
+// requestElem_.setAttributeNS(Constants.XMLNS_NS_URI, "xmlns:"
+// + Constants.XML_PREFIX, Constants.XMLNS_NS_URI);
+ Element verifiySignatureInfoElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo");
+ requestElem_.appendChild(verifiySignatureInfoElem);
+ Element verifySignatureEnvironmentElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment");
+ verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem);
+ Element xmlContentElem = requestDoc_.createElementNS(MOA_NS_URI, "XMLContent");
+ verifySignatureEnvironmentElem.appendChild(xmlContentElem);
+ xmlContentElem.setAttribute(Constants.XML_PREFIX + ":space", "preserve");
+ // insert the SAML assertion
+ xmlContentElem.appendChild(requestDoc_.importNode(csr.getSamlAssertion(), true));
+ // specify the signature location
+ Element verifySignatureLocationElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation");
+ verifiySignatureInfoElem.appendChild(verifySignatureLocationElem);
+ Node signatureLocation = requestDoc_.createTextNode(DSIG + "Signature");
+ verifySignatureLocationElem.appendChild(signatureLocation);
+ // signature manifest params
+ Element signatureManifestCheckParamsElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams");
+ requestElem_.appendChild(signatureManifestCheckParamsElem);
+ signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "true");
+ // add the transform profile IDs
+ Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo");
+ signatureManifestCheckParamsElem.appendChild(referenceInfoElem);
+
+// for (int i = 0; i < verifyTransformsInfoProfileID.length; i++) {
+//
+// Element verifyTransformsInfoProfileIDElem =
+// requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfileID");
+// referenceInfoElem.appendChild(verifyTransformsInfoProfileIDElem);
+// verifyTransformsInfoProfileIDElem.appendChild(
+// requestDoc_.createTextNode(verifyTransformsInfoProfileID[i]));
+// }
+
+ for (String element : verifyTransformsInfoProfileID) {
+
+ Element verifyTransformsInfoProfileIDElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfileID");
+ referenceInfoElem.appendChild(verifyTransformsInfoProfileIDElem);
+ verifyTransformsInfoProfileIDElem.appendChild(
+ requestDoc_.createTextNode(element));
+ }
+
+ Element returnHashInputDataElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData");
+ requestElem_.appendChild(returnHashInputDataElem);
+ Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID");
+ trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID));
+ requestElem_.appendChild(trustProfileIDElem);
+
+ } catch (Throwable t) {
+ throw new BuildException("builder.00", new Object[] { "VerifyXMLSignatureRequest" }, t);
+ }
+
+ return requestElem_;
+ }
+
+ /**
+ * Builds a <code>&lt;VerifyXMLSignatureRequest&gt;</code>
+ * from the signed data with a known trustProfileID which
+ * has to exist in MOA-SP
+ * @param csr - signed AUTH-Block
+ * @param trustProfileID - a preconfigured TrustProfile at MOA-SP
+ * @return Element - The complete request as Dom-Element
+ * @throws ParseException
+ */
+ public Element buildDsig(
+ CreateXMLSignatureResponse csr,
+ String trustProfileID)
+ throws BuildException { //samlAssertionObject
+
+ try {
+ // build the request
+// requestElem_.setAttributeNS(Constants.XMLNS_NS_URI, "xmlns:"
+// + Constants.XML_PREFIX, Constants.XMLNS_NS_URI);
+
+ Element verifiySignatureInfoElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo");
+ requestElem_.appendChild(verifiySignatureInfoElem);
+ Element verifySignatureEnvironmentElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment");
+ verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem);
+
+ Element xmlContentElem = requestDoc_.createElementNS(MOA_NS_URI, "XMLContent");
+ verifySignatureEnvironmentElem.appendChild(xmlContentElem);
+ xmlContentElem.setAttribute(Constants.XML_PREFIX + ":space", "preserve");
+
+ // insert the dsig:Signature
+ xmlContentElem.appendChild(requestDoc_.importNode(csr.getDsigSignature(), true));
+ // specify the signature location
+ Element verifySignatureLocationElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation");
+ verifiySignatureInfoElem.appendChild(verifySignatureLocationElem);
+ Node signatureLocation = requestDoc_.createTextNode("/"+ DSIG + "Signature");
+ verifySignatureLocationElem.appendChild(signatureLocation);
+ // signature manifest params
+ Element signatureManifestCheckParamsElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams");
+ requestElem_.appendChild(signatureManifestCheckParamsElem);
+ signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "true");
+ // add the transform profile IDs
+ Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo");
+ signatureManifestCheckParamsElem.appendChild(referenceInfoElem);
+
+ Element returnHashInputDataElem =
+ requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData");
+ requestElem_.appendChild(returnHashInputDataElem);
+ Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID");
+
+ trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID));
+ requestElem_.appendChild(trustProfileIDElem);
+
+ } catch (Throwable t) {
+ throw new BuildException("builder.00", new Object[] { "VerifyXMLSignatureRequest" }, t);
+ }
+
+ return requestElem_;
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java
new file mode 100644
index 000000000..72a7d3ba1
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java
@@ -0,0 +1,142 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.invoke;
+
+import java.util.Vector;
+
+import javax.xml.namespace.QName;
+import javax.xml.rpc.Call;
+import javax.xml.rpc.Service;
+import javax.xml.rpc.ServiceFactory;
+
+import org.apache.axis.message.SOAPBodyElement;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import at.gv.egovernment.moa.id.auth.exception.ServiceException;
+import at.gv.egovernment.moa.id.config.ConnectionParameter;
+import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.spss.api.SignatureVerificationService;
+import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureRequestParser;
+import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureResponseBuilder;
+import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest;
+import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse;
+import at.gv.egovernment.moa.util.MiscUtil;
+
+/**
+ * Invoker of the <code>SignatureVerification</code> web service of MOA-SPSS.<br>
+ * Either invokes the web service, or calls the corresponding API, depending on configuration data.
+ *
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+public class SignatureVerificationInvoker {
+ /** This QName Object identifies the SignatureVerification endpoint of the web service */
+ private static final QName SERVICE_QNAME = new QName("SignatureVerification");
+
+ /**
+ * Method verifyXMLSignature.
+ * @param request to be sent
+ * @return Element with the answer
+ * @throws ServiceException if an error occurs
+ */
+ public Element verifyXMLSignature(Element request) throws ServiceException {
+ return doCall(SERVICE_QNAME, request);
+ }
+
+ /**
+ * Method doCall.
+ * @param serviceName the name of the service
+ * @param request the request to be sent
+ * @return Element the answer
+ * @throws ServiceException if an error occurs
+ */
+ protected Element doCall(QName serviceName, Element request) throws ServiceException {
+ ConnectionParameter authConnParam = null;
+ try {
+ Service service = ServiceFactory.newInstance().createService(serviceName);
+ Call call = service.createCall();
+ SOAPBodyElement body = new SOAPBodyElement(request);
+ SOAPBodyElement[] params = new SOAPBodyElement[] { body };
+ Vector responses;
+ SOAPBodyElement response;
+
+ String endPoint;
+ AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance();
+ authConnParam = authConfigProvider.getMoaSpConnectionParameter();
+ //If the ConnectionParameter do NOT exist, we try to get the api to work....
+ if (authConnParam != null && MiscUtil.isNotEmpty(authConnParam.getUrl())) {
+ Logger.debug("Connecting using auth url: " + authConnParam.getUrl() + ", service " + serviceName.getNamespaceURI() + " : " + serviceName.getLocalPart() + " : "+ serviceName.getPrefix());
+ endPoint = authConnParam.getUrl();
+ call.setTargetEndpointAddress(endPoint);
+ responses = (Vector) call.invoke(serviceName, params);
+ Logger.debug("Got responses: " + responses.size()); // TODO handle axis 302 response when incorrect service url is used
+ response = (SOAPBodyElement) responses.get(0);
+ return response.getAsDOM();
+ }
+ else {
+ SignatureVerificationService svs = SignatureVerificationService.getInstance();
+ VerifyXMLSignatureRequest vsrequest = new VerifyXMLSignatureRequestParser().parse(request);
+
+ VerifyXMLSignatureResponse vsresponse = svs.verifyXMLSignature(vsrequest);
+ Document result = new VerifyXMLSignatureResponseBuilder().build(vsresponse);
+
+ //Logger.setHierarchy("moa.id.auth");
+ return result.getDocumentElement();
+ }
+ }
+ catch (Exception ex) {
+ if (authConnParam != null) {
+ throw new ServiceException("service.00", new Object[] { ex.toString()}, ex);
+ } else {
+ throw new ServiceException("service.03", new Object[] { ex.toString()}, ex);
+ }
+ }
+ }
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java
new file mode 100644
index 000000000..cac7359c7
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java
@@ -0,0 +1,36 @@
+package at.gv.egovernment.moa.id.auth.modules.internal;
+
+import org.apache.commons.lang3.StringUtils;
+
+import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
+import at.gv.egovernment.moa.id.auth.modules.AuthModule;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+
+/**
+ * Module descriptor
+ */
+public class DefaultAuthModuleImpl implements AuthModule {
+
+ @Override
+ public int getPriority() {
+ return 0;
+ }
+
+ @Override
+ public String selectProcess(ExecutionContext context) {
+ //select process if BKU is selected and it is no STORK authentication
+ if (StringUtils.isBlank((String) context.get("ccc")) &&
+ StringUtils.isNotBlank((String) context.get(MOAIDAuthConstants.PARAM_BKU)))
+ return "DefaultAuthentication";
+
+ else
+ return 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/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java
new file mode 100644
index 000000000..7e1bf1fc7
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.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 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.auth.modules.AbstractAuthServletTask;
+import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
+
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+import at.gv.egovernment.moa.id.util.CitizenCardServletUtils;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.<p/>
+ * In detail:
+ * <ul>
+ * <li>Renames the moa session id.</li>
+ * <li>Creates {@code InfoBoxReadRequest} in order to read the subject's certificates.</li>
+ * <li>Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code /VerifyCertificate}</li>
+ * </ul>
+ * Expects:
+ * <ul>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
+ * </ul>
+ * Result:
+ * <ul>
+ * <li>Responds with {@code InfoBoxReadRequest} (for CCE), {@code DataURL} is {@code /VerifyCertificate}</li>
+ * </ul>
+ * 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 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);
+ try {
+
+ String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID));
+
+ // check parameter
+ if (!ParamValidatorUtils.isValidSessionID(sessionID)) {
+ throw new WrongParametersException("CertificateReadRequestTask", PARAM_SESSIONID, "auth.12");
+ }
+
+ 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());
+
+ CitizenCardServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest,
+ AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl);
+
+ } catch (MOAIDException ex) {
+ throw new TaskExecutionException(ex.getMessage(), ex);
+
+ } catch (IOException e) {
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ } finally {
+
+ }
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java
new file mode 100644
index 000000000..20f102571
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java
@@ -0,0 +1,138 @@
+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.BooleanUtils;
+import org.apache.commons.lang3.ObjectUtils;
+
+import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils;
+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.modules.TaskExecutionException;
+import at.gv.egovernment.moa.id.auth.servlet.GenerateIFrameTemplateServlet;
+
+import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.RequestStorage;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.MiscUtil;
+import at.gv.egovernment.moa.util.StringUtils;
+
+/**
+ * Creates a http form including an embedded {@code InfoBoxReadRequest} for reading the identity link.<p/>
+ * In detail:
+ * <ul>
+ * <li>Renames the moa session id.</li>
+ * <li>Removes ExecutionContext property {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}.</li>
+ * <li>Creates the http form mentioned above.</li>
+ * <li>Returns the http form via HttpServletResponse.</li>
+ * </ul>
+ * Expects:
+ * <ul>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID} <strong>or</strong></li>
+ * <li>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).</li>
+ * </ul>
+ * Result:
+ * <ul>
+ * <li>The identity link form via HttpServletResponse.</li>
+ * </ul>
+ * Possible branches:
+ * <ul>
+ * <li>In case of STORK authentication
+ * <ul>
+ * <li>Creates STORK auth SAML request.</li>
+ * <li>Creates and returns a form for submitting the SAML request to the CPEPS (post binding).</li>
+ * <li>Returns the form via HttpServletResponse.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ * 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 TaskExecutionException {
+
+ 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 {
+ 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);
+
+ IRequest pendingReq = RequestStorage.getPendingRequest(
+ (String) executionContext.get("pendingRequestID"));
+
+ if (BooleanUtils.isTrue((Boolean) executionContext.get("useMandate")))
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_MANDATES_REQUESTED);
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_URL, moasession.getBkuURL());
+
+ 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);
+ 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("CreateIdentityLinkFormTask has an interal Error.", e);
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ }
+
+ finally {
+
+ TransactionIDUtils.removeTransactionId();
+ TransactionIDUtils.removeSessionId();
+ }
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java
new file mode 100644
index 000000000..b729f26e1
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java
@@ -0,0 +1,192 @@
+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.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+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.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;
+import at.gv.egovernment.moa.id.client.utils.SZRGWClientUtils;
+import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.ModulUtils;
+import at.gv.egovernment.moa.id.moduls.RequestStorage;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse;
+
+/**
+ * Evaluates the {@code CreateXMLSignatureResponse}, extracts signature and certificate and asks the SZR Gateway for an identity link.<p/>
+ * In detail:
+ * <ul>
+ * <li>Renames the moa session id.</li>
+ * <li>Parses the CreateXMLSignatureResponse retrieved from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.</li>
+ * <li>Extracts signature and signer certificate.</li>
+ * <li>Send request to SZR Gateway in order to get an identity link.</li>
+ * <li>Updates moa session (sets identity link, QAA level 4, authentication data and foreigner flag).</li>
+ * <li>Redirects back to {@code /dispatcher} in order to finalize authentication.</li>
+ * </ul>
+ * Expects:
+ * <ul>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.</li>
+ * </ul>
+ * Result:
+ * <ul>
+ * <li>Identity link, QAA level 4 and foreigner flag put into moa session.</li>
+ * <li>Redirect to {@code /dispatcher}.</li>
+ * </ul>
+ * 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 TaskExecutionException {
+
+ Logger.debug("POST GetForeignIDServlet");
+
+ setNoCachingHeaders(resp);
+
+ Map<String, String> parameters;
+
+ try {
+ parameters = getParameters(req);
+
+ } catch (FileUploadException | IOException e) {
+ Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
+ throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", 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);
+
+ IRequest pendingReq = RequestStorage.getPendingRequest(
+ (String) executionContext.get("pendingRequestID"));
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost());
+
+ // 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);
+ }
+
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_FOREIGN_SZRGW_CONNECTED);
+
+ // make SZR request to the identity link
+ CreateIdentityLinkResponse response = SZRGWClientUtils.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);
+
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_FOREIGN_SZRGW_RECEIVED);
+
+ try {
+ AuthenticationSessionStoreage.storeSession(session);
+ } catch (MOADatabaseException e) {
+ throw new MOAIDException("Session store error", null);
+ }
+
+ //put session to context
+ executionContext.put(PARAM_SESSIONID, session.getSessionID());
+ }
+
+ } catch (MOAIDException ex) {
+ 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/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java
new file mode 100644
index 000000000..d85681b40
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java
@@ -0,0 +1,184 @@
+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.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+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.auth.modules.AbstractAuthServletTask;
+import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
+
+import at.gv.egovernment.moa.id.config.ConnectionParameter;
+import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.data.MISMandate;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.ModulUtils;
+import at.gv.egovernment.moa.id.moduls.RequestStorage;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.id.util.SSLUtils;
+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;
+
+/**
+ * Retrieves a mandate from the online mandate issuing service.<p/>
+ * In detail:
+ * <ul>
+ * <li>Renames the moa session id.</li>
+ * <li>Retrieves the mandate referenced within the moa session from the online (external) mandate issuing service.</li>
+ * <li>Verifies the mandate.</li>
+ * <li>Puts mandate into moa session.</li>
+ * <li>Redirects back to {@code /dispatcher} in order to finalize the authentication.</li>
+ * </ul>
+ * Expects:
+ * <ul>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
+ * </ul>
+ * Result:
+ * <ul>
+ * <li>Mandate put into moa session.</li>
+ * <li>Redirect to {@code /dispatcher}.</li>
+ * </ul>
+ * 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 TaskExecutionException {
+
+ 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);
+
+ IRequest pendingReq = RequestStorage.getPendingRequest(
+ (String) executionContext.get("pendingRequestID"));
+
+ //change MOASessionID
+ sessionID = AuthenticationSessionStoreage.changeSessionID(session);
+
+ String misSessionID = session.getMISSessionID();
+
+ AuthConfiguration authConf = AuthConfigurationProviderFactory
+ .getInstance();
+ ConnectionParameter connectionParameters = authConf
+ .getOnlineMandatesConnectionParameter();
+ SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(
+ AuthConfigurationProviderFactory.getInstance(),
+ connectionParameters);
+
+ List<MISMandate> list = MISSimpleClient.sendGetMandatesRequest(
+ connectionParameters.getUrl(), misSessionID, sslFactory);
+
+ if (list == null || list.size() == 0) {
+ Logger.error("Keine Vollmacht gefunden.");
+ throw new AuthenticationException("auth.15", null);
+ }
+
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_MANDATE_RECEIVED);
+
+
+ // 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);
+
+ //log mandate specific set of events
+ MOAReversionLogger.getInstance().logMandateEventSet(pendingReq, mandate);
+
+ 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);
+
+ //put session to context
+ executionContext.put(PARAM_SESSIONID, session.getSessionID());
+
+
+ } catch (MOAIDException ex) {
+ throw new TaskExecutionException(ex.getMessage(), ex);
+
+ } catch (GeneralSecurityException ex) {
+ throw new TaskExecutionException(ex.getMessage(), ex);
+
+ } catch (PKIException e) {
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ } catch (SAXException e) {
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ } catch (ParserConfigurationException e) {
+ 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/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java
new file mode 100644
index 000000000..a86385d06
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java
@@ -0,0 +1,189 @@
+/*
+ * 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.internal.tasks;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+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.AuthenticationException;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask;
+import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
+import at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser;
+import at.gv.egovernment.moa.id.commons.db.dao.config.deprecated.MOAAuthDataType;
+import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.RequestStorage;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.FileUtils;
+import at.gv.egovernment.moa.util.MiscUtil;
+
+/**
+ * @author tlenz
+ *
+ */
+public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask {
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ @Override
+ public void execute(ExecutionContext executionContext,
+ HttpServletRequest request, HttpServletResponse response)
+ throws TaskExecutionException {
+
+ try {
+ String moasessionid = (String) executionContext.get(MOAIDAuthConstants.PARAM_SESSIONID);
+ String pendingRequestID = (String) executionContext.get("pendingRequestID");
+
+ //load pending request
+ IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
+ if (pendingReq == null) {
+ Logger.info("No PendingRequest with Id: " + pendingRequestID + " Maybe, a transaction timeout occure.");
+ throw new MOAIDException("auth.28", new Object[]{pendingRequestID});
+
+ }
+
+ //load MOASession object
+ AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moasessionid);
+
+ boolean isLegacyRequest = false;
+ Object isLegacyRequestObj = executionContext.get("isLegacyRequest");
+ if (isLegacyRequestObj != null && isLegacyRequestObj instanceof Boolean)
+ isLegacyRequest = (boolean) isLegacyRequestObj;
+
+ if (isLegacyRequest) {
+ //parse request parameter into MOASession
+ Logger.info("Start Authentication Module: " + moasession.getModul()
+ + " Action: " + moasession.getAction());
+
+ StartAuthentificationParameterParser.parse(executionContext, request, moasession, pendingReq);
+
+ } else {
+ String bkuid = (String) executionContext.get(MOAIDAuthConstants.PARAM_BKU);
+ String useMandate = (String) executionContext.get(MOAIDAuthConstants.PARAM_USEMANDATE);
+ String ccc = (String) executionContext.get(MOAIDAuthConstants.PARAM_CCC);
+
+ //remove MOASessionID from executionContext because it is not needed any more
+
+
+ if (MiscUtil.isEmpty(bkuid) || MiscUtil.isEmpty(moasessionid)) {
+ Logger.warn("MOASessionID or BKU-type is empty. Maybe an old BKU-selection template is in use.");
+ throw new MOAIDException("auth.23", new Object[] {});
+ }
+
+ //load OA Config
+ IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration();
+
+ if (oaParam == null)
+ throw new AuthenticationException("auth.00", new Object[] { moasession.getOAURLRequested() });
+
+ else {
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUTYPE_SELECTED, bkuid);
+
+ //get Target from config or from request in case of SAML 1
+ String target = null;
+ if (MiscUtil.isNotEmpty(pendingReq.getTarget()) &&
+ pendingReq.requestedModule().equals("id_saml1"))
+ 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");
+ bkuURL = AuthConfigurationProviderFactory.getInstance().getDefaultBKUURL(bkuid);
+ }
+
+ //search for OA specific template
+ String templateURL = null;
+ List<String> oaTemplateURLList = oaParam.getTemplateURL();
+ if ( oaTemplateURLList != null && oaTemplateURLList.size() > 0
+ && MiscUtil.isNotEmpty(oaTemplateURLList.get(0)) ) {
+ templateURL = oaTemplateURLList.get(0);
+
+ } else {
+ templateURL = AuthConfigurationProviderFactory.getInstance().getSLRequestTemplates(bkuid);
+ }
+
+ //make url absolut if it is a local url
+ if (MiscUtil.isNotEmpty(templateURL))
+ templateURL = FileUtils.makeAbsoluteURL(templateURL,
+ AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir());
+
+ if (oaParam.isOnlyMandateAllowed())
+ useMandate = "true";
+
+ if (!oaParam.isShowMandateCheckBox())
+ useMandate = "false";
+
+ //parse all OA parameters i
+ StartAuthentificationParameterParser.parse(moasession,
+ target,
+ moasession.getOAURLRequested(),
+ bkuURL,
+ templateURL,
+ useMandate,
+ ccc,
+ moasession.getModul(),
+ moasession.getAction(),
+ request,
+ pendingReq);
+ }
+ }
+
+ executionContext.put(MOAIDAuthConstants.PARAM_USEMANDATE, moasession.getUseMandate());
+
+ // 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()});
+ }
+
+
+ } catch (MOADatabaseException | MOAIDException e) {
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ } catch (Exception e) {
+ Logger.warn("InitializeBKUAuthentication has an internal error", e);
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ }
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java
new file mode 100644
index 000000000..469ca91a9
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.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 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.auth.modules.TaskExecutionException;
+
+import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+import at.gv.egovernment.moa.id.util.CitizenCardServletUtils;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * Creates {@code CreateXMLSignatureRequest} for auth block signature.<p/>
+ * In detail:
+ * <ul>
+ * <li>Renames the moa session id.</li>
+ * <li>Creates {@code CreateXMLSignatureRequest} for auth block signature.</li>
+ * <li>Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code /VerifyAuthBlock}</li>
+ * </ul>
+ * Expects:
+ * <ul>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
+ * </ul>
+ * Result:
+ * <ul>
+ * <li>Responds with {@code CreateXMLSignatureRequest} (for CCE), {@code DataURL} is {@code /VerifyAuthBlock}</li>
+ * </ul>
+ * 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 TaskExecutionException {
+ // 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);
+
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(
+ session.getPublicOAURLPrefix());
+ AuthConfiguration authConf = AuthConfigurationProviderFactory.getInstance();
+
+ String createXMLSignatureRequest = AuthenticationServer.getInstance()
+ .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam);
+
+ AuthenticationSessionStoreage.storeSession(session);
+
+ CitizenCardServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session,
+ createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT,
+ "VerifyIdentityLink");
+
+ } catch (MOAIDException ex) {
+ 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/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java
new file mode 100644
index 000000000..099bc085c
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java
@@ -0,0 +1,207 @@
+/*
+ * 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.internal.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 java.util.List;
+
+import javax.net.ssl.SSLSocketFactory;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.w3c.dom.Element;
+
+import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+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.BuildException;
+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.modules.AbstractAuthServletTask;
+import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
+import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.config.ConnectionParameter;
+import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters;
+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.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+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 at.gv.egovernment.moa.util.MiscUtil;
+
+/**
+ * @author tlenz
+ *
+ */
+public class PrepareGetMISMandateTask extends AbstractAuthServletTask {
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ @Override
+ public void execute(ExecutionContext executionContext,
+ HttpServletRequest request, HttpServletResponse response)
+ throws TaskExecutionException {
+
+ //mandate Mode
+ try {
+ IRequest pendingReq = RequestStorage.getPendingRequest(
+ (String) executionContext.get("pendingRequestID"));
+
+ //get Session from context
+ String moasessionid = (String) executionContext.get(PARAM_SESSIONID);
+ AuthenticationSession session = null;
+ if (MiscUtil.isEmpty(moasessionid)) {
+ Logger.warn("MOASessionID is empty.");
+ throw new MOAIDException("auth.18", new Object[] {});
+ }
+
+ try {
+ session = AuthenticationSessionStoreage.getSession(moasessionid);
+ AuthenticationSessionStoreage.changeSessionID(session);
+
+ } 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[] {});
+
+ } finally {
+ executionContext.remove(PARAM_SESSIONID);
+
+ }
+
+
+ AuthConfiguration authConf= AuthConfigurationProviderFactory.getInstance();
+ ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter();
+ SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProviderFactory.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);
+
+ String redirectURL = new DataURLBuilder().buildDataURL(
+ session.getAuthURL(),
+ GET_MIS_SESSIONID,
+ newMOASessionID);
+
+ String oaURL = session.getOAURLRequested();
+ IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration();
+ if (oaParam == null) {
+ oaParam = authConf.getOnlineApplicationParameter(oaURL);
+ Logger.info("No Service info in PendingRequest --> load service info from configuration");
+
+ }
+
+ List<String> 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();
+ }
+
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_MANDATE_SERVICE_REQUESTED, mandateReferenceValue);
+
+ 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 | BuildException e) {
+ throw new MOAIDException("Session store error", null);
+
+ }
+
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_MANDATE_REDIRECT);
+
+ response.setStatus(302);
+ response.addHeader("Location", redirectMISGUI);
+ Logger.debug("REDIRECT TO: " + redirectMISGUI);
+
+ } catch (Exception e ) {
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ }
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java
new file mode 100644
index 000000000..35104bf3e
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java
@@ -0,0 +1,160 @@
+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.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.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+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.auth.modules.AbstractAuthServletTask;
+import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
+
+import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.config.ConnectionParameter;
+import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.ModulUtils;
+import at.gv.egovernment.moa.id.moduls.RequestStorage;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.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;
+
+/**
+ * Verifies the signed authentication block (provided as {@code CreateXMLSignatureResponse}).<p/>
+ * In detail:
+ * <ul>
+ * <li>Renames the moa session id.</li>
+ * <li>Takes the {@code CreateXMLSignatureResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.</li>
+ * <li>Verifies the {@code CreateXMLSignatureResponse}.</li>
+ * <li>Updates moa session.</li>
+ * <li>Redirects back to {@code /dispatcher} in order to finalize the authentication.</li>
+ * </ul>
+ * Expects:
+ * <ul>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code CreateXMLSignatureResponse}.</li>
+ * </ul>
+ * Result:
+ * <ul>
+ * <li>Authentication data put into moa session.</li>
+ * <li>Redirect to {@code /dispatcher}.</li>
+ * </ul>
+ * Possible branches:
+ * <ul>
+ * <li>In case of mandate mode
+ * <ul>
+ * <li>Creates a mandate session at the external mandate issuing service.</li>
+ * <li>Redirects the user's browser to the online mandate issuing service GUI.</li>
+ * </ul>
+ * </li>
+ * </ul>
+ * 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 TaskExecutionException {
+
+ // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet
+
+ Logger.debug("POST VerifyAuthenticationBlock");
+
+ String pendingRequestID = null;
+
+ Map<String, String> parameters;
+ try
+ {
+ parameters = getParameters(req);
+
+ } catch (FileUploadException | IOException e)
+ {
+ Logger.error("Parsing mulitpart/form-data request parameters failed: " + 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);
+
+ // 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);
+
+ IRequest pendingReq = RequestStorage.getPendingRequest(
+ (String) executionContext.get("pendingRequestID"));
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost());
+
+ //change MOASessionID
+ sessionID = AuthenticationSessionStoreage.changeSessionID(session);
+
+ AuthenticationServer.getInstance().verifyAuthenticationBlock(pendingReq, session, createXMLSignatureResponse);
+
+ //store all changes in session DAO
+ AuthenticationSessionStoreage.storeSession(session);
+
+ //put session to context
+ executionContext.put(PARAM_SESSIONID, session.getSessionID());
+
+ }
+
+ catch (MOAIDException ex) {
+ throw new TaskExecutionException(ex.getMessage(), ex);
+
+
+
+ } catch (Exception e) {
+ Logger.error("AuthBlockValidation has an interal Error.", e);
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ }
+
+
+ finally {
+
+ }
+
+
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java
new file mode 100644
index 000000000..d99ba873d
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java
@@ -0,0 +1,175 @@
+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.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+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.auth.modules.AbstractAuthServletTask;
+import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
+
+import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.RequestStorage;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+import at.gv.egovernment.moa.id.util.CitizenCardServletUtils;
+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;
+
+/**
+ * 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.<p/>
+ * In detail:
+ * <ul>
+ * <li>Renames the moa session id.</li>
+ * <li>Retrieves the certificate via {@code InfoBoxReadResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.</li>
+ * <li>Verifies the certificate.</li>
+ * <li>Creates the auth block to be signed using information from the certificate (Organwalter, foreign citizen.</li>
+ * <li>Puts it in a {@code CreateXMLSignatureRequest}.</li>
+ * <li>Updates moa session.</li>
+ * <li>Responds with {@code CreateXMLSignatureRequest}.</li>
+ * </ul>
+ * Expects:
+ * <ul>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_SESSIONID} containing a {@code InfoBoxReadResponse}.</li>
+ * </ul>
+ * Result:
+ * <ul>
+ * <li>{@code CreateXMLSignatureRequest} send as HttpServletResponse (for CCE).</li>
+ * </ul>
+ * 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 TaskExecutionException {
+
+ // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet
+
+ Logger.debug("POST VerifyCertificateServlet");
+
+ Map<String, String> parameters;
+ try
+ {
+ parameters = getParameters(req);
+ } catch (FileUploadException | IOException e)
+ {
+ Logger.error("Parsing mulitpart/form-data request parameters failed: " + 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);
+
+ AuthenticationSession session = null;
+ try {
+ // check parameter
+ if (!ParamValidatorUtils.isValidSessionID(sessionID))
+ throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12");
+
+ session = AuthenticationServer.getSession(sessionID);
+
+ IRequest pendingReq = RequestStorage.getPendingRequest(
+ (String) executionContext.get("pendingRequestID"));
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost());
+
+ //change MOASessionID
+ sessionID = AuthenticationSessionStoreage.changeSessionID(session);
+
+ X509Certificate cert = AuthenticationServer.getInstance().getCertificate(pendingReq, 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"
+ CitizenCardServletUtils.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
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_FOREIGN_FOUND);
+
+ 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"
+ CitizenCardServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl);
+
+ Logger.debug("Send CreateXMLSignatureRequest to BKU");
+ }
+ }
+ catch (MOAIDException ex) {
+ throw new TaskExecutionException(ex.getMessage(), ex);
+
+ } catch (Exception e) {
+ Logger.error("CertificateValidation has an interal Error.", e);
+ throw new TaskExecutionException(e.getMessage(), e);
+
+ }
+
+
+ finally {
+
+ }
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java
new file mode 100644
index 000000000..50ef11f27
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java
@@ -0,0 +1,111 @@
+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.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+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.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.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.RequestStorage;
+import at.gv.egovernment.moa.id.process.api.ExecutionContext;
+import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * Verifies the identity link.<p/>
+ * In detail:
+ * <ul>
+ * <li>Renames the moa session id.</li>
+ * <li>Parses the identity link retrieved as {@code InfoBoxReadResponse} from POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}.</li>
+ * <li>Verifies the identity link.</li>
+ * <li>Updates moa session.</li>
+ * <li>Puts boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.</li>
+ * </ul>
+ * Expects:
+ * <ul>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
+ * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE} containing a {@code InfoBoxReadResponse}.</li>
+ * </ul>
+ * Result:
+ * <ul>
+ * <li>Identity link put into moa session.</li>
+ * <li>Boolean flag {@code identityLinkAvailable} into {@code ExecutionContext}.</li>
+ * </ul>
+ * 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 TaskExecutionException {
+
+ // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet
+
+ Logger.debug("POST VerifyIdentityLink");
+
+ setNoCachingHeaders(resp);
+
+ Map<String, String> parameters;
+
+ try {
+ parameters = getParameters(req);
+ } catch (Exception e) {
+ Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage());
+ throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", 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");
+ }
+ AuthenticationSession session = AuthenticationServer.getSession(sessionID);
+
+ IRequest pendingReq = RequestStorage.getPendingRequest(
+ (String) executionContext.get("pendingRequestID"));
+ MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(),
+ pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost());
+
+ boolean identityLinkAvailable = AuthenticationServer.getInstance().verifyIdentityLink(pendingReq, session, parameters) != null;
+ AuthenticationSessionStoreage.storeSession(session);
+
+ executionContext.put("identityLinkAvailable", identityLinkAvailable);
+
+ } catch (ParseException ex) {
+ throw new TaskExecutionException(ex.getMessage(), ex);
+
+ } catch (MOAIDException ex) {
+ 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/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java
new file mode 100644
index 000000000..b39cf9e9b
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java
@@ -0,0 +1,285 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.parser;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.traversal.NodeIterator;
+
+import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse;
+import at.gv.egovernment.moa.id.auth.data.SAMLAttribute;
+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.ParseException;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.XPathUtils;
+
+/**
+ * Parses an <code>&lt;InfoboxReadResponse&gt;</code> returned from
+ * the security layer
+ *
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+
+public class CreateXMLSignatureResponseParser {
+ //
+ // XPath namespace prefix shortcuts
+ //
+
+ /** Xpath prefix for reaching SAML Namespaces */
+ private static final String SAML = Constants.SAML_PREFIX + ":";
+ /** Xpath prefix for reaching XML-DSIG Namespaces */
+ private static final String DSIG = Constants.DSIG_PREFIX + ":";
+ /** Xpath expression to the root element */
+ private static final String ROOT = ":CreateXMLSignatureResponse/";
+ /** Xpath expression to the SAML:Assertion element */
+ private static final String SAML_ASSERTION_XPATH = ROOT + SAML + "Assertion";
+ /** Xpath expression to the SAML:NameIdentifier element */
+ private static final String SAML_SUBJECT_NAME_IDENTIFIER_XPATH = SAML_ASSERTION_XPATH + "/" + SAML + "AttributeStatement/" + SAML + "Subject/" + SAML + "NameIdentifier";
+ /** Xpath expression to the AttributeStatement element */
+ private static final String SAML_ATTRIBUTE_XPATH = SAML_ASSERTION_XPATH + "/" + SAML + "AttributeStatement/" + SAML + "Attribute";
+ /** Xpath expression to the AttributeValue element */
+ private static final String SAML_ATTRIBUTE_VALUE_XPATH = SAML + "AttributeValue";
+
+
+ /** This is the root element of the CreateXMLsignatureResponse */
+ private Element sigResponse_;
+
+ /**
+ * Parses and validates the document given as string and extracts the
+ * root element.
+ *
+ * @param xmlResponse <code>&lt;CreateXMLSignatureResponse&gt;</code> as String
+ *
+ * @throws AuthenticationException if any authentication error occurs
+ * @throws ParseException if an element cannot be parsed
+ * @throws
+ */
+ public CreateXMLSignatureResponseParser(String xmlResponse) throws AuthenticationException, ParseException, BKUException{
+ try {
+ InputStream s = new ByteArrayInputStream(xmlResponse.getBytes("UTF-8"));
+ init(s);
+ }
+
+ catch (BKUException e) {
+ throw e;
+
+ } catch (Throwable t) {
+ throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+ }
+ }
+
+ /**
+ * Parses and validates the document given as stream and extracts the
+ * root element.
+ *
+ * @param is <code>&lt;InfoboxReadResponse&gt;</code> as InputStream
+ *
+ * @throws AuthenticationException If any authentication error occurs
+ * @throws ParseException If an element cannot be parsed
+ * @throws BKUException
+ */
+ public CreateXMLSignatureResponseParser(InputStream is) throws AuthenticationException, ParseException, BKUException {
+ init(is);
+ }
+
+ /**
+ * Constructor for CreateXMLSignatureResponseParser.
+ * The incoming Element will be used for further operations
+ * @param xmlResponse <code>&lt;InfoboxReadResponse&gt;</code> as InputStream
+ */
+ public CreateXMLSignatureResponseParser(Element xmlResponse) {
+ sigResponse_ = xmlResponse;
+ }
+
+ /**
+ * Initializes the parser.
+ * Parses and validates the document given as stream and extracts the
+ * root element.
+ *
+ * @param is The CreateXMLSignatureResponse as stream.
+ * @throws AuthenticationException if an authentication error occurs.
+ * @throws ParseException If an error occurs on parsing the the document.
+ * @throws BKUException
+ */
+ private void init(InputStream is) throws AuthenticationException, ParseException, BKUException {
+ try {
+
+ Element responseElem = DOMUtils.parseXmlValidating(is);
+
+ if ("CreateXMLSignatureResponse".equals(responseElem.getLocalName())) {
+ sigResponse_ = responseElem;
+ } else {
+ ErrorResponseParser erp = new ErrorResponseParser(responseElem);
+ throw new BKUException("auth.08",
+ new Object[] { erp.getErrorCode(), erp.getErrorInfo()},
+ erp.getErrorCode(),
+ erp.getErrorInfo());
+ }
+
+ } catch (BKUException e) {
+ throw e;
+
+ } catch (Throwable t) {
+ throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+ }
+ }
+
+ /**
+ * Unmarshalls the <@link sigResponse> to an
+ * <code>&lt;CreateXMLSignatureResponse&gt;</code> object.
+ *
+ * @return a <code>&lt;CreateXMLSignatureResponse&gt;</code> object
+ * @throws ParseException
+ */
+
+ public CreateXMLSignatureResponse parseResponseDsig() throws ParseException {
+ CreateXMLSignatureResponse cResp;
+ try {
+ cResp = new CreateXMLSignatureResponse();
+
+ NodeList list = sigResponse_.getElementsByTagNameNS(Constants.DSIG_NS_URI, "Signature");
+ Element dsigSignatureNode = (Element) list.item(0);
+
+ Element dsigSignatureElement = (Element) dsigSignatureNode;
+
+ cResp.setDsigSignature(dsigSignatureElement);
+ }
+ catch (Throwable t) {
+ throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+ }
+ return cResp;
+ }
+
+ /**
+ * Unmarshalls the <@link sigResponse> to an
+ * <code>&lt;CreateXMLSignatureResponse&gt;</code> object.
+ *
+ * @return a <code>&lt;CreateXMLSignatureResponse&gt;</code> object
+ * @throws ParseException
+ */
+
+ public CreateXMLSignatureResponse parseResponse() throws ParseException {
+ CreateXMLSignatureResponse cResp;
+ try {
+ cResp = new CreateXMLSignatureResponse();
+ String slPrefix = XPathUtils.getSlPrefix(sigResponse_);
+ cResp.setSamlNameIdentifier(XPathUtils.getElementValue(sigResponse_, "/" + slPrefix + SAML_SUBJECT_NAME_IDENTIFIER_XPATH, null));
+ cResp.setSamlAssertion((Element) XPathUtils.selectSingleNode(sigResponse_, "/" + slPrefix + SAML_ASSERTION_XPATH));
+ NodeIterator attrIter = XPathUtils.selectNodeIterator(sigResponse_, "/" + slPrefix + SAML_ATTRIBUTE_XPATH);
+ Element samlAttr;
+ List<SAMLAttribute> samlAttributes = new ArrayList<SAMLAttribute>();
+ while ((samlAttr = (Element) attrIter.nextNode()) != null) {
+ String attrName = XPathUtils.getAttributeValue(samlAttr, "@AttributeName", "");
+ String attrNamespace = XPathUtils.getAttributeValue(samlAttr, "@AttributeNamespace", "");
+ Object attrValue;
+ Element attrValueElem = (Element)XPathUtils.selectSingleNode(samlAttr, SAML_ATTRIBUTE_VALUE_XPATH);
+ attrValue = DOMUtils.getElementFromNodeList(attrValueElem.getChildNodes());
+ if (attrValue == null) {
+ if (null!=attrValueElem.getFirstChild()) {
+ attrValue = attrValueElem.getFirstChild().getNodeValue();
+ } else {
+ attrValue = "";
+ }
+ }
+ samlAttributes.add(new SAMLAttribute(attrName, attrNamespace, attrValue));
+ }
+ SAMLAttribute[] result = new SAMLAttribute[samlAttributes.size()];
+ samlAttributes.toArray(result);
+ cResp.setSamlAttributes(result);
+
+ NodeList list = sigResponse_.getElementsByTagNameNS(Constants.DSIG_NS_URI, "Signature");
+ Element dsigSignatureNode = (Element) list.item(0);
+ cResp.setDsigSignature(dsigSignatureNode);
+
+ }
+ catch (Throwable t) {
+ throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+ }
+ return cResp;
+ }
+
+// public CreateXMLSignatureResponse parseResponse() throws ParseException {
+// CreateXMLSignatureResponse cResp;
+// try {
+// cResp = new CreateXMLSignatureResponse();
+// Element samlAssertion = (Element)sigResponse.getElementsByTagNameNS(Constants.SAML_NS_URI, "Assertion").item(0);
+// cResp.setSamlAssertion(samlAssertion);
+// Element samlAttributeStatement = (Element)samlAssertion.getElementsByTagNameNS(Constants.SAML_NS_URI, "AttributeStatement").item(0);
+// Element samlSubject = (Element)samlAttributeStatement.getElementsByTagNameNS(Constants.SAML_NS_URI, "Subject").item(0);
+// Element samlNameIdentifier = (Element)samlSubject.getElementsByTagNameNS(Constants.SAML_NS_URI, "NameIdentifier").item(0);
+// cResp.setSamlNameIdentifier(samlNameIdentifier.getFirstChild().getNodeValue());
+// NodeList nl = samlAttributeStatement.getElementsByTagNameNS(Constants.SAML_NS_URI, "Attribute");
+// List samlAttributes = new ArrayList();
+// for (int i=0; i<nl.getLength(); i++) {
+// Element samlAttribute = (Element)nl.item(i);
+// String attrName = samlAttribute.getAttribute("AttributeName");
+// String attrNamespace = samlAttribute.getAttribute("AttributeNamespace");
+// String attrValue = ((Element)samlAttribute.getElementsByTagNameNS(Constants.SAML_NS_URI, "AttributeValue").item(0)).getFirstChild().getNodeValue();
+// samlAttributes.add(new SAMLAttribute(attrName, attrNamespace, attrValue));
+// }
+// SAMLAttribute[] result = new SAMLAttribute[samlAttributes.size()];
+// samlAttributes.toArray(result);
+// cResp.setSamlAttributes(result);
+// }
+// catch (Throwable t) {
+// throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+// }
+// return cResp;
+// }
+
+
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/ErrorResponseParser.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/ErrorResponseParser.java
new file mode 100644
index 000000000..a09f0a2a8
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/ErrorResponseParser.java
@@ -0,0 +1,115 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.parser;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+
+/**
+ * Parses an <code>&lt;ErrorResponse&gt;</code>.
+ *
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+
+public class ErrorResponseParser {
+
+ /**
+ * The error code included in this error response.
+ * <code>1000</code> is used as default value, if some problems occur on
+ * evaluating the error response.
+ */
+ private String errorCode_ = "1000";
+
+ /**
+ * The error info included in this error response.
+ * <code>&lt;Unklassifizierter Fehler.&gt;</code> is used as default value,
+ * if some problems occur on evaluating the error response.
+ */
+ private String errorInfo_ = "Unklassifizierter Fehler.";
+
+
+ /**
+ * This Constructor extracts the error code and error info included in this
+ * error response.
+ *
+ * @param errorElement The error element. This is the root element of
+ * the error response.
+ */
+ public ErrorResponseParser(Element errorElement) throws ParseException {
+ if (errorElement != null) {
+ String namespace = errorElement.getNamespaceURI();
+ NodeList nl = errorElement.getElementsByTagNameNS(namespace, "ErrorCode");
+ if (nl.getLength() == 1) {
+ errorCode_ = ((Element)nl.item(0)).getFirstChild().getNodeValue();
+ }
+ nl = errorElement.getElementsByTagNameNS(namespace, "Info");
+ if (nl.getLength() == 1) {
+ errorInfo_ = ((Element)nl.item(0)).getFirstChild().getNodeValue();
+ }
+ }
+ }
+
+ /**
+ * Returns the error code included in this error response.
+ */
+ public String getErrorCode() {
+ return errorCode_ ;
+ }
+
+ /**
+ * Returns the information included in this error response.
+ * @return The error infomation String
+ */
+ public String getErrorInfo() {
+ return errorInfo_ ;
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/ExtendedInfoboxReadResponseParser.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/ExtendedInfoboxReadResponseParser.java
new file mode 100644
index 000000000..390467bf8
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/ExtendedInfoboxReadResponseParser.java
@@ -0,0 +1,203 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.parser;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Vector;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import at.gv.egovernment.moa.id.auth.data.InfoboxToken;
+import at.gv.egovernment.moa.id.auth.data.InfoboxTokenImpl;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+
+/**
+ * Parses and unmarshales <code>InfoboxReadResponse<code>.
+ * This parser is especially used for parsing additional responses (additional to that
+ * one containing the <code>IdentityLink</code> retuned from the BKU as an answer of
+ * a <code>&lt;PushInfobox&gt;</code> request.
+ */
+public class ExtendedInfoboxReadResponseParser {
+
+ /**
+ * Hide default constructor.
+ */
+ private ExtendedInfoboxReadResponseParser() {
+ }
+
+ /**
+ * Parses and unmarshales the given <code>infoboxReadResponse</code> to a list of
+ * {@link at.gv.egovernment.moa.id.auth.data.InfoboxToken InfoboxToken} objects.
+ * The method parses the given <code>infoboxReadResponse</code>
+ *
+ * @param infoboxReadResponse The infobox read response to be unmarshaled.
+ * @param infoboxName The name of the infobox the reponse corresponds to.
+ *
+ * @return A list of {@link at.gv.egovernment.moa.id.auth.data.InfoboxToken InfoboxToken}
+ * objects. Maybe empty.
+ *
+ * @throws ParseException If an error occurs on parsing and unmarshaling the response.
+ */
+ public static List parseInfoboxReadResponse(String infoboxReadResponse, String infoboxName)
+ throws ParseException
+ {
+ Element infoboxReadResponseElem = null;
+ try {
+ Document doc =
+ DOMUtils.parseDocument(infoboxReadResponse, true, Constants.ALL_SCHEMA_LOCATIONS, null);
+ infoboxReadResponseElem = doc.getDocumentElement();
+ } catch (Exception e) {
+ Logger.error("InfoboxReadResponse for \"" + infoboxName +
+ "\"-infobox could not be parsed successfully: " + e.getMessage());
+ throw new ParseException("parser.01", new Object[] {infoboxName + "-InfoboxReadResponse"});
+ }
+
+ Vector infoboxTokenList = new Vector();
+
+ if (infoboxReadResponseElem != null) {
+ // avoid using namespace URI or prefix, because it might change within the response
+ // (e.g.: sl11-namespace, some child sl10-namespace
+ List infoboxReadResponseChildren = DOMUtils.getChildElements(infoboxReadResponseElem);
+ String key = null;
+ boolean primary = true;
+ Element infoboxReadResponseChild = (Element)infoboxReadResponseChildren.get(0);
+ String infoboxReadResponseChildName = infoboxReadResponseChild.getLocalName();
+ if (infoboxReadResponseChildName.equals("AssocArrayData")) {
+ // get the <Pair> child elements from the <AssocArrayData> element
+ List assocArrayPairs = DOMUtils.getChildElements(infoboxReadResponseChild);
+ Iterator assocArrayPairIt = assocArrayPairs.iterator();
+ int pairCount = 0;
+ // step through the <Pair> elemnts
+ while (assocArrayPairIt.hasNext()) {
+ Element assocArrayPair = (Element)assocArrayPairIt.next();
+ // check if the element actually a "Pair" element and not only a "key"
+ if (assocArrayPair.getLocalName().equals("Key")) {
+ // do not accept only a Key
+ throw new ParseException("parser.07", new Object[] {infoboxName});
+ }
+ key = assocArrayPair.getAttribute("Key");
+ if (pairCount > 0) {
+ primary = false;
+ }
+ pairCount++;
+ infoboxTokenList.addAll(getTokenFromXMLOrBase64Content(assocArrayPair, infoboxName, key, primary));
+ }
+
+ } else if (infoboxReadResponseChildName.equals("BinaryFileData")) {
+ infoboxTokenList.addAll(getTokenFromXMLOrBase64Content(infoboxReadResponseChild, infoboxName, null, true));
+ }
+ }
+ return infoboxTokenList;
+ }
+
+ /**
+ * Unmarshales the <code>&lt;XMLContent&gt;</code> or
+ * <code>&lt;Base64Content&gt;</code> child of the given element to a list of
+ * infobox token.
+ *
+ * @param contentParent The elment including the <code>&lt;XMLContent&gt;</code> or
+ * <code>&lt;Base64Content&gt;</code> child to unmarshal the
+ * infobox token from.
+ * @param infoboxName The name of the infobox.
+ * @param key The key of an <code>AssocArrayData-Pair</code>.
+ * Maybe <code>null</code>.
+ * @param primary Specifies whether this token is the first (e.g. in an
+ * AssocArrayData) token.
+ *
+ * @return A infobox token list.
+ *
+ * @throws ParseException If the <code>contentParent</code> has no <code>&lt;XMLContent&gt;</code>
+ * or <code>&lt;Base64Content&gt;</code> child or the
+ * <code>&lt;XMLContent&gt;</code> is empty.
+ */
+ public static List getTokenFromXMLOrBase64Content(
+ Element contentParent,
+ String infoboxName,
+ String key,
+ boolean primary)
+ throws ParseException
+ {
+ Vector tokenList = new Vector();
+ // get the <XMLContent> or <Base64Content>
+ List content = DOMUtils.getChildElements(contentParent);
+ if (content.size() == 1) {
+ Element contentElem = (Element)content.get(0);
+ if (contentElem.getLocalName().equals("XMLContent")) {
+ List xmlContentChildren = DOMUtils.getChildElements(contentElem);
+ if (xmlContentChildren.size() == 0) {
+ throw new ParseException("parser.06", new Object[] {infoboxName, "Inhalt", "XMLContent"});
+ }
+ int xmlCount = 0;
+ Iterator contentIt = xmlContentChildren.iterator();
+ while (contentIt.hasNext()) {
+ Element xmlToken = (Element)contentIt.next();
+ if (xmlCount > 0) {
+ primary = false;
+ }
+ InfoboxToken infoboxToken = new InfoboxTokenImpl(key, primary, xmlToken);
+ tokenList.add(infoboxToken);
+ xmlCount++;
+ }
+ } else {
+ String base64Token = contentElem.getFirstChild().getNodeValue();
+ InfoboxToken infoboxToken = new InfoboxTokenImpl(key, primary, base64Token);
+ tokenList.add(infoboxToken);
+ }
+ } else {
+ throw new ParseException("parser.06",
+ new Object[] {infoboxName, "XMLContent oder Base64Content", contentParent.getLocalName()});
+ }
+ return tokenList;
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java
new file mode 100644
index 000000000..28ce69e95
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java
@@ -0,0 +1,274 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.parser;
+
+import iaik.x509.X509Certificate;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.security.cert.CertificateException;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.TransformerException;
+
+import org.apache.axis.encoding.Base64;
+import org.apache.xpath.XPathAPI;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+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.ParseException;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.XPathUtils;
+
+/**
+ * Parses an <code>&lt;InfoboxReadResponse&gt;</code>.
+ *
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+
+public class InfoboxReadResponseParser {
+
+ /** This is the root element of the XML-Document provided by the Security Layer Card*/
+ private Element infoBoxElem_;
+
+ /**
+ * Parses and validates the document given as string and extracts the
+ * root element.
+ *
+ * @param xmlResponse <code>&lt;InfoboxReadResponse&gt;</code> as String
+ * @throws ParseException If an element cannot be parsed
+ * @throws AuthenticationException If any authentication error occurs
+ * @throws BKUException
+ */
+ public InfoboxReadResponseParser(String xmlResponse) throws ParseException, AuthenticationException, BKUException {
+
+ try {
+ InputStream s = new ByteArrayInputStream(xmlResponse.getBytes("UTF-8"));
+ init(s);
+ }
+
+ catch (BKUException e) {
+ throw e;
+
+ } catch (Throwable t) {
+ throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+ }
+ }
+
+ /**
+ * Parses and validates the document given as stream and extracts the
+ * root element.
+ *
+ * @param is <code>&lt;InfoboxReadResponse&gt;</code> as InputStream
+ * @throws ParseException If an element cannot be parsed
+ * @throws AuthenticationException If any authentication error occurs
+ * @throws BKUException
+ */
+ public InfoboxReadResponseParser(InputStream is) throws ParseException, AuthenticationException, BKUException {
+ init(is);
+ }
+
+ /**
+ * Initializes the parser.
+ * Parses and validates the document given as stream and extracts the
+ * root element.
+ *
+ * @param is The InfoBoxReadResponse as stream.
+ * @throws AuthenticationException If an authentication error occurs.
+ * @throws ParseException If an error occurs on parsing the the document.
+ * @throws BKUException
+ */
+ private void init(InputStream is) throws AuthenticationException, ParseException, BKUException {
+ try {
+
+ Element responseElem = DOMUtils.parseXmlValidating(is);
+
+ if ("InfoboxReadResponse".equals(responseElem.getLocalName())) {
+ infoBoxElem_ = responseElem;
+ } else {
+ ErrorResponseParser erp = new ErrorResponseParser(responseElem);
+ throw new BKUException("auth.08",
+ new Object[] { erp.getErrorCode(), erp.getErrorInfo()},
+ erp.getErrorCode(),
+ erp.getErrorInfo());
+ }
+
+ } catch (BKUException e) {
+ throw e;
+
+ } catch (Throwable t) {
+ throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+ }
+ }
+
+
+
+ /**
+ * Parses the embedded <code>&lt;saml:Assertion&gt;</code> element from <code>&lt;InfoboxReadResponse&gt;</code>
+ * @return <code>&lt;saml:Assertion&gt;</code> as String
+ * @throws ParseException on any parsing error
+ */
+// public String parseSAMLAssertion() throws ParseException {
+// try {
+//
+// String slPrefix = XPathUtils.getSlPrefix(infoBoxElem_);
+// StringBuffer sb = new StringBuffer("/");
+// sb.append(slPrefix);
+// sb.append(":InfoboxReadResponse/");
+// sb.append(slPrefix);
+// sb.append(":BinaryFileData/");
+// sb.append(slPrefix);
+// sb.append(":XMLContent/");
+// sb.append(Constants.SAML_PREFIX);
+// sb.append(":Assertion");
+// String samlAssertionXPath = sb.toString();
+// Element samlAssertion = (Element) XPathUtils.selectSingleNode(infoBoxElem_, samlAssertionXPath);
+// return DOMUtils.serializeNode(samlAssertion);
+//
+// }
+// catch (Throwable t) {
+// throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+// }
+// }
+
+ /**
+ * Parses the embedded <code>&lt;saml:Assertion&gt;</code> element from <code>&lt;InfoboxReadResponse&gt;</code>
+ * @return <code>&lt;saml:Assertion&gt;</code> as String
+ * @throws ParseException on any parsing error
+ */
+ public Element parseSAMLAssertion() throws ParseException {
+ try {
+
+ String slPrefix = XPathUtils.getSlPrefix(infoBoxElem_);
+ StringBuffer sb = new StringBuffer("/");
+ sb.append(slPrefix);
+ sb.append(":InfoboxReadResponse/");
+ sb.append(slPrefix);
+ sb.append(":BinaryFileData/");
+ sb.append(slPrefix);
+ sb.append(":XMLContent/");
+ sb.append(Constants.SAML_PREFIX);
+ sb.append(":Assertion");
+ String samlAssertionXPath = sb.toString();
+ Element samlAssertion = (Element) XPathUtils.selectSingleNode(infoBoxElem_, samlAssertionXPath);
+ return samlAssertion;
+
+ }
+ catch (Throwable t) {
+ throw new ParseException("parser.01", new Object[] { t.toString()}, t);
+ }
+ }
+
+ /**
+ * Parses the identity link from the <code>&lt;saml:Assertion&gt;</code>
+ * @return Identity link
+ * @throws ParseException on any parsing error
+ */
+
+// public IdentityLink parseIdentityLink() throws ParseException {
+// String samlAssertionString = parseSAMLAssertion();
+// IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(samlAssertionString);
+// return ilParser.parseIdentityLink();
+// }
+
+ /**
+ * Parses the identity link from the <code>&lt;saml:Assertion&gt;</code>
+ * @return Identity link
+ * @throws ParseException on any parsing error
+ */
+ public IdentityLink parseIdentityLink() throws ParseException {
+ Element samlAssertion = parseSAMLAssertion();
+ IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(samlAssertion);
+ return ilParser.parseIdentityLink();
+ }
+
+ /**
+ * Returns the certificate given in the InfoboxReadResponse
+ * @return
+ * @throws ParseException
+ */
+ public X509Certificate parseCertificate() throws ParseException {
+ try {
+ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
+ Document doc = builder.newDocument();
+
+ Element nameSpaceNode = doc.createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns:" + Constants.PD_PREFIX, Constants.PD_NS_URI);
+ nameSpaceNode.setAttribute("xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI);
+ nameSpaceNode.setAttribute("xmlns:" + Constants.SL12_PREFIX, Constants.SL12_NS_URI);
+
+ Element base64ContentElement = (Element)XPathAPI.selectSingleNode(infoBoxElem_.getParentNode(), "//sl:Base64Content[1]", nameSpaceNode);
+
+ if (base64ContentElement == null) {
+ throw new ParseException("parser.01", new Object[] { "Could not find Base64Content for X509Certificate."});
+ }
+
+ String base64Content = DOMUtils.getText(base64ContentElement);
+
+ // Decode Base64 value to X509Certificate
+ byte[] content = Base64.decode(base64Content);
+ return new X509Certificate(content);
+
+ } catch (ParserConfigurationException e) {
+ throw new ParseException("parser.01", new Object[] { "Could not parse X509Certificate from InfoboxReadRequest."}, e);
+ } catch (TransformerException e) {
+ throw new ParseException("parser.01", new Object[] { "Could not parse X509Certificate from InfoboxReadRequest."}, e);
+ } catch (CertificateException e) {
+ throw new ParseException("parser.01", new Object[] { "Could not parse X509Certificate from InfoboxReadRequest."}, e);
+ }
+
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java
new file mode 100644
index 000000000..7bce406e0
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java
@@ -0,0 +1,211 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.parser;
+
+import iaik.utils.Base64InputStream;
+import iaik.x509.X509Certificate;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+
+import org.w3c.dom.Element;
+
+import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.XPathUtils;
+
+/**
+ * Parses a <code>&lt;VerifyXMLSignatureResponse&gt;</code> returned by
+ * MOA-SPSS.
+ * This class implements the Singleton pattern
+ *
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+
+
+public class VerifyXMLSignatureResponseParser {
+ //
+ // XPath namespace prefix shortcuts
+ //
+ /** Xpath prefix for reaching MOA Namespaces */
+ private static final String MOA = Constants.MOA_PREFIX + ":";
+ /** Xpath prefix for reaching DSIG Namespaces */
+ private static final String DSIG = Constants.DSIG_PREFIX + ":";
+ /** Xpath expression to the root element */
+ private static final String ROOT = "/" + MOA + "VerifyXMLSignatureResponse/";
+
+ /** Xpath expression to the X509SubjectName element */
+ private static final String DSIG_SUBJECT_NAME_XPATH =
+ ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" +
+ DSIG + "X509SubjectName";
+ /** Xpath expression to the X509Certificate element */
+ private static final String DSIG_X509_CERTIFICATE_XPATH =
+ ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" +
+ DSIG + "X509Certificate";
+ /** Xpath expression to the PublicAuthority element */
+ private static final String PUBLIC_AUTHORITY_XPATH =
+ ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" +
+ MOA + "PublicAuthority";
+ /** Xpath expression to the PublicAuthorityCode element */
+ private static final String PUBLIC_AUTHORITY_CODE_XPATH =
+ PUBLIC_AUTHORITY_XPATH + "/" + MOA + "Code";
+ /** Xpath expression to the QualifiedCertificate element */
+ private static final String QUALIFIED_CERTIFICATE_XPATH =
+ ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" +
+ MOA + "QualifiedCertificate";
+
+ /** Xpath expression to the SignatureCheckCode element */
+ private static final String SIGNATURE_CHECK_CODE_XPATH =
+ ROOT + MOA + "SignatureCheck/" + MOA + "Code";
+ /** Xpath expression to the XMLDSIGManifestCheckCode element */
+ private static final String XMLDSIG_MANIFEST_CHECK_CODE_XPATH =
+ ROOT + MOA + "XMLDSIGManifestCheck/" + MOA + "Code";
+ /** Xpath expression to the SignatureManifestCheckCode element */
+ private static final String SIGNATURE_MANIFEST_CHECK_CODE_XPATH =
+ ROOT + MOA + "SignatureManifestCheck/" + MOA + "Code";
+ /** Xpath expression to the CertificateCheckCode element */
+ private static final String CERTIFICATE_CHECK_CODE_XPATH =
+ ROOT + MOA + "CertificateCheck/" + MOA + "Code";
+
+
+ /** This is the root element of the XML-Document provided by the Security Layer Card*/
+ private Element verifyXMLSignatureResponse;
+
+ /**
+ * Constructor for VerifyXMLSignatureResponseParser.
+ * A DOM-representation of the incoming String will be created
+ * @param xmlResponse <code>&lt;InfoboxReadResponse&gt;</code> as String
+ * @throws ParseException on any parsing error
+ */
+ public VerifyXMLSignatureResponseParser(String xmlResponse) throws ParseException{
+ try {
+ InputStream s = new ByteArrayInputStream(xmlResponse.getBytes("UTF-8"));
+
+ verifyXMLSignatureResponse = DOMUtils.parseXmlValidating(s);
+ }
+ catch (Throwable t) {
+ throw new ParseException("parser.01", new Object[] { t.toString() }, t);
+ }
+ }
+
+ /**
+ * Constructor for VerifyXMLSignatureResponseParser.
+ * A DOM-representation of the incoming Inputstream will be created
+ * @param xmlResponse <code>&lt;InfoboxReadResponse&gt;</code> as InputStream
+ * @throws Exception on any parsing error
+ */
+ public VerifyXMLSignatureResponseParser(InputStream xmlResponse) throws Exception
+ {
+ try {
+ verifyXMLSignatureResponse = DOMUtils.parseXmlValidating(xmlResponse);
+ }
+ catch (Throwable t) {
+ throw new ParseException("parser.01", null, t);
+ }
+ }
+
+ /**
+ * Constructor for VerifyXMLSignatureResponseParser.
+ * The incoming Element will be used for further operations
+ * @param xmlResponse <code>&lt;InfoboxReadResponse&gt;</code> as Element
+ */
+ public VerifyXMLSignatureResponseParser(Element xmlResponse)
+ {
+ verifyXMLSignatureResponse =xmlResponse;
+
+ }
+
+ /**
+ * Parse identity link from <code>&lt;InfoboxReadResponse&gt;</code>
+ * @return Identity link
+ * @throws ParseException on any parsing error
+ */
+
+ public VerifyXMLSignatureResponse parseData() throws ParseException {
+
+ VerifyXMLSignatureResponse respData=new VerifyXMLSignatureResponse();
+
+ try {
+
+ String s = DOMUtils.serializeNode(verifyXMLSignatureResponse);
+ respData.setXmlDsigSubjectName(XPathUtils.getElementValue(verifyXMLSignatureResponse,DSIG_SUBJECT_NAME_XPATH,""));
+ Element e = (Element)XPathUtils.selectSingleNode(verifyXMLSignatureResponse,QUALIFIED_CERTIFICATE_XPATH);
+ respData.setQualifiedCertificate(e!=null);
+
+ Base64InputStream in = new Base64InputStream(new ByteArrayInputStream(XPathUtils.getElementValue(
+ verifyXMLSignatureResponse,DSIG_X509_CERTIFICATE_XPATH,"").getBytes("UTF-8")),true);
+
+ respData.setX509certificate(new X509Certificate(in));
+ Element publicAuthority = (Element)XPathUtils.selectSingleNode(verifyXMLSignatureResponse,PUBLIC_AUTHORITY_XPATH);
+ respData.setPublicAuthority(publicAuthority != null);
+ respData.setPublicAuthorityCode(XPathUtils.getElementValue(verifyXMLSignatureResponse,PUBLIC_AUTHORITY_CODE_XPATH,""));
+ respData.setSignatureCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNATURE_CHECK_CODE_XPATH,"")).intValue());
+
+ String xmlDsigCheckCode = XPathUtils.getElementValue(verifyXMLSignatureResponse,XMLDSIG_MANIFEST_CHECK_CODE_XPATH,null);
+ if (xmlDsigCheckCode!=null) {
+ respData.setXmlDSIGManigest(true);
+ respData.setXmlDSIGManifestCheckCode(new Integer(xmlDsigCheckCode).intValue());
+ } else {
+ respData.setXmlDSIGManigest(false);
+ }
+ String signatureManifestCheckCode = XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNATURE_MANIFEST_CHECK_CODE_XPATH,null);
+ if (signatureManifestCheckCode != null) {
+ respData.setSignatureManifestCheckCode(new Integer(signatureManifestCheckCode).intValue());
+ }
+ respData.setCertificateCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,CERTIFICATE_CHECK_CODE_XPATH,"")).intValue());
+ }
+ catch (Throwable t) {
+ throw new ParseException("parser.01", null, t);
+ }
+ return respData;
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java
new file mode 100644
index 000000000..d70cd6f50
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java
@@ -0,0 +1,671 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.validator;
+
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.xml.bind.DatatypeConverter;
+
+import org.jaxen.SimpleNamespaceContext;
+import org.w3c.dom.Element;
+
+import at.gv.egovernment.moa.id.auth.builder.AuthenticationBlockAssertionBuilder;
+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.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.data.SAMLAttribute;
+import at.gv.egovernment.moa.id.auth.exception.ValidateException;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.MiscUtil;
+import at.gv.egovernment.moa.util.StringUtils;
+import at.gv.egovernment.moa.util.XPathUtils;
+
+/**
+ *
+ * This class is used to validate an {@link CreateXMLSignatureResponse}
+ * returned by the security layer.
+ * This class implements the Singleton pattern.
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+public class CreateXMLSignatureResponseValidator {
+
+
+ /** Xpath expression to the dsig:Signature element */
+ private static final String SIGNATURE_XPATH = Constants.DSIG_PREFIX + ":Signature";
+
+ private static final String XADES_1_1_1_SIGNINGTIME_PATH = "//" + Constants.XADES_1_1_1_NS_PREFIX + ":SigningTime";
+ private static final String XADES_1_3_2_SIGNINGTIME_PATH = "//" + Constants.XADES_1_3_2_NS_PREFIX + ":SigningTime";
+
+
+ private static final long MAX_DIFFERENCE_IN_MILLISECONDS = 600000; // 10min
+
+ /** Singleton instance. <code>null</code>, if none has been created. */
+ private static CreateXMLSignatureResponseValidator instance;
+
+ private static SimpleNamespaceContext NS_CONTEXT;
+ static {
+ NS_CONTEXT = new SimpleNamespaceContext();
+ NS_CONTEXT.addNamespace(Constants.XADES_1_1_1_NS_PREFIX, Constants.XADES_1_1_1_NS_URI);
+ NS_CONTEXT.addNamespace(Constants.XADES_1_2_2_NS_PREFIX, Constants.XADES_1_2_2_NS_URI);
+ NS_CONTEXT.addNamespace(Constants.XADES_1_3_2_NS_PREFIX, Constants.XADES_1_3_2_NS_URI);
+ NS_CONTEXT.addNamespace(Constants.XADES_1_4_1_NS_PREFIX, Constants.XADES_1_4_1_NS_URI);
+ }
+
+
+ /**
+ * Constructor for a singleton CreateXMLSignatureResponseValidator.
+ * @return an instance of CreateXMLSignatureResponseValidator
+ * @throws ValidateException if no instance can be created
+ */
+ public static synchronized CreateXMLSignatureResponseValidator getInstance()
+ throws ValidateException {
+ if (instance == null) {
+ instance = new CreateXMLSignatureResponseValidator();
+ }
+ return instance;
+ }
+
+
+ /**
+ * The Method validate is used for validating an explicit {@link CreateXMLSignatureResponse}
+ * @param createXMLSignatureResponse
+ * @param session
+ * @throws ValidateException
+ */
+ public void validate(CreateXMLSignatureResponse createXMLSignatureResponse, AuthenticationSession session)
+ throws ValidateException {
+
+ // A3.056: more then one /saml:Assertion/saml:AttributeStatement/saml:Subject/saml:NameIdentifier
+
+ String gbTarget = session.getTarget();
+ String oaURL = session.getPublicOAURLPrefix();
+ boolean businessService = session.getBusinessService();
+
+ IdentityLink identityLink = session.getIdentityLink();
+
+ Element samlAssertion = createXMLSignatureResponse.getSamlAssertion();
+ String issuer = samlAssertion.getAttribute("Issuer");
+ if (issuer == null) {
+ // should not happen, because parser would dedect this
+ throw new ValidateException("validator.32", null);
+ }
+ // replace ' in name with &#39;
+ issuer = issuer.replaceAll("'", "&#39;");
+
+ String issueInstant = samlAssertion.getAttribute("IssueInstant");
+ if (!issueInstant.equals(session.getIssueInstant())) {
+ throw new ValidateException("validator.39", new Object[] {issueInstant, session.getIssueInstant()});
+ }
+
+ String name = identityLink.getName();
+
+ if (!issuer.equals(name)) {
+ throw new ValidateException("validator.33", new Object[] {issuer, name});
+ }
+
+ SAMLAttribute[] samlAttributes = createXMLSignatureResponse.getSamlAttributes();
+
+ boolean foundOA = false;
+ boolean foundGB = false;
+ boolean foundWBPK = false;
+ int offset = 0;
+
+ // check number of SAML aatributes
+ List<ExtendedSAMLAttribute> extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH();
+ int extendedSAMLAttributesNum = 0;
+ if (extendedSAMLAttributes != null) {
+ extendedSAMLAttributesNum = extendedSAMLAttributes.size();
+ }
+ int expectedSAMLAttributeNumber =
+ AuthenticationBlockAssertionBuilder.NUM_OF_SAML_ATTRIBUTES + extendedSAMLAttributesNum;
+ if (!session.getSAMLAttributeGebeORwbpk()) expectedSAMLAttributeNumber--;
+ int actualSAMLAttributeNumber = samlAttributes.length;
+ if (actualSAMLAttributeNumber != expectedSAMLAttributeNumber) {
+ Logger.error("Wrong number of SAML attributes in CreateXMLSignatureResponse: expected " +
+ expectedSAMLAttributeNumber + ", but was " + actualSAMLAttributeNumber);
+ throw new ValidateException(
+ "validator.36",
+ new Object[] {String.valueOf(actualSAMLAttributeNumber), String.valueOf(expectedSAMLAttributeNumber)});
+ }
+
+ SAMLAttribute samlAttribute;
+ if (session.getSAMLAttributeGebeORwbpk()) {
+ // check the first attribute ("Geschaeftsbereich" or "wbPK")
+ samlAttribute = samlAttributes[0];
+ if (businessService) {
+ if (!samlAttribute.getName().equals("wbPK")) {
+ if (samlAttribute.getName().equals("Geschaeftsbereich")) {
+ throw new ValidateException("validator.26", null);
+ } else {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "wbPK", String.valueOf(1)});
+ }
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ foundWBPK = true;
+ try {
+ Element attrValue = (Element)samlAttribute.getValue();
+ String value = ((Element)attrValue.getElementsByTagNameNS(Constants.PD_NS_URI, "Value").item(0)).getFirstChild().getNodeValue();
+ String type = ((Element)attrValue.getElementsByTagNameNS(Constants.PD_NS_URI, "Type").item(0)).getFirstChild().getNodeValue();
+ if (!value.equals(identityLink.getIdentificationValue())) {
+ throw new ValidateException("validator.28", null);
+ }
+ if (!type.equals(identityLink.getIdentificationType())) {
+ throw new ValidateException("validator.28", null);
+ }
+ } catch (Exception ex) {
+ throw new ValidateException("validator.29", null);
+ }
+ } else {
+ throw new ValidateException("validator.30", null);
+ }
+ } else {
+ if (!samlAttribute.getName().equals("Geschaeftsbereich")) {
+ if (samlAttribute.getName().equals("wbPK")) {
+ throw new ValidateException("validator.26", null);
+ } else {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "Geschaeftsbereich", String.valueOf(1)});
+ }
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ foundGB = true;
+ String targetFriendlyName = session.getTargetFriendlyName();
+ String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(gbTarget);
+ if (StringUtils.isEmpty(sectorName)) {
+ if (targetFriendlyName != null)
+ sectorName = targetFriendlyName;
+ }
+ gbTarget = gbTarget + " (" + sectorName + ")";
+ //gbTarget = gbTarget + " (" + TargetToSectorNameMapper.getSectorNameViaTarget(gbTarget) + ")";
+
+ if (!gbTarget.equals((String)samlAttribute.getValue())) {
+ throw new ValidateException("validator.13", null);
+ }
+ } else {
+ throw new ValidateException("validator.12", null);
+ }
+ }
+ } else {
+ offset--;
+ }
+
+ // check the second attribute (must be "OA")
+ samlAttribute = samlAttributes[1 + offset];
+ if (!samlAttribute.getName().equals("OA")) {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "OA", String.valueOf(2)});
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ foundOA = true;
+ if (!oaURL.equals((String)samlAttribute.getValue())) { // CHECKS für die AttributeVALUES fehlen noch
+ throw new ValidateException("validator.16", new Object[] {":gefunden wurde '" + oaURL + "', erwartet wurde '" + samlAttribute.getValue()});
+ }
+ } else {
+ throw new ValidateException("validator.15", null);
+ }
+
+ // check the third attribute (must be "Geburtsdatum")
+ samlAttribute = samlAttributes[2 + offset];
+ if (!samlAttribute.getName().equals("Geburtsdatum")) {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "Geburtsdatum", String.valueOf(3)});
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ String samlDateOfBirth = (String)samlAttribute.getValue();
+ String dateOfBirth = identityLink.getDateOfBirth();
+ if (!samlDateOfBirth.equals(dateOfBirth)) {
+ throw new ValidateException("validator.34", new Object[] {samlDateOfBirth, dateOfBirth});
+ }
+ } else {
+ throw new ValidateException("validator.35", null);
+ }
+
+ // check four attribute could be a special text
+ samlAttribute = samlAttributes[3 + offset];
+ if (!samlAttribute.getName().equals("SpecialText")) {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "SpecialText", String.valueOf(4)});
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ String samlSpecialText = (String)samlAttribute.getValue();
+ samlSpecialText = samlSpecialText.replaceAll("'", "&#39;");
+
+ String text = "";
+ try {
+ OAAuthParameter oaparam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix());
+ if (MiscUtil.isNotEmpty(oaparam.getAditionalAuthBlockText())) {
+ Logger.info("Use addional AuthBlock Text from OA=" + oaparam.getPublicURLPrefix());
+ text = oaparam.getAditionalAuthBlockText();
+ }
+ } catch (ConfigurationException e) {
+ Logger.warn("Addional AuthBlock Text can not loaded from OA!", e);
+ }
+
+
+ String specialText = AuthenticationBlockAssertionBuilder.generateSpecialText(text, issuer, identityLink.getDateOfBirth(), issueInstant);
+ if (!samlSpecialText.equals(specialText)) {
+ throw new ValidateException("validator.67", new Object[] {samlSpecialText, specialText});
+ }
+ } else {
+ throw new ValidateException("validator.35", null);
+ }
+
+
+ //check unique AuthBlock tokken
+ samlAttribute = samlAttributes[4 + offset];
+ if (!samlAttribute.getName().equals("UniqueTokken")) {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "UniqueTokken", String.valueOf(5)});
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ String uniquetokken = (String)samlAttribute.getValue();
+
+ if (!uniquetokken.equals(session.getAuthBlockTokken())) {
+ throw new ValidateException("validator.70", new Object[] {uniquetokken, session.getAuthBlockTokken()});
+ }
+ } else {
+ throw new ValidateException("validator.35", null);
+ }
+
+
+ // now check the extended SAML attributes
+ int i = AuthenticationBlockAssertionBuilder.NUM_OF_SAML_ATTRIBUTES + offset;
+ if (extendedSAMLAttributes != null) {
+ Iterator<ExtendedSAMLAttribute> it = extendedSAMLAttributes.iterator();
+ while (it.hasNext()) {
+ ExtendedSAMLAttribute extendedSAMLAttribute = (ExtendedSAMLAttribute)it.next();
+ samlAttribute = samlAttributes[i];
+ String actualName = samlAttribute.getName();
+ String expectedName = extendedSAMLAttribute.getName();
+ if (!actualName.equals(expectedName)) {
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Name", String.valueOf((i+1)), actualName, actualName, expectedName });
+ }
+ String actualNamespace = samlAttribute.getNamespace();
+ String expectedNamespace = extendedSAMLAttribute.getNameSpace();
+ if (!actualNamespace.equals(expectedNamespace)) {
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Namespace", String.valueOf((i+1)), actualName, actualNamespace, expectedNamespace, });
+ }
+ Object expectedValue = extendedSAMLAttribute.getValue();
+ Object actualValue = samlAttribute.getValue();
+ try {
+ if (expectedValue instanceof String) {
+ // replace \r\n because text might be base64-encoded
+ String expValue = StringUtils.replaceAll((String)expectedValue,"\r","");
+ expValue = StringUtils.replaceAll(expValue,"\n","");
+ String actValue = StringUtils.replaceAll((String)actualValue,"\r","");
+ actValue = StringUtils.replaceAll(actValue,"\n","");
+ if (!expValue.equals(actValue)) {
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Wert", String.valueOf((i+1)), actualName, actualValue, expectedValue });
+ }
+ } else if (expectedValue instanceof Element) {
+ // only check the name of the element
+ String actualElementName = ((Element)actualValue).getNodeName();
+ String expectedElementName = ((Element)expectedValue).getNodeName();
+ if (!(expectedElementName.equals(actualElementName))){
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Wert", String.valueOf((i+1)), actualName, actualElementName, expectedElementName});
+ }
+ } else {
+ // should not happen
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Typ", String.valueOf((i+1)), expectedName, "java.lang.String oder org.wrc.dom.Element", expectedValue.getClass().getName()});
+ }
+ } catch (ClassCastException e) {
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Typ", String.valueOf((i+1)), expectedName, expectedValue.getClass().getName(), actualValue.getClass().getName()});
+ }
+ i++;
+ }
+ }
+
+
+ if (!foundOA) throw new ValidateException("validator.14", null);
+ if (businessService) {
+ if (session.getSAMLAttributeGebeORwbpk() && !foundWBPK) throw new ValidateException("validator.31", null);
+ } else {
+ if (!foundGB) throw new ValidateException("validator.11", null);
+ }
+
+ //Check if dsig:Signature exists
+// NodeList nl = createXMLSignatureResponse.getSamlAssertion().getElementsByTagNameNS(Constants.DSIG_NS_URI, "Signature");
+// if (nl.getLength() != 1) {
+// throw new ValidateException("validator.05", null);
+// }
+ Element dsigSignature = (Element) XPathUtils.selectSingleNode(samlAssertion, SIGNATURE_XPATH);
+ if (dsigSignature == null) {
+ throw new ValidateException("validator.05", new Object[] {"im AUTHBlock"}) ;
+ }
+ }
+
+ /**
+ * The Method validate is used for validating an explicit {@link CreateXMLSignatureResponse}
+ * @param createXMLSignatureResponse
+ * @param session
+ * @throws ValidateException
+ */
+ public void validateSSO(CreateXMLSignatureResponse createXMLSignatureResponse, AuthenticationSession session)
+ throws ValidateException {
+
+ // A3.056: more then one /saml:Assertion/saml:AttributeStatement/saml:Subject/saml:NameIdentifier
+
+ String oaURL;
+ try {
+ oaURL = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix().get(0);
+ } catch (ConfigurationException e1) {
+ oaURL = new String();
+ }
+
+ IdentityLink identityLink = session.getIdentityLink();
+
+ Element samlAssertion = createXMLSignatureResponse.getSamlAssertion();
+ String issuer = samlAssertion.getAttribute("Issuer");
+ if (issuer == null) {
+ // should not happen, because parser would dedect this
+ throw new ValidateException("validator.32", null);
+ }
+ // replace ' in name with &#39;
+ issuer = issuer.replaceAll("'", "&#39;");
+
+ String issueInstant = samlAssertion.getAttribute("IssueInstant");
+ if (!issueInstant.equals(session.getIssueInstant())) {
+ throw new ValidateException("validator.39", new Object[] {issueInstant, session.getIssueInstant()});
+ }
+
+ String name = identityLink.getName();
+
+ if (!issuer.equals(name)) {
+ throw new ValidateException("validator.33", new Object[] {issuer, name});
+ }
+
+ SAMLAttribute[] samlAttributes = createXMLSignatureResponse.getSamlAttributes();
+
+ boolean foundOA = false;
+// boolean foundGB = false;
+// boolean foundWBPK = false;
+ int offset = 0;
+
+ // check number of SAML aatributes
+ List<ExtendedSAMLAttribute> extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH();
+ int extendedSAMLAttributesNum = 0;
+ if (extendedSAMLAttributes != null) {
+ extendedSAMLAttributesNum = extendedSAMLAttributes.size();
+ }
+ int expectedSAMLAttributeNumber =
+ AuthenticationBlockAssertionBuilder.NUM_OF_SAML_ATTRIBUTES_SSO + extendedSAMLAttributesNum;
+ if (!session.getSAMLAttributeGebeORwbpk()) expectedSAMLAttributeNumber--;
+ int actualSAMLAttributeNumber = samlAttributes.length;
+ if (actualSAMLAttributeNumber != expectedSAMLAttributeNumber) {
+ Logger.error("Wrong number of SAML attributes in CreateXMLSignatureResponse: expected " +
+ expectedSAMLAttributeNumber + ", but was " + actualSAMLAttributeNumber);
+ throw new ValidateException(
+ "validator.36",
+ new Object[] {String.valueOf(actualSAMLAttributeNumber), String.valueOf(expectedSAMLAttributeNumber)});
+ }
+
+ SAMLAttribute samlAttribute;
+ if (!session.getSAMLAttributeGebeORwbpk()) {
+ offset--;
+ }
+
+ // check the first attribute (must be "OA")
+ samlAttribute = samlAttributes[0 + offset];
+ if (!samlAttribute.getName().equals("OA")) {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "OA", String.valueOf(2)});
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ foundOA = true;
+ if (!oaURL.equals((String)samlAttribute.getValue())) { // CHECKS für die AttributeVALUES fehlen noch
+ throw new ValidateException("validator.16", new Object[] {":gefunden wurde '" + oaURL + "', erwartet wurde '" + samlAttribute.getValue()});
+ }
+ } else {
+ throw new ValidateException("validator.15", null);
+ }
+
+ // check the third attribute (must be "Geburtsdatum")
+ samlAttribute = samlAttributes[1 + offset];
+ if (!samlAttribute.getName().equals("Geburtsdatum")) {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "Geburtsdatum", String.valueOf(3)});
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ String samlDateOfBirth = (String)samlAttribute.getValue();
+ String dateOfBirth = identityLink.getDateOfBirth();
+ if (!samlDateOfBirth.equals(dateOfBirth)) {
+ throw new ValidateException("validator.34", new Object[] {samlDateOfBirth, dateOfBirth});
+ }
+ } else {
+ throw new ValidateException("validator.35", null);
+ }
+
+ // check four attribute could be a special text
+ samlAttribute = samlAttributes[2 + offset];
+ if (!samlAttribute.getName().equals("SpecialText")) {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "SpecialText", String.valueOf(4)});
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ String samlSpecialText = (String)samlAttribute.getValue();
+ samlSpecialText = samlSpecialText.replaceAll("'", "&#39;");
+
+ String text = "";
+ try {
+ if (MiscUtil.isNotEmpty(AuthConfigurationProviderFactory.getInstance().getSSOSpecialText())) {
+ text = AuthConfigurationProviderFactory.getInstance().getSSOSpecialText();
+ Logger.info("Use addional AuthBlock Text from SSO=" +text);
+
+ }
+ else
+ text = new String();
+ } catch (ConfigurationException e) {
+ Logger.warn("Addional AuthBlock Text can not loaded from SSO!", e);
+ }
+
+
+ String specialText = AuthenticationBlockAssertionBuilder.generateSpecialText(text, issuer, identityLink.getDateOfBirth(), issueInstant);
+ if (!samlSpecialText.equals(specialText)) {
+ throw new ValidateException("validator.67", new Object[] {samlSpecialText, specialText});
+ }
+ } else {
+ throw new ValidateException("validator.35", null);
+ }
+
+ //check unique AuthBlock tokken
+ samlAttribute = samlAttributes[3 + offset];
+ if (!samlAttribute.getName().equals("UniqueTokken")) {
+ throw new ValidateException(
+ "validator.37",
+ new Object[] {samlAttribute.getName(), "UniqueTokken", String.valueOf(5)});
+ }
+ if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) {
+ String uniquetokken = (String)samlAttribute.getValue();
+
+ if (!uniquetokken.equals(session.getAuthBlockTokken())) {
+ throw new ValidateException("validator.70", new Object[] {uniquetokken, session.getAuthBlockTokken()});
+ }
+ } else {
+ throw new ValidateException("validator.35", null);
+ }
+
+
+ // now check the extended SAML attributes
+ int i = AuthenticationBlockAssertionBuilder.NUM_OF_SAML_ATTRIBUTES_SSO + offset;
+ if (extendedSAMLAttributes != null) {
+ Iterator<ExtendedSAMLAttribute> it = extendedSAMLAttributes.iterator();
+ while (it.hasNext()) {
+ ExtendedSAMLAttribute extendedSAMLAttribute = (ExtendedSAMLAttribute)it.next();
+ samlAttribute = samlAttributes[i];
+ String actualName = samlAttribute.getName();
+ String expectedName = extendedSAMLAttribute.getName();
+ if (!actualName.equals(expectedName)) {
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Name", String.valueOf((i+1)), actualName, actualName, expectedName });
+ }
+ String actualNamespace = samlAttribute.getNamespace();
+ String expectedNamespace = extendedSAMLAttribute.getNameSpace();
+ if (!actualNamespace.equals(expectedNamespace)) {
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Namespace", String.valueOf((i+1)), actualName, actualNamespace, expectedNamespace, });
+ }
+ Object expectedValue = extendedSAMLAttribute.getValue();
+ Object actualValue = samlAttribute.getValue();
+ try {
+ if (expectedValue instanceof String) {
+ // replace \r\n because text might be base64-encoded
+ String expValue = StringUtils.replaceAll((String)expectedValue,"\r","");
+ expValue = StringUtils.replaceAll(expValue,"\n","");
+ String actValue = StringUtils.replaceAll((String)actualValue,"\r","");
+ actValue = StringUtils.replaceAll(actValue,"\n","");
+ if (!expValue.equals(actValue)) {
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Wert", String.valueOf((i+1)), actualName, actualValue, expectedValue });
+ }
+ } else if (expectedValue instanceof Element) {
+ // only check the name of the element
+ String actualElementName = ((Element)actualValue).getNodeName();
+ String expectedElementName = ((Element)expectedValue).getNodeName();
+ if (!(expectedElementName.equals(actualElementName))){
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Wert", String.valueOf((i+1)), actualName, actualElementName, expectedElementName});
+ }
+ } else {
+ // should not happen
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Typ", String.valueOf((i+1)), expectedName, "java.lang.String oder org.wrc.dom.Element", expectedValue.getClass().getName()});
+ }
+ } catch (ClassCastException e) {
+ throw new ValidateException(
+ "validator.38",
+ new Object[] {"Typ", String.valueOf((i+1)), expectedName, expectedValue.getClass().getName(), actualValue.getClass().getName()});
+ }
+ i++;
+ }
+ }
+
+
+ if (!foundOA) throw new ValidateException("validator.14", null);
+
+ //Check if dsig:Signature exists
+// NodeList nl = createXMLSignatureResponse.getSamlAssertion().getElementsByTagNameNS(Constants.DSIG_NS_URI, "Signature");
+// if (nl.getLength() != 1) {
+// throw new ValidateException("validator.05", null);
+// }
+ Element dsigSignature = (Element) XPathUtils.selectSingleNode(samlAssertion, SIGNATURE_XPATH);
+ if (dsigSignature == null) {
+ throw new ValidateException("validator.05", new Object[] {"im AUTHBlock"}) ;
+ }
+ }
+
+ public void validateSigningDateTime( CreateXMLSignatureResponse csresp) throws ValidateException {
+
+ Element dsigSignatureElement = csresp.getDsigSignature();
+ if (dsigSignatureElement == null) {
+ throw new ValidateException("validator.05", new Object[] {"im AUTHBlock"}) ;
+ }
+ else {
+ Element signingTimeElem = (Element) XPathUtils.selectSingleNode(dsigSignatureElement, NS_CONTEXT, XADES_1_1_1_SIGNINGTIME_PATH);
+ if (signingTimeElem == null) {
+ signingTimeElem = (Element) XPathUtils.selectSingleNode(dsigSignatureElement, NS_CONTEXT, XADES_1_3_2_SIGNINGTIME_PATH);
+ if (signingTimeElem == null)
+ throw new ValidateException("validator.68", null) ;
+ }
+
+
+ String signingTimeStr = signingTimeElem.getTextContent();
+ if (signingTimeStr == null)
+ throw new ValidateException("validator.68", null) ;
+
+ Calendar signingTimeCal = DatatypeConverter.parseDate(signingTimeStr);
+ Calendar serverTimeCal = new GregorianCalendar();
+
+ long diff = Math.abs(signingTimeCal.getTimeInMillis() - serverTimeCal.getTimeInMillis());
+
+ if (diff > MAX_DIFFERENCE_IN_MILLISECONDS)
+ throw new ValidateException("validator.69", new Object[] {"mehr als " + MAX_DIFFERENCE_IN_MILLISECONDS + " Millisekunden"}) ;
+
+ Logger.debug("Compare \"" + signingTimeCal.getTime() + "\" (SigningTime) with \"" + serverTimeCal.getTime() + "\" (server time)");
+
+
+ }
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java
new file mode 100644
index 000000000..fa6486afe
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java
@@ -0,0 +1,209 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.validator;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.exception.ValidateException;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.XPathUtils;
+
+/**
+ * This class is used to validate an {@link IdentityLink}
+ * returned by the security layer
+ *
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+public class IdentityLinkValidator implements Constants {
+
+ //
+ // XPath namespace prefix shortcuts
+ //
+ /** Xpath prefix for reaching PersonData Namespaces */
+ private static final String PDATA = PD_PREFIX + ":";
+ /** Xpath prefix for reaching SAML Namespaces */
+ private static final String SAML = SAML_PREFIX + ":";
+ /** Xpath prefix for reaching XML-DSIG Namespaces */
+ private static final String DSIG = DSIG_PREFIX + ":";
+ /** Xpath prefix for reaching ECDSA Namespaces */
+ private static final String ECDSA = ECDSA_PREFIX + ":";
+ /** Xpath expression to the root element */
+ private static final String ROOT = "";
+ /** Xpath expression to the SAML:SubjectConfirmationData element */
+ private static final String SAML_SUBJECT_CONFIRMATION_DATA_XPATH =
+ ROOT
+ + SAML
+ + "AttributeStatement/"
+ + SAML
+ + "Subject/"
+ + SAML
+ + "SubjectConfirmation/"
+ + SAML
+ + "SubjectConfirmationData";
+/** Xpath expression to the PersonData:Person element */
+ private static final String PERSON_XPATH =
+ SAML_SUBJECT_CONFIRMATION_DATA_XPATH + "/" + PDATA + "Person";
+ /** Xpath expression to the SAML:Attribute element */
+ private static final String ATTRIBUTE_XPATH =
+ ROOT + SAML + "AttributeStatement/" + SAML + "Attribute";
+// /** Xpath expression to the SAML:AttributeName attribute */
+// private static final String ATTRIBUTE_NAME_XPATH =
+// ROOT + SAML + "AttributeStatement/" + SAML + "Attribute/@AttributeName";
+// /** Xpath expression to the SAML:AttributeNamespace attribute */
+// private static final String ATTRIBUTE_NAMESPACE_XPATH =
+// ROOT
+// + SAML
+// + "AttributeStatement/"
+// + SAML
+// + "Attribute/@AttributeNamespace";
+// /** Xpath expression to the SAML:AttributeValue element */
+// private static final String ATTRIBUTE_VALUE_XPATH =
+// ROOT
+// + SAML
+// + "AttributeStatement/"
+// + SAML
+// + "Attribute/"
+// + SAML
+// + "AttributeValue";
+
+ /** Singleton instance. <code>null</code>, if none has been created. */
+ private static IdentityLinkValidator instance;
+
+ /**
+ * Constructor for a singleton IdentityLinkValidator.
+ * @return a new IdentityLinkValidator instance
+ * @throws ValidateException if no instance can be created
+ */
+ public static synchronized IdentityLinkValidator getInstance()
+ throws ValidateException {
+ if (instance == null) {
+ instance = new IdentityLinkValidator();
+ }
+ return instance;
+ }
+
+ /**
+ * Method validate. Validates the {@link IdentityLink}
+ * @param identityLink The identityLink to validate
+ * @throws ValidateException on any validation error
+ */
+ public void validate(IdentityLink identityLink) throws ValidateException {
+
+ Element samlAssertion = identityLink.getSamlAssertion();
+ //Search the SAML:ASSERTION Object (A2.054)
+ if (samlAssertion == null) {
+ throw new ValidateException("validator.00", null);
+ }
+
+ // Check how many saml:Assertion/saml:AttributeStatement/
+ // saml:Subject/ saml:SubjectConfirmation/
+ // saml:SubjectConfirmationData/pr:Person of type
+ // PhysicalPersonType exist (A2.056)
+ NodeList nl = XPathUtils.selectNodeList(samlAssertion, PERSON_XPATH);
+ // If we have just one Person-Element we don't need to check the attributes
+ int counterPhysicalPersonType = 0;
+ if (nl.getLength() > 1)
+ for (int i = 0; i < nl.getLength(); i++) {
+ String xsiType =
+ ((Element) nl.item(i))
+ .getAttributeNodeNS(
+ "http://www.w3.org/2001/XMLSchema-instance",
+ "type")
+ .getNodeValue();
+ // We have to check if xsiType contains "PhysicalPersonType"
+ // An equal-check will fail because of the Namespace-prefix of the attribute value
+ if (xsiType.indexOf("PhysicalPersonType") > -1)
+ counterPhysicalPersonType++;
+ }
+ if (counterPhysicalPersonType > 1)
+ throw new ValidateException("validator.01", null);
+
+ //Check the SAML:ATTRIBUTES
+ nl = XPathUtils.selectNodeList(samlAssertion, ATTRIBUTE_XPATH);
+ for (int i = 0; i < nl.getLength(); i++) {
+ String attributeName =
+ XPathUtils.getAttributeValue(
+ (Element) nl.item(i),
+ "@AttributeName",
+ null);
+ String attributeNS =
+ XPathUtils.getAttributeValue(
+ (Element) nl.item(i),
+ "@AttributeNamespace",
+ null);
+ if (attributeName.equals("CitizenPublicKey")) {
+
+ if (attributeNS.equals("http://www.buergerkarte.at/namespaces/personenbindung/20020506#") ||
+ attributeNS.equals("urn:publicid:gv.at:namespaces:identitylink:1.2")) {
+ Element attributeValue =
+ (Element) XPathUtils.selectSingleNode((Element) nl.item(i),nSMap, SAML + "AttributeValue/" + DSIG + "RSAKeyValue");
+ if (attributeValue==null)
+ attributeValue =
+ (Element) XPathUtils.selectSingleNode((Element)nl.item(i), nSMap, SAML + "AttributeValue/" + ECDSA + "ECDSAKeyValue");
+ if (attributeValue==null)
+ attributeValue =
+ (Element) XPathUtils.selectSingleNode((Element)nl.item(i), nSMap, SAML + "AttributeValue/" + DSIG + "DSAKeyValue");
+ if (attributeValue == null)
+ throw new ValidateException("validator.02", null);
+
+ }
+ else
+ throw new ValidateException("validator.03", new Object [] {attributeNS} );
+ }
+ else
+ throw new ValidateException("validator.04", new Object [] {attributeName} );
+ }
+
+ //Check if dsig:Signature exists
+ Element dsigSignature = (Element) XPathUtils.selectSingleNode(samlAssertion,ROOT + DSIG + "Signature");
+ if (dsigSignature==null) throw new ValidateException("validator.05", new Object[] {"in der Personenbindung"});
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/InfoboxValidator.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/InfoboxValidator.java
new file mode 100644
index 000000000..e6e2539c9
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/InfoboxValidator.java
@@ -0,0 +1,128 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.validator;
+
+import java.util.Map;
+
+import org.w3c.dom.Element;
+
+import at.gv.egovernment.moa.id.auth.data.InfoboxValidationResult;
+import at.gv.egovernment.moa.id.auth.data.InfoboxValidatorParams;
+import at.gv.egovernment.moa.id.auth.exception.ValidateException;
+
+/**
+ * Validates an InfoboxReadResponse.
+ * An implementing class has to validate the content of the InfoboxReadResponse
+ * according to the type specific rules and guidelines of the underlying
+ * application.
+ */
+public interface InfoboxValidator {
+
+ /**
+ * This method validates an InfoboxReadResponse.
+ * The method validates the content of the passed <code>infoboxReadResponse</code>
+ * according to the type specific rules and guidelines of the underlying
+ * application.
+ *
+ * @param params {@link at.gv.egovernment.moa.id.auth.data.InfoboxValidatorParams
+ * Parameters} needed by the validator.
+ *
+ * @return InfoboxValidationResult structure (@link at.gv.egovernment.moa.id.auth.data.InfoboxValidationResult}
+ *
+ * @throws ValidateException If an error occurs on validating the
+ * InfoboxReadResponse.
+ */
+ public InfoboxValidationResult validate (InfoboxValidatorParams params)
+ throws ValidateException;
+
+ /**
+ * This method is used to do intermediate processing before signing the auth block.
+ * If a infobox validator threw a form to gather user input, this method is used
+ * to validate this input. In no further input is needed the form must be empty to
+ * proceed, and also a valid <code>InfoboxValidationResult</code> is necessary.
+ * If more input is needed, the validator can build a new form and it is then shown
+ * to the citizen.
+ * The implementation of <code>InfoboxValidator</code> must hold its necessary
+ * data and configuration internally, if this method is called - the class is
+ * reused at this call
+ *
+ * @param parameters the parameters got returned by the input fields
+ *
+ * @return InfoboxValidationResult structure (@link at.gv.egovernment.moa.id.auth.data.InfoboxValidationResult}
+ *
+ * @throws ValidateException If an error occurs on validating the
+ * InfoboxReadResponse.
+ */
+ public InfoboxValidationResult validate (Map parameters)
+ throws ValidateException;
+
+ /**
+ * This method is used to do post processing after signing the auth block.
+ * The method validates the content of the <code>infoboxReadResponse</code
+ * against the passed <code>samlAssertion</code> if needed.
+ * The implementation of <code>InfoboxValidator</code> must hold its necessary
+ * data and configuration internally, if this method is called - the class is
+ * reused at this call
+ *
+ * @param samlAssertion the SAML assertion needed by the validator
+ *
+ * @return InfoboxValidationResult structure (@link at.gv.egovernment.moa.id.auth.data.InfoboxValidationResult}
+ *
+ * @throws ValidateException If an error occurs on validating the
+ * InfoboxReadResponse.
+ */
+ public InfoboxValidationResult validate (Element samlAssertion)
+ throws ValidateException;
+
+ /**
+ * form for user interaction for intermediate processing of infobox validation
+ *
+ * @return answer form of the servlet request.
+ */
+ public String getForm();
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java
new file mode 100644
index 000000000..ac528c89d
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java
@@ -0,0 +1,303 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.validator;
+
+import iaik.asn1.ObjectID;
+import iaik.asn1.structures.Name;
+import iaik.security.ecc.ecdsa.ECPublicKey;
+import iaik.utils.RFC2253NameParserException;
+import iaik.x509.X509Certificate;
+import iaik.x509.X509ExtensionInitException;
+
+import java.security.InvalidKeyException;
+import java.security.PublicKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
+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.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters;
+import at.gv.egovernment.moa.id.util.MOAIDMessageProvider;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * This class is used to validate an {@link VerifyXMLSignatureResponse}
+ * returned by MOA-SPSS
+ *
+ * @author Stefan Knirsch
+ * @version $Id$
+ */
+public class VerifyXMLSignatureResponseValidator {
+
+ /** Identification string for checking identity link */
+ public static final String CHECK_IDENTITY_LINK = "IdentityLink";
+ /** Identification string for checking authentication block */
+ public static final String CHECK_AUTH_BLOCK = "AuthBlock";
+
+ /** Singleton instance. <code>null</code>, if none has been created. */
+ private static VerifyXMLSignatureResponseValidator instance;
+
+ /**
+ * Constructor for a singleton VerifyXMLSignatureResponseValidator.
+ */
+ public static synchronized VerifyXMLSignatureResponseValidator getInstance()
+ throws ValidateException {
+ if (instance == null) {
+ instance = new VerifyXMLSignatureResponseValidator();
+ }
+ return instance;
+ }
+
+ /**
+ * Validates a {@link VerifyXMLSignatureResponse} returned by MOA-SPSS.
+ *
+ * @param verifyXMLSignatureResponse the <code>&lt;VerifyXMLSignatureResponse&gt;</code>
+ * @param identityLinkSignersSubjectDNNames subject names configured
+ * @param whatToCheck is used to identify whether the identityLink or the Auth-Block is validated
+ * @param oaParam specifies whether the validation result of the
+ * manifest has to be ignored (identityLink validation if
+ * the OA is a business service) or not
+ * @throws ValidateException on any validation error
+ * @throws ConfigurationException
+ */
+ public void validate(VerifyXMLSignatureResponse verifyXMLSignatureResponse,
+ List<String> identityLinkSignersSubjectDNNames,
+ String whatToCheck,
+ IOAAuthParameters oaParam)
+ throws ValidateException, ConfigurationException {
+
+ if (verifyXMLSignatureResponse.getSignatureCheckCode() != 0)
+ throw new ValidateException("validator.06", null);
+
+ if (verifyXMLSignatureResponse.getCertificateCheckCode() != 0) {
+ String checkFailedReason ="";
+ if (verifyXMLSignatureResponse.getCertificateCheckCode() == 1)
+ checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.21", null);
+ if (verifyXMLSignatureResponse.getCertificateCheckCode() == 2)
+ checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.22", null);
+ if (verifyXMLSignatureResponse.getCertificateCheckCode() == 3)
+ checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.23", null);
+ if (verifyXMLSignatureResponse.getCertificateCheckCode() == 4)
+ checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.24", null);
+ if (verifyXMLSignatureResponse.getCertificateCheckCode() == 5)
+ checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.25", null);
+
+// TEST CARDS
+ if (whatToCheck.equals(CHECK_IDENTITY_LINK))
+ throw new ValidateException("validator.07", new Object[] { checkFailedReason } );
+ else
+ throw new ValidateException("validator.19", new Object[] { checkFailedReason } );
+ }
+
+ //check QC
+ if (AuthConfigurationProviderFactory.getInstance().isCertifiacteQCActive() &&
+ !whatToCheck.equals(CHECK_IDENTITY_LINK) &&
+ !verifyXMLSignatureResponse.isQualifiedCertificate()) {
+
+ //check if testcards are active and certificate has an extension for test credentials
+ if (oaParam.isTestCredentialEnabled()) {
+ boolean foundTestCredentialOID = false;
+ try {
+ X509Certificate signerCert = verifyXMLSignatureResponse.getX509certificate();
+
+ List<String> validOIDs = new ArrayList<String>();
+ if (oaParam.getTestCredentialOIDs() != null)
+ validOIDs.addAll(oaParam.getTestCredentialOIDs());
+ else
+ validOIDs.add(MOAIDAuthConstants.TESTCREDENTIALROOTOID);
+
+ Set<String> extentsions = signerCert.getCriticalExtensionOIDs();
+ extentsions.addAll(signerCert.getNonCriticalExtensionOIDs());
+ Iterator<String> extit = extentsions.iterator();
+ while(extit.hasNext()) {
+ String certOID = extit.next();
+ for (String el : validOIDs) {
+ if (certOID.startsWith(el))
+ foundTestCredentialOID = true;
+ }
+ }
+
+ } catch (Exception e) {
+ Logger.warn("Test credential OID extraction FAILED.", e);
+
+ }
+ //throw Exception if not TestCredentialOID is found
+ if (!foundTestCredentialOID)
+ throw new ValidateException("validator.72", null);
+
+ } else
+ throw new ValidateException("validator.71", null);
+ }
+
+ // if OA is type is business service the manifest validation result has
+ // to be ignored
+ boolean ignoreManifestValidationResult = false;
+ if (whatToCheck.equals(CHECK_IDENTITY_LINK))
+ ignoreManifestValidationResult = (oaParam.getBusinessService()) ? true
+ : false;
+
+ if (ignoreManifestValidationResult) {
+ Logger.debug("OA type is business service, thus ignoring DSIG manifest validation result");
+ } else {
+ if (verifyXMLSignatureResponse.isXmlDSIGManigest())
+ if (verifyXMLSignatureResponse.getXmlDSIGManifestCheckCode() != 0)
+ throw new ValidateException("validator.08", null);
+ }
+
+
+ // Check the signature manifest only when verifying the signed AUTHBlock
+ if (whatToCheck.equals(CHECK_AUTH_BLOCK)) {
+ if (verifyXMLSignatureResponse.getSignatureManifestCheckCode() > 0) {
+ throw new ValidateException("validator.50", null);
+ }
+ }
+
+ //Check whether the returned X509 SubjectName is in the MOA-ID configuration or not
+ if (identityLinkSignersSubjectDNNames != null) {
+ String subjectDN = "";
+ X509Certificate x509Cert = verifyXMLSignatureResponse.getX509certificate();
+ try {
+ subjectDN = ((Name) x509Cert.getSubjectDN()).getRFC2253String();
+ }
+ catch (RFC2253NameParserException e) {
+ throw new ValidateException("validator.17", null);
+ }
+ //System.out.println("subjectDN: " + subjectDN);
+ // check the authorisation to sign the identity link
+ if (!identityLinkSignersSubjectDNNames.contains(subjectDN)) {
+ // subject DN check failed, try OID check:
+ try {
+ if (x509Cert.getExtension(MOAIDAuthConstants.IDENTITY_LINK_SIGNER_OID) == null) {
+ throw new ValidateException("validator.18", new Object[] { subjectDN });
+ } else {
+ Logger.debug("Identity link signer cert accepted for signing identity link: " +
+ "subjectDN check failed, but OID check successfully passed.");
+ }
+ } catch (X509ExtensionInitException e) {
+ throw new ValidateException("validator.49", null);
+ }
+ } else {
+ Logger.debug("Identity link signer cert accepted for signing identity link: " +
+ "subjectDN check successfully passed.");
+ }
+
+ }
+ }
+
+ /**
+ * Method validateCertificate.
+ * @param verifyXMLSignatureResponse The VerifyXMLSignatureResponse
+ * @param idl The Identitylink
+ * @throws ValidateException
+ */
+ public void validateCertificate(
+ VerifyXMLSignatureResponse verifyXMLSignatureResponse,
+ IdentityLink idl)
+ throws ValidateException {
+
+ X509Certificate x509Response = verifyXMLSignatureResponse.getX509certificate();
+ PublicKey[] pubKeysIdentityLink = (PublicKey[]) idl.getPublicKey();
+
+ PublicKey pubKeySignature = x509Response.getPublicKey();
+
+ boolean found = false;
+ for (int i = 0; i < pubKeysIdentityLink.length; i++) {
+
+ //compare RSAPublicKeys
+ if ((idl.getPublicKey()[i] instanceof java.security.interfaces.RSAPublicKey) &&
+ (pubKeySignature instanceof java.security.interfaces.RSAPublicKey)) {
+
+ RSAPublicKey rsaPubKeySignature = (RSAPublicKey) pubKeySignature;
+ RSAPublicKey rsakey = (RSAPublicKey) pubKeysIdentityLink[i];
+
+ if (rsakey.getModulus().equals(rsaPubKeySignature.getModulus())
+ && rsakey.getPublicExponent().equals(rsaPubKeySignature.getPublicExponent()))
+ found = true;
+ }
+
+ //compare ECDSAPublicKeys
+ if( ( (idl.getPublicKey()[i] instanceof java.security.interfaces.ECPublicKey) ||
+ (idl.getPublicKey()[i] instanceof iaik.security.ecc.ecdsa.ECPublicKey)) &&
+ ( (pubKeySignature instanceof java.security.interfaces.ECPublicKey) ||
+ (pubKeySignature instanceof iaik.security.ecc.ecdsa.ECPublicKey) ) ) {
+
+ try {
+ ECPublicKey ecdsaPubKeySignature = new ECPublicKey(pubKeySignature.getEncoded());
+ ECPublicKey ecdsakey = new ECPublicKey(pubKeysIdentityLink[i].getEncoded());
+
+ if(ecdsakey.equals(ecdsaPubKeySignature))
+ found = true;
+
+ } catch (InvalidKeyException e) {
+ Logger.warn("ECPublicKey can not parsed into a iaik.ECPublicKey", e);
+ throw new ValidateException("validator.09", null);
+ }
+
+
+
+ }
+
+// Logger.debug("IDL-Pubkey=" + idl.getPublicKey()[i].getClass().getName()
+// + " Resp-Pubkey=" + pubKeySignature.getClass().getName());
+
+ }
+
+ if (!found) {
+
+ throw new ValidateException("validator.09", null);
+
+ }
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/ParepUtils.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/ParepUtils.java
new file mode 100644
index 000000000..1850ff671
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/ParepUtils.java
@@ -0,0 +1,762 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.validator.parep;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.apache.xml.serialize.OutputFormat;
+import org.apache.xml.serialize.XMLSerializer;
+import org.apache.xpath.XPathAPI;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+import at.gv.egovernment.moa.id.auth.builder.BPKBuilder;
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.id.auth.exception.ValidateException;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException;
+import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWConstants;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.BoolUtils;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.StringUtils;
+
+/**
+ * This class implements a set of utility methods.
+ *
+ * @author <a href="mailto:peter.danner@egiz.gv.at">Peter Danner</a>
+ */
+public class ParepUtils {
+
+ /**
+ * Determines whether a string is null or empty
+ *
+ * @param str the string to check.
+ * @return <code>true</code> if the string is null or empty,
+ * <code>false</code> otherwise.
+ */
+ public static boolean isEmpty(String str) {
+ return str == null || "".equals(str);
+ }
+
+ /**
+ * Reads a XML document from an input stream (namespace-aware).
+ *
+ * @param is
+ * the input stream to read from.
+ * @return the read XML document.
+ * @throws SZRGWClientException
+ * if an error occurs reading the document from the input stream.
+ */
+ public static Document readDocFromIs(InputStream is) throws SZRGWClientException {
+ try {
+ DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
+ f.setNamespaceAware(true);
+ return f.newDocumentBuilder().parse(is);
+ } catch (Exception e) {
+ throw new SZRGWClientException(e);
+ }
+ }
+
+// /*
+// *
+// */
+// public static String extractRepresentativeID(Element mandate) throws ValidateException {
+// try {
+// Element nameSpaceNode = mandate.getOwnerDocument().createElement("NameSpaceNode");
+// nameSpaceNode.setAttribute("xmlns:md", SZRGWConstants.MANDATE_NS);
+// Node resultNode = XPathAPI.selectSingleNode(mandate, "//md:Mandate/attribute::MandateID", nameSpaceNode);
+// if (resultNode != null) {
+// // because following line is not ready for JDK 1.4.x we need to get the childnode;
+// // return resultNode.getTextContent();
+// Node textNode = resultNode.getFirstChild();
+// if (textNode != null) {
+// return textNode.getNodeValue();
+// }
+// }
+// return null;
+// } catch (Exception e) {
+// throw new ValidateException("validator.62", null);
+// }
+// }
+
+
+ /**
+ * Dumps all bytes from an input stream to the given output stream.
+ *
+ * @param is
+ * the input stream to dump from.
+ * @param os
+ * the output stream to dump to.
+ * @throws IOException
+ * if an error occurs while dumping.
+ */
+ public static void dumpInputOutputStream(InputStream is, OutputStream os) throws IOException {
+ if (is == null) {
+ return;
+ }
+ int ch;
+ while ((ch = is.read()) != -1) {
+ os.write(ch);
+ }
+ }
+
+ /**
+ * Gets a string that represents the date a mandate was issued.
+ *
+ * @param mandate
+ * the mandate to extract the issuing date from.
+ * @return the issuing date of the given mandate.
+ * @throws SZRGWClientException
+ * if an exception occurs extracting the issuing date of the
+ * mandate.
+ */
+ public static String getMandateIssuedDate(Element mandate) throws SZRGWClientException {
+ try {
+ Element nameSpaceNode = mandate.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns:md", SZRGWConstants.MANDATE_NS);
+
+ Node dateNode = XPathAPI.selectSingleNode(mandate, "//md:Issued/md:Date/text()", nameSpaceNode);
+
+ if (dateNode == null) {
+ throw new Exception("Date in Mandate-Issued not found.");
+ }
+ return dateNode.getNodeValue();
+ } catch (Exception e) {
+ throw new SZRGWClientException(e);
+ }
+ }
+
+ /**
+ * Gets a string that represents the place a mandate was issued.
+ *
+ * @param mandate
+ * the mandate to extract the issuing place from.
+ * @return the issuing place of the given mandate.
+ * @throws SZRGWClientException
+ * if an exception occurs extracting the issuing place of the
+ * mandate.
+ */
+ public static String getMandateIssuedPlace(Element mandate) throws SZRGWClientException {
+ try {
+ Element nameSpaceNode = mandate.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns:md", SZRGWConstants.MANDATE_NS);
+
+ Node placeNode = XPathAPI.selectSingleNode(mandate, "//md:Issued/md:Place/text()", nameSpaceNode);
+
+ if (placeNode == null) {
+ throw new Exception("Place in Mandate-Issued not found.");
+ }
+ return placeNode.getNodeValue();
+ } catch (Exception e) {
+ throw new SZRGWClientException(e);
+ }
+ }
+
+ /**
+ * Extracts the textual description of the mandate.
+ *
+ * @param mandate
+ * the mandate to extract the textual description from.
+ * @return the textual description of the mandate.
+ * @throws SZRGWClientException
+ * if an exception occurs extracting the textual description.
+ */
+ public static String getMandateContent(Element mandate) throws SZRGWClientException {
+ try {
+ Element nameSpaceNode = mandate.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns:md", SZRGWConstants.MANDATE_NS);
+
+ Node contentNode = XPathAPI.selectSingleNode(mandate, "//md:SimpleMandateContent/md:TextualDescription/text()", nameSpaceNode);
+
+ if (contentNode == null) {
+ throw new Exception("Content in Mandate not found.");
+ }
+ return contentNode.getNodeValue();
+ } catch (Exception e) {
+ throw new SZRGWClientException(e);
+ }
+ }
+
+ /**
+ * Extracts the md:Mandator element from a XML mandate element.
+ *
+ * @param mandate
+ * the md:Mandate element to extract the md:Mandator from.
+ * @return the md:Mandator element.
+ * @throws SZRGWClientException
+ * if an error occurs extracting the md:Mandator element.
+ */
+ public static Element extractMandator(Element mandate) throws ParseException {
+ try {
+
+ Element nameSpaceNode = mandate.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX, SZRGWConstants.MANDATE_NS);
+ Element mandator = (Element) XPathAPI.selectSingleNode(mandate, "//" + SZRGWConstants.MANDATE_PREFIX + SZRGWConstants.MANDATOR, nameSpaceNode);
+ if (mandator == null) {
+ // if we got the Mandator itself
+ if (mandate.getLocalName().equals(SZRGWConstants.MANDATOR)) return mandate;
+ }
+ if (mandator == null)
+ return null;
+ String nsPrefix = mandator.getPrefix();
+ String nsUri = mandator.getNamespaceURI();
+ Element mandatorClone = (Element) mandator.cloneNode(true);
+ mandatorClone.setAttribute("xmlns:" + nsPrefix, nsUri);
+ return mandatorClone;
+ } catch (Exception e) {
+ throw new ParseException(e.toString(), null);
+ }
+ }
+
+ /**
+ * Tells wether a mandator is a physical person or not.
+ *
+ * @param mandator
+ * the XML md:Mandator element to extract from.
+ * @return <code>true<code> if the mandator is a physical person, <code>false</code> otherwise.
+ */
+ public static boolean isPhysicalPerson(Element mandator) {
+ try {
+ Element nameSpaceNode = mandator.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+
+ DOMUtils.serializeNode(mandator);
+
+ // check if physical person
+ Element physicalPerson = (Element) XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:PhysicalPerson", nameSpaceNode);
+
+
+ // Element physicalPerson = (Element)XPathAPI.selectSingleNode(mandator,
+ // "descendant-or-self::pr:CorporateBody", nameSpaceNode);
+ return physicalPerson != null;
+ } catch (Exception e) {
+ e.printStackTrace();
+ return false;
+ }
+ }
+
+ /**
+ * Extracts the <code>pr:PhysicalPerson</code> or <code>pr:CorporateBody</code>
+ * element from a XML mandate element.
+ *
+ * @param mandate
+ * the md:Mandate element to extract the person from.
+ * @return the <code>pr:PhysicalPerson</code> or <code>pr:CorporateBody</code> element.
+ * @throws ParseException
+ * if an error occurs extracting the element.
+ */
+ public static Element extractPersonOfMandate(Element mandate) throws ParseException {
+ try {
+
+ Element nameSpaceNode = mandate.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX, SZRGWConstants.MANDATE_NS);
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+ Element person = (Element) XPathAPI.selectSingleNode(mandate, "//" + SZRGWConstants.MANDATE_PREFIX + SZRGWConstants.MANDATOR + "/pr:PhysicalPerson", nameSpaceNode);
+ if (person == null) {
+ person = (Element) XPathAPI.selectSingleNode(mandate, "//" + SZRGWConstants.MANDATE_PREFIX + SZRGWConstants.MANDATOR + "/pr:CorporateBody", nameSpaceNode);
+ }
+ if (person == null) return null;
+ String nsPrefix = person.getPrefix();
+ String nsUri = person.getNamespaceURI();
+ Element personClone = (Element) person.cloneNode(true);
+ personClone.setAttribute("xmlns:" + nsPrefix, nsUri);
+ return personClone;
+ } catch (Exception e) {
+ //e.printStackTrace();
+ throw new ParseException(e.toString(), null);
+ }
+ }
+
+ /**
+ * Benerates the </code>pr:Person</code> element form a
+ * <code>pr:PhysicalPerson</code> or <code>pr:CorporateBody</code>
+ * element of a XML mandate element.
+ *
+ * @param mandate
+ * the md:Mandate element to extract the person from.
+ * @return the <code>pr:Person</code> element.
+ * @throws ParseException
+ * if an error occurs extracting the element.
+ */
+ public static Element extractPrPersonOfMandate(Element mandate) throws ParseException {
+
+ try {
+ Document document = ParepUtils.createEmptyDocument();
+ Element root = document.createElement(SZRGWConstants.PD_PREFIX + SZRGWConstants.PERSON);
+ root.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+ root.setAttribute("xmlns:" + Constants.XSI_PREFIX, Constants.XSI_NS_URI);
+
+ Element nameSpaceNode = mandate.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX, SZRGWConstants.MANDATE_NS);
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+ Element person = (Element) XPathAPI.selectSingleNode(mandate, "//"
+ + SZRGWConstants.MANDATE_PREFIX + SZRGWConstants.MANDATOR + "/" + SZRGWConstants.PD_PREFIX + SZRGWConstants.PHYSICALPERSON, nameSpaceNode);
+ if (person == null) {
+ person = (Element) XPathAPI.selectSingleNode(mandate, "//"
+ + SZRGWConstants.MANDATE_PREFIX + SZRGWConstants.MANDATOR + "/" + SZRGWConstants.PD_PREFIX + SZRGWConstants.CORPORATEBODY, nameSpaceNode);
+ }
+ if (person != null) {
+ root.setAttribute(Constants.XSI_PREFIX + ":type", SZRGWConstants.PD_PREFIX + person.getLocalName());
+ if (person != null) {
+ NodeList nl = person.getChildNodes();
+ for (int i = 0; i < nl.getLength(); i++) {
+ Node testNode = nl.item(i);
+ if (Node.ELEMENT_NODE == testNode.getNodeType()) {
+ root.appendChild(document.importNode(testNode, true));
+ }
+ }
+ }
+ }
+
+ return root;
+ } catch (Exception e) {
+ //e.printStackTrace();
+ throw new ParseException(e.toString(), null);
+ }
+ }
+
+ /**
+ * Extracts the name of the mandator as a string representation.
+ *
+ * @param mandator
+ * the XML md:Mandator element to extract from.
+ * @return the mandator name as a string.
+ */
+ public static String extractMandatorName(Element mandator) {
+ try {
+ Element nameSpaceNode = mandator.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+
+ // first check if physical person
+ Element name = (Element) XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:Name/pr:GivenName", nameSpaceNode);
+ if (name != null) {
+ String givenName = XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:Name/pr:GivenName/text()", nameSpaceNode).getNodeValue();
+ String familyName = XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:Name/pr:FamilyName/text()", nameSpaceNode).getNodeValue();
+
+ return givenName + " " + familyName;
+ }
+
+ // check if corporate body
+ Node fullName = XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:FullName/text()", nameSpaceNode);
+ if (fullName != null) {
+ return fullName.getNodeValue();
+ }
+ return "";
+ } catch (Exception e) {
+ //e.printStackTrace();
+ return "";
+ }
+ }
+
+ /**
+ * Extracts specific text of an element of a given md:Mandator element.
+ *
+ * @param mandator
+ * the XML md:Mandator to extract from.
+ * @return the resulting text of the mandator element.
+ */
+ public static String extractText(Element mandator, String xpath) {
+ try {
+ Element nameSpaceNode = mandator.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+
+ Node textNode = XPathAPI.selectSingleNode(mandator, xpath, nameSpaceNode);
+ if (textNode == null)
+ return null;
+ return textNode.getNodeValue();
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * Extracts the date of birth of the mandator of a given md:Mandator element.
+ *
+ * @param mandator
+ * the XML md:Mandator to extract from.
+ * @return the dob of the mandator.
+ */
+ public static String extractMandatorDateOfBirth(Element mandator) {
+ try {
+ Element nameSpaceNode = mandator.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+
+ Node dobName = XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:DateOfBirth/text()", nameSpaceNode);
+ if (dobName == null)
+ return null;
+ return dobName.getNodeValue();
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * Extracts the full name of the mandators corporate body of a given
+ * md:Mandator element.
+ *
+ * @param mandator
+ * the XML md:Mandator to extract from.
+ * @return the full name of the mandator.
+ */
+ public static String extractMandatorFullName(Element mandator) {
+ try {
+ Element nameSpaceNode = mandator.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+
+ Node fullName = XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:CorporateBody/pr:FullName/text()", nameSpaceNode);
+ if (fullName == null)
+ return null;
+ return fullName.getNodeValue();
+ } catch (Exception e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * Extracts the identification value of the mandator of a given mandate.
+ *
+ * @param mandator
+ * the XML md:Mandator element.
+ * @return the identification value.
+ */
+ public static String extractMandatorWbpk(Element mandator) {
+ try {
+ Element nameSpaceNode = mandator.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+
+ Node idValue = XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:Identification/pr:Value/text()", nameSpaceNode);
+ if (idValue != null) {
+ return idValue.getNodeValue();
+ }
+ return "";
+ } catch (Exception e) {
+ e.printStackTrace();
+ return "";
+ }
+ }
+
+ /**
+ * Extracts the identification type of the mandator of a given mandate.
+ *
+ * @param mandator
+ * the XML md:Mandator element.
+ * @return the identification type.
+ */
+ public static String extractMandatorIdentificationType(Element mandator) {
+ try {
+ Element nameSpaceNode = mandator.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+
+ Node idType = XPathAPI.selectSingleNode(mandator, "descendant-or-self::pr:Identification/pr:Type/text()", nameSpaceNode);
+ if (idType != null) {
+ return idType.getNodeValue();
+ }
+ return "";
+ } catch (Exception e) {
+ e.printStackTrace();
+ return "";
+ }
+ }
+
+ /*
+ *
+ */
+ public static String getIdentification(Element personElement, String element) throws ParseException {
+ try {
+
+ Element nameSpaceNode = personElement.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+
+ return XPathAPI.selectSingleNode(personElement, "descendant-or-self::pr:Identification/pr:" + element + "/text()", nameSpaceNode)
+ .getNodeValue();
+ } catch (Exception e) {
+ throw new ParseException(e.toString(), null);
+ }
+ }
+
+// /*
+// *
+// */
+// private static Element extractRepresentative(Element mandate) throws SZRGWClientException {
+// try {
+// Element nameSpaceNode = mandate.getOwnerDocument().createElement("NameSpaceNode");
+// nameSpaceNode.setAttribute("xmlns:md", SZRGWConstants.MANDATE_NS);
+// Element mandator = (Element) XPathAPI.selectSingleNode(mandate, "//md:Representative/child::*[1]", nameSpaceNode);
+// String nsPrefix = mandator.getPrefix();
+// String nsUri = mandator.getNamespaceURI();
+//
+// Element mandatorClone = (Element) mandator.cloneNode(true);
+// mandatorClone.setAttribute("xmlns:" + nsPrefix, nsUri);
+//
+// return mandatorClone;
+// } catch (Exception e) {
+// throw new SZRGWClientException(e);
+// }
+// }
+
+ /**
+ * Serializes a XML element to a given output stream.
+ *
+ * @param element
+ * the XML element to serialize.
+ * @param out
+ * the output streamt o serialize to.
+ * @throws IOException
+ * if an I/O error occurs during serialization.
+ */
+ public static void serializeElement(Element element, OutputStream out) throws IOException {
+ OutputFormat format = new OutputFormat();
+ format.setOmitXMLDeclaration(true);
+ format.setEncoding("UTF-8");
+ format.setPreserveSpace(true);
+ XMLSerializer serializer = new XMLSerializer(new OutputStreamWriter(out, "UTF-8"), format);
+ serializer.serialize(element);
+ }
+
+ public static void serializeElementAsDocument(Element element, OutputStream out) throws IOException {
+ OutputFormat format = new OutputFormat();
+ format.setOmitXMLDeclaration(false);
+ format.setEncoding("UTF-8");
+ format.setPreserveSpace(true);
+ XMLSerializer serializer = new XMLSerializer(new OutputStreamWriter(out, "UTF-8"), format);
+ serializer.serialize(element);
+ }
+
+ public static void serializeElementWithoutEncoding(Element element, OutputStream out) throws IOException {
+ OutputFormat format = new OutputFormat();
+ format.setOmitXMLDeclaration(true);
+ format.setEncoding("UTF-8");
+ format.setPreserveSpace(true);
+ XMLSerializer serializer = new XMLSerializer(new OutputStreamWriter(out), format);
+ serializer.serialize(element);
+ }
+
+ public static void saveStringToFile(String str, File file) throws IOException {
+ FileOutputStream fos = new FileOutputStream(file);
+ fos.write(str.getBytes());
+ fos.flush();
+ fos.close();
+ }
+
+ public static void saveBytesToFile(byte[] str, File file) throws IOException {
+ FileOutputStream fos = new FileOutputStream(file);
+ fos.write(str);
+ fos.flush();
+ fos.close();
+ }
+
+ public static void saveElementToFile(Element elem, File file) throws IOException {
+ FileOutputStream fos = new FileOutputStream(file);
+ serializeElementWithoutEncoding(elem, fos);
+ fos.flush();
+ fos.close();
+ }
+
+ /**
+ * Creates an empty XML document.
+ *
+ * @return a newly created empty XML document.
+ * @throws SZRGWClientException
+ * if an error occurs creating the empty document.
+ */
+ public static Document createEmptyDocument() throws SZRGWClientException {
+ try {
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ return factory.newDocumentBuilder().newDocument();
+ } catch (Exception e) {
+ throw new SZRGWClientException(e);
+ }
+ }
+
+
+ /**
+ * Tells if the Validator of an Infobox is enabled. If the corresponding application
+ * specific configuration element <code>EnableInfoboxValidator</code> is missing, a default value <code>true</code> is assumed
+ *
+ * @param applicationSpecificParams
+ * the XML element of the infobox configuration.
+ * @return the boolean value of the determination.
+ * @throws ConfigurationException
+ * if an error occurs reading the configuration.
+ */
+ public static boolean isValidatorEnabled(Element applicationSpecificParams) throws ConfigurationException {
+ try {
+ Element nameSpaceNode = applicationSpecificParams.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns:" + Constants.MOA_ID_CONFIG_PREFIX, Constants.MOA_ID_CONFIG_NS_URI);
+
+ //ParepUtils.serializeElement(applicationSpecificParams, System.out);
+ Node validatorEnabledNode = XPathAPI.selectSingleNode(applicationSpecificParams, Constants.MOA_ID_CONFIG_PREFIX
+ + ":EnableInfoboxValidator/text()", nameSpaceNode);
+ if (validatorEnabledNode != null) {
+ return BoolUtils.valueOf(validatorEnabledNode.getNodeValue());
+ }
+ return true;
+ } catch (Exception e) {
+ // e.printStackTrace();
+ throw new ConfigurationException("config.02", null);
+ }
+ }
+
+ /**
+ * Delivers a String with the description of the register which is described
+ * through the identification Type of a corporate body of the persondata schema
+ *
+ * @param identificationType
+ * the identification type.
+ * @return the register description.
+ */
+ public static String getRegisterString(String identificationType) {
+ String corporateBase = Constants.URN_PREFIX_BASEID + "+";
+ if (ParepUtils.isEmpty(identificationType) || !identificationType.startsWith(corporateBase)) return null;
+ String register = identificationType.substring(corporateBase.length());
+ if (ParepUtils.isEmpty(register)) return null;
+ if (register.equals("FN") || register.equals("XFN")) return "Firmenbuchnummer";
+ if (register.equals("VR") || register.equals("XZVR") || register.equals("XVR") || register.equals("ZVR")) return "Nummer im Vereinsregister";
+ if (register.equals("ERSB") || register.equals("XERSB")) return "Nummer im Ergänzungsregister für sonstige Betroffene";
+ return null;
+ }
+
+ /**
+ * Hides Stammzahlen in the given element
+ *
+ * @param hideElement The element where Stammzahlen should be replaced.
+ * @param businessApplication For decision whether to calc a bPK or wbPK.
+ * @param target Target for calculating a bPK.
+ * @param registerID Necessary string for calculating a wbPK (example <code>FN+4096i</code>).
+ * @param blank Switch for behaviour.
+ * <code>true</code> if Stammzahlen are blinded. All occurences will be replaced by empty strings.
+ * <code>false</code> calculates (w)bPKs and changes also the <code>pr:Identifivation/pr:Type</code> elements.
+ * @return The element where Stammzahlen are hidden.
+ */
+ public static Element HideStammZahlen(Element hideElement, boolean businessApplication, String target, String registerID, boolean blank)
+ throws BuildException {
+ try {
+ if (hideElement != null) {
+ Element nameSpaceNode = hideElement.getOwnerDocument().createElement("NameSpaceNode");
+ nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, Constants.PD_NS_URI);
+ NodeList identifications = XPathAPI.selectNodeList(hideElement, "descendant-or-self::pr:Identification", nameSpaceNode);
+ for (int i = 0; i < identifications.getLength(); i++) {
+ Element identificationElement = (Element) identifications.item(i);
+ Node idTypeNode = XPathAPI.selectSingleNode(identificationElement, "descendant-or-self::pr:Identification/pr:Type/text()", nameSpaceNode);
+ if (idTypeNode != null && Constants.URN_PREFIX_BASEID.equals(idTypeNode.getNodeValue())) {
+ Node idValueNode = XPathAPI.selectSingleNode(identificationElement, "descendant-or-self::pr:Identification/pr:Value/text()", nameSpaceNode);
+ if (idValueNode == null || ParepUtils.isEmpty(idValueNode.getNodeValue())) {
+ Logger.error("HideStammZahlen: Problem beim Parsen des erhaltenen Elements - Value Element(-Inhalt) von pr:Identification nicht vorhanden.");
+ throw new BuildException("builder.02", null);
+ }
+ if (blank) {
+ idValueNode.setNodeValue("");
+ } else {
+ String idValue = idValueNode.getNodeValue();
+ if (businessApplication) {
+ // wbPK berechnen
+ idTypeNode.setNodeValue(Constants.URN_PREFIX_WBPK + "+" + registerID);
+ String bpkBase64 = new BPKBuilder().buildWBPK(idValueNode.getNodeValue(), registerID);
+ idValueNode.setNodeValue(bpkBase64);
+
+ } else {
+ // bPK berechnen
+ idTypeNode.setNodeValue(Constants.URN_PREFIX_BPK);
+ String bpkBase64 = new BPKBuilder().buildBPK(idValueNode.getNodeValue(), target);
+ idValueNode.setNodeValue(bpkBase64);
+ }
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ throw new BuildException("builder.02", null);
+ }
+ return hideElement;
+ }
+
+ /**
+ * Replaces each substring of string <code>s</code> that matches the given
+ * <code>search</code> string by the given <code>replace</code> string.
+ *
+ * @param s The string where the replacement should take place.
+ * @param search The pattern that should be replaced.
+ * @param replace The string that should replace all each <code>search</code>
+ * string within <code>s</code>.
+ * @return A string where all occurrence of <code>search</code> are
+ * replaced with <code>replace</code>.
+ */
+ public static String replaceAll (String s, String search, String replace) {
+ if (replace==null) replace = "";
+ return StringUtils.replaceAll(s, search, replace);
+ }
+
+
+// public static void main(String[] args) throws Exception {
+// Document mandate = readDocFromIs(new FileInputStream("c:/Doku/work/Organwalter/schemas/Vertretung_OW_Max_Mustermann.xml"));
+// Document mandate = readDocFromIs(new FileInputStream("c:/mandator.xml"));
+// Document mandate = readDocFromIs(new FileInputStream("c:/vertetervollmacht_1.2.40.0.10.3.1.xml"));
+// Element mandatorElement = extractMandator(mandate.getDocumentElement());
+// System.out.println(extractMandatorName(mandatorElement));
+// System.out.println(extractMandatorDateOfBirth(mandatorElement));
+// System.out.println(extractMandatorWbpk(mandatorElement));
+// //serializeElement(mandatorElement, System.out);
+// serializeElement((extractPrPersonOfMandate(mandate.getDocumentElement())), System.out);
+// }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClientException.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClientException.java
new file mode 100644
index 000000000..85c213169
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClientException.java
@@ -0,0 +1,88 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw;
+
+/**
+ * This class implements the basic exception type for the SZR-gateway client
+ *
+ * @author <a href="mailto:peter.danner@egiz.gv.at">Peter Danner</a>
+ */
+public class SZRGWClientException extends Exception {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 26538259471017714L;
+
+/*
+ * see super constructor.
+ */
+ public SZRGWClientException() {
+ super();
+ }
+
+ /*
+ * see super constructor.
+ */
+ public SZRGWClientException(String arg0) {
+ super(arg0);
+ }
+
+ /*
+ * see super construction.
+ */
+ public SZRGWClientException(Throwable arg0) {
+ super(arg0);
+ }
+
+ /*
+ * see super constructor
+ */
+ public SZRGWClientException(String arg0, Throwable arg1) {
+ super(arg0, arg1);
+ }
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWSecureSocketFactory.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWSecureSocketFactory.java
new file mode 100644
index 000000000..22b575489
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWSecureSocketFactory.java
@@ -0,0 +1,170 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+import javax.net.ssl.SSLSocketFactory;
+
+import org.apache.commons.httpclient.params.HttpConnectionParams;
+import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
+
+/**
+ * This class implements a secure protocol socket factory
+ * for the Apache HTTP client.
+ *
+ * @author <a href="mailto:peter.danner@egiz.gv.at">Peter Danner</a>
+ */
+public class SZRGWSecureSocketFactory implements SecureProtocolSocketFactory {
+
+ /**
+ * The SSL socket factory.
+ */
+ private SSLSocketFactory factory;
+
+ /**
+ * Creates a new Secure socket factory for the
+ * Apache HTTP client.
+ *
+ * @param factory the SSL socket factory to use.
+ */
+ public SZRGWSecureSocketFactory(SSLSocketFactory factory) {
+ this.factory = factory;
+ }
+
+
+ /**
+ * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
+ */
+ public Socket createSocket(
+ String host,
+ int port,
+ InetAddress clientHost,
+ int clientPort)
+ throws IOException, UnknownHostException {
+
+ return this.factory.createSocket(
+ host,
+ port,
+ clientHost,
+ clientPort
+ );
+ }
+
+ /**
+ * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
+ */
+ public Socket createSocket(String host, int port)
+ throws IOException, UnknownHostException {
+ return this.factory.createSocket(
+ host,
+ port
+ );
+ }
+
+ /**
+ * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
+ */
+ public Socket createSocket(
+ Socket socket,
+ String host,
+ int port,
+ boolean autoClose)
+ throws IOException, UnknownHostException {
+ return this.factory.createSocket(
+ socket,
+ host,
+ port,
+ autoClose
+ );
+ }
+
+ /**
+ * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int,org.apache.commons.httpclient.params.HttpConnectionParams)
+ */
+ public Socket createSocket(
+ String host,
+ int port,
+ InetAddress clientHost,
+ int clientPort,
+ HttpConnectionParams params)
+ throws IOException, UnknownHostException, org.apache.commons.httpclient.ConnectTimeoutException {
+
+ Socket socket = createSocket(host, port, clientHost, clientPort);
+ if (socket != null) {
+ // socket.setKeepAlive(false);
+ if (params.getReceiveBufferSize() >= 0)
+ socket.setReceiveBufferSize(params.getReceiveBufferSize());
+ if (params.getSendBufferSize() >= 0)
+ socket.setSendBufferSize(params.getSendBufferSize());
+ socket.setReuseAddress(true);
+ if (params.getSoTimeout() >= 0)
+ socket.setSoTimeout(params.getSoTimeout());
+ }
+ return socket;
+
+ }
+
+ /**
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ public boolean equals(Object obj) {
+ return ((obj != null) && obj.getClass().equals(SZRGWSecureSocketFactory.class));
+ }
+
+ /**
+ * @see java.lang.Object#hashCode()
+ */
+ public int hashCode() {
+ return SZRGWSecureSocketFactory.class.hashCode();
+ }
+
+}
+
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/CitizenCardServletUtils.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/CitizenCardServletUtils.java
new file mode 100644
index 000000000..276d6a105
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/CitizenCardServletUtils.java
@@ -0,0 +1,171 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+/**
+ *
+ */
+package at.gv.egovernment.moa.id.util;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.URLEncoder;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+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.MOAIDException;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * @author <a href="mailto:peter.danner@egiz.gv.at">Peter Danner</a>
+ *
+ */
+public class CitizenCardServletUtils extends ServletUtils{
+
+ /**
+ * Writes out whether the CreateXMLSignatureRequest or a Redirect for form input processing
+ * 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 writeCreateXMLSignatureRequestOrRedirect(HttpServletResponse resp, AuthenticationSession session, String createXMLSignatureRequestOrRedirect, String servletGoal, String servletName)
+ throws MOAIDException,
+ IOException
+ {
+ if (!createXMLSignatureRequestOrRedirect.startsWith("Redirect")) {
+ resp.setStatus(307);
+ String dataURL = new DataURLBuilder().buildDataURL(
+ session.getAuthURL(), MOAIDAuthConstants.REQ_VERIFY_AUTH_BLOCK, session.getSessionID());
+ resp.addHeader("Location", dataURL);
+
+ //TODO test impact of explicit setting charset with older versions of BKUs (HotSign)
+ resp.setContentType("text/xml;charset=UTF-8");
+
+ OutputStream out = resp.getOutputStream();
+ out.write(createXMLSignatureRequestOrRedirect.getBytes("UTF-8"));
+ out.flush();
+ out.close();
+ Logger.debug("Finished POST " + servletName);
+
+ } else {
+ String redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), servletGoal, session.getSessionID());
+ resp.setContentType("text/html");
+ resp.setStatus(302);
+ resp.addHeader("Location", redirectURL);
+ Logger.debug("REDIRECT TO: " + redirectURL);
+
+ }
+ }
+ /**
+ * Writes out whether the CreateXMLSignatureRequest or a Redirect for form input processing
+ * depending on the requests starting text.
+ *
+ * @param resp The httpServletResponse
+ * @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, String createXMLSignatureRequestOrRedirect, String servletGoal, String servletName, String dataURL)
+ throws MOAIDException,
+ IOException
+ {
+ resp.setStatus(307);
+ resp.addHeader("Location", dataURL);
+
+ //TODO test impact of explicit setting charset with older versions of BKUs (HotSign)
+ resp.setContentType("text/xml;charset=UTF-8");
+
+ OutputStream out = resp.getOutputStream();
+ out.write(createXMLSignatureRequestOrRedirect.getBytes("UTF-8"));
+ out.flush();
+ out.close();
+ Logger.debug("Finished POST " + servletName);
+
+ }
+
+ /**
+ * Writes out whether the CreateXMLSignatureRequest or a Redirect for form input processing
+ * 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 writeCreateXMLSignatureRequestURLEncoded(HttpServletResponse resp, AuthenticationSession session, String createXMLSignatureRequestOrRedirect, String servletGoal, String servletName, String dataURL)
+ throws MOAIDException,
+ IOException {
+ resp.setStatus(200);
+ Logger.debug("ContentType set to: application/x-www-form-urlencoded");
+
+ resp.setContentType("application/x-www-form-urlencoded");
+
+ String content = "XMLRequest=" + URLEncoder.encode(createXMLSignatureRequestOrRedirect, "UTF-8") + "&" +
+ "DataURL=" + URLEncoder.encode(dataURL, "UTF-8");
+
+ OutputStream out = resp.getOutputStream();
+ out.write(content.getBytes("UTF-8"));
+ out.flush();
+ out.close();
+ Logger.debug("Finished POST " + servletName);
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSessionId.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSessionId.java
new file mode 100644
index 000000000..69b546f78
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSessionId.java
@@ -0,0 +1,68 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.util.client.mis.simple;
+
+public class MISSessionId {
+
+ private String sessiondId = null;
+ private String redirectURL = null;
+
+ public String getSessiondId() {
+ return sessiondId;
+ }
+ public void setSessiondId(String sessiondId) {
+ this.sessiondId = sessiondId;
+ }
+ public String getRedirectURL() {
+ return redirectURL;
+ }
+ public void setRedirectURL(String redirectURL) {
+ this.redirectURL = redirectURL;
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java
new file mode 100644
index 000000000..e346c8bee
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java
@@ -0,0 +1,359 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.util.client.mis.simple;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.net.ssl.SSLSocketFactory;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.TransformerException;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.httpclient.HostConfiguration;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
+import org.apache.commons.httpclient.protocol.Protocol;
+import org.apache.xpath.XPathAPI;
+import org.w3c.dom.DOMException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+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.id.data.MISMandate;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.StringUtils;
+
+
+public class MISSimpleClient {
+
+
+ private final static String SOAP_NS = "http://schemas.xmlsoap.org/soap/envelope/";
+ private final static String MIS_NS = "http://reference.e-government.gv.at/namespace/mandates/mis/1.0/xsd";
+
+ private static Element NS_NODE = null;
+
+
+ static {
+ try {
+ NS_NODE = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument().createElement("test");
+ NS_NODE.setAttribute("xmlns:soap", SOAP_NS);
+ NS_NODE.setAttribute("xmlns:mis", MIS_NS);
+ } catch (Exception e) {
+ Logger.warn("Error initializing namespace node.", e);
+ }
+ }
+
+ public static List<MISMandate> sendGetMandatesRequest(String webServiceURL, String sessionId, SSLSocketFactory sSLSocketFactory) throws MISSimpleClientException {
+ if (webServiceURL == null) {
+ throw new NullPointerException("Argument webServiceURL must not be null.");
+ }
+ if (sessionId == null) {
+ throw new NullPointerException("Argument sessionId must not be null.");
+ }
+
+ // ssl settings
+ if (sSLSocketFactory != null) {
+ SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory);
+ Protocol.registerProtocol("https", new Protocol("https", fac, 443));
+ }
+
+
+ try {
+ Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
+ Element mirElement = doc.createElementNS(MIS_NS, "MandateIssueRequest");
+ Element sessionIdElement = doc.createElementNS(MIS_NS, "SessionID");
+ sessionIdElement.appendChild(doc.createTextNode(sessionId));
+ mirElement.appendChild(sessionIdElement);
+
+ // send soap request
+ Element mandateIssueResponseElement = sendSOAPRequest(webServiceURL, mirElement);
+
+ // check for error
+ checkForError(mandateIssueResponseElement);
+
+ // check for session id
+ NodeList mandateElements = XPathAPI.selectNodeList(mandateIssueResponseElement, "//mis:MandateIssueResponse/mis:Mandates/mis:Mandate", NS_NODE);
+
+ if (mandateElements == null || mandateElements.getLength() == 0) {
+ throw new MISSimpleClientException("No mandates found in response.");
+ }
+
+ ArrayList<MISMandate> foundMandates = new ArrayList<MISMandate>();
+ for (int i=0; i<mandateElements.getLength(); i++) {
+ Element mandate = (Element) mandateElements.item(i);
+
+ MISMandate misMandate = new MISMandate();
+ if (mandate.hasAttribute("ProfessionalRepresentative")) {
+// System.out.println("OID: " + mandate.getAttribute("ProfessionalRepresentative"));
+ misMandate.setProfRep(mandate.getAttribute("ProfessionalRepresentative"));
+ }
+ if (mandate.hasAttribute("OWbPK")) {
+ misMandate.setOWbPK(mandate.getAttribute("OWbPK"));
+// System.out.println("OWBPK: " + mandate.getAttribute("OWbPK"));
+ }
+
+ //misMandate.setMandate(Base64.decodeBase64(DOMUtils.getText(mandate)));
+ misMandate.setMandate(Base64.decodeBase64(DOMUtils.getText(mandate).getBytes()));
+ misMandate.setFullMandateIncluded(true);
+
+ foundMandates.add(misMandate);
+ }
+ return foundMandates;
+ } catch (ParserConfigurationException e) {
+ throw new MISSimpleClientException("service.06", e);
+ } catch (DOMException e) {
+ throw new MISSimpleClientException("service.06", e);
+ } catch (TransformerException e) {
+ throw new MISSimpleClientException("service.06", e);
+ }
+ }
+
+ public static MISSessionId sendSessionIdRequest(String webServiceURL, byte[] idl, byte[] cert, String oaFriendlyName, String redirectURL, String referenceValue, List<String> mandateIdentifier, String targetType, byte[] authBlock, SSLSocketFactory sSLSocketFactory) throws MISSimpleClientException {
+ if (webServiceURL == null) {
+ throw new MISSimpleClientException("service.04");
+ }
+ if (idl == null) {
+ throw new NullPointerException("Argument idl must not be null.");
+ }
+ if (redirectURL == null) {
+ throw new NullPointerException("Argument redirectURL must not be null.");
+ }
+
+ // ssl settings
+ if (sSLSocketFactory != null) {
+ SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory);
+ Protocol.registerProtocol("https", new Protocol("https", fac, 443));
+ }
+
+ try {
+ Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
+ Element mirElement = doc.createElementNS(MIS_NS, "MandateIssueRequest");
+ Element idlElement = doc.createElementNS(MIS_NS, "IdentityLink");
+
+
+ idlElement.appendChild(doc.createTextNode(new String(Base64.encodeBase64(idl))));
+ mirElement.appendChild(idlElement);
+
+ if (cert != null && cert.length > 0) {
+ Element certElement = doc.createElementNS(MIS_NS, "X509SignatureCertificate");
+ certElement.appendChild(doc.createTextNode(new String(Base64.encodeBase64(cert))));
+ //certElement.appendChild(doc.createTextNode(Base64.encodeBase64(cert)));
+ // certElement.appendChild(doc.createTextNode(new String(Base64.encodeBase64(cert))));
+ mirElement.appendChild(certElement);
+ }
+
+ if (!StringUtils.isEmpty(oaFriendlyName)) {
+ Element oaFriendlyNameElement = doc.createElementNS(MIS_NS, "OAFriendlyName");
+ oaFriendlyNameElement.appendChild(doc.createTextNode(oaFriendlyName));
+ mirElement.appendChild(oaFriendlyNameElement);
+ }
+
+ Element redirectElement = doc.createElementNS(MIS_NS, "RedirectURL");
+ redirectElement.appendChild(doc.createTextNode(redirectURL));
+ mirElement.appendChild(redirectElement);
+
+ Element referenceValueElement = doc.createElementNS(MIS_NS, "ReferenceValue");
+ referenceValueElement.appendChild(doc.createTextNode(referenceValue));
+ mirElement.appendChild(referenceValueElement);
+
+ if (mandateIdentifier != null && mandateIdentifier.size() > 0) {
+ Element filtersElement = doc.createElementNS(MIS_NS, "Filters");
+ Element mandateIdentifiersElement = doc.createElementNS(MIS_NS, "MandateIdentifiers");
+ for (int i=0; i<mandateIdentifier.size(); i++) {
+ Element mandateIdentifierElement = doc.createElementNS(MIS_NS, "MandateIdentifier");
+ mandateIdentifierElement.appendChild(doc.createTextNode(mandateIdentifier.get(i)));
+ mandateIdentifiersElement.appendChild(mandateIdentifierElement);
+ }
+ filtersElement.appendChild(mandateIdentifiersElement);
+ mirElement.appendChild(filtersElement);
+ }
+
+ //add Target element
+ Element targetElement = doc.createElementNS(MIS_NS, "Target");
+ Element targetTypeElement = doc.createElementNS(MIS_NS, "Type");
+ targetTypeElement.appendChild(doc.createTextNode(targetType));
+ targetElement.appendChild(targetTypeElement);
+ mirElement.appendChild(targetElement);
+
+ //add AuthBlock element
+ Element authBlockElement = doc.createElementNS(MIS_NS, "authBlock");
+ authBlockElement.appendChild(doc.createTextNode(new String(Base64.encodeBase64(authBlock))));
+ mirElement.appendChild(authBlockElement);
+
+ // send soap request
+ Element mandateIssueResponseElement = sendSOAPRequest(webServiceURL, mirElement);
+
+ // check for error
+ checkForError(mandateIssueResponseElement);
+
+ // check for session id
+ //String sessionId = ((Node) XPathAPI.selectSingleNode(mandateIssueResponseElement, "/mis:MandateIssueResponse/mis:SessionID/text()", NS_NODE)).getNodeValue();
+ Node sessionIdNode = ((Node) XPathAPI.selectSingleNode(mandateIssueResponseElement, "//mis:MandateIssueResponse/mis:SessionID/text()", NS_NODE));
+ if (sessionIdNode == null) {
+ throw new MISSimpleClientException("SessionId not found in response.");
+ }
+ String sessionId = sessionIdNode.getNodeValue();
+
+ Node guiRedirectURLNode = ((Node) XPathAPI.selectSingleNode(mandateIssueResponseElement, "//mis:MandateIssueResponse/mis:GuiRedirectURL/text()", NS_NODE));
+ if (guiRedirectURLNode == null) {
+ throw new MISSimpleClientException("GuiRedirectURL not found in response.");
+ }
+ String guiRedirectURL = guiRedirectURLNode.getNodeValue();
+
+ // create return object
+ MISSessionId msid = new MISSessionId();
+ msid.setSessiondId(sessionId);
+ msid.setRedirectURL(guiRedirectURL);
+
+ return msid;
+ } catch (ParserConfigurationException e) {
+ throw new MISSimpleClientException("service.06", e);
+ } catch (DOMException e) {
+ throw new MISSimpleClientException("service.06", e);
+ } catch (TransformerException e) {
+ throw new MISSimpleClientException("service.06", e);
+ }
+
+ }
+
+ private static void checkForError(Element mandateIssueResponseElement) throws MISSimpleClientException {
+ if (mandateIssueResponseElement == null) {
+ throw new NullPointerException("Argument mandateIssueResponseElement must not be null.");
+ }
+ try {
+ Element errorElement = (Element) XPathAPI.selectSingleNode(mandateIssueResponseElement, "//mis:MandateIssueResponse/mis:Error", NS_NODE);
+ if (errorElement != null) {
+ String code = ((Node) XPathAPI.selectSingleNode(mandateIssueResponseElement, "//mis:MandateIssueResponse/mis:Error/mis:Code/text()", NS_NODE)).getNodeValue();
+ String text = ((Node) XPathAPI.selectSingleNode(mandateIssueResponseElement, "//mis:MandateIssueResponse/mis:Error/mis:Text/text()", NS_NODE)).getNodeValue();
+ throw new MISSimpleClientException("service.05", code, text); }
+
+ } catch (TransformerException e) {
+ throw new MISSimpleClientException("auth.15", e);
+ }
+ }
+
+ private static Element sendSOAPRequest(String webServiceURL, Element request) throws MISSimpleClientException {
+
+// try {
+// System.out.println("REQUEST-MIS: \n" + DOMUtils.serializeNode(request));
+// } catch (TransformerException e1) {
+// e1.printStackTrace();
+// } catch (IOException e1) {
+// e1.printStackTrace();
+// }
+
+ if (webServiceURL == null) {
+ throw new NullPointerException("Argument webServiceURL must not be null.");
+ }
+ if (request == null) {
+ throw new NullPointerException("Argument request must not be null.");
+ }
+ try {
+ HttpClient httpclient = HttpClientWithProxySupport.getHttpClient();
+ PostMethod post = new PostMethod(webServiceURL);
+ StringRequestEntity re = new StringRequestEntity(DOMUtils.serializeNode(packIntoSOAP(request)),"text/xml", "UTF-8");
+ post.setRequestEntity(re);
+ int responseCode = httpclient.executeMethod(post);
+
+ if (responseCode != 200) {
+ throw new MISSimpleClientException("Invalid HTTP response code " + responseCode);
+ }
+ //Element elem = parse(post.getResponseBodyAsStream());
+ Document doc = DOMUtils.parseDocumentSimple(post.getResponseBodyAsStream());
+ return unpackFromSOAP(doc.getDocumentElement());
+
+ } catch(IOException e) {
+ throw new MISSimpleClientException("service.04", e);
+
+ } catch (TransformerException e) {
+ throw new MISSimpleClientException("service.06", e);
+
+ } catch (SAXException e) {
+ throw new MISSimpleClientException("service.06", e);
+
+ } catch (ParserConfigurationException e) {
+ throw new MISSimpleClientException("service.06", e);
+
+ } catch (Exception e) {
+ throw new MISSimpleClientException("service.06", e);
+
+ }
+
+ }
+
+ private static Element packIntoSOAP(Element element) throws MISSimpleClientException {
+ try {
+ Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
+ Element soapEnvelope = doc.createElement("Envelope");
+ soapEnvelope.setAttribute("xmlns", SOAP_NS);
+ Element soapBody = doc.createElement("Body");
+ soapEnvelope.appendChild(soapBody);
+ soapBody.appendChild(doc.importNode(element, true));
+ return soapEnvelope;
+ } catch(ParserConfigurationException e) {
+ throw new MISSimpleClientException("service.06", e);
+ }
+ }
+
+ private static Element unpackFromSOAP(Element element) throws MISSimpleClientException {
+ try {
+ return (Element) XPathAPI.selectSingleNode(element, "/soap:Envelope/soap:Body/child::*[position()=1]", NS_NODE);
+ } catch(TransformerException e) {
+ throw new MISSimpleClientException("service.06", e);
+ }
+ }
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.auth.modules.AuthModule b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.auth.modules.AuthModule
new file mode 100644
index 000000000..865096055
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.auth.modules.AuthModule
@@ -0,0 +1,2 @@
+# The default moaid process
+at.gv.egovernment.moa.id.auth.modules.internal.DefaultAuthModuleImpl
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml
new file mode 100644
index 000000000..6bbaf6ece
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<pd:ProcessDefinition id="DefaultAuthentication" xmlns:pd="http://reference.e-government.gv.at/namespace/moa/process/definition/v1">
+
+<!--
+ - National authentication with Austrian Citizen Card and mobile signature with our without mandate.
+ - Legacy authentication for foreign citizens using MOCCA supported signature cards.
+-->
+ <pd:Task id="initializeBKUAuthentication" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.InitializeBKUAuthenticationTask" />
+ <pd:Task id="createIdentityLinkForm" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.CreateIdentityLinkFormTask" />
+ <pd:Task id="verifyIdentityLink" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyIdentityLinkTask" async="true" />
+ <pd:Task id="verifyAuthBlock" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyAuthenticationBlockTask" async="true" />
+ <pd:Task id="verifyCertificate" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyCertificateTask" async="true" />
+ <pd:Task id="getMISMandate" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetMISSessionIDTask" async="true" />
+ <pd:Task id="certificateReadRequest" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.CertificateReadRequestTask" />
+ <pd:Task id="prepareAuthBlockSignature" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.PrepareAuthBlockSignatureTask" />
+ <pd:Task id="prepareGetMISMandate" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.PrepareGetMISMandateTask" />
+ <pd:Task id="finalizeAuthentication" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.FinalizeAuthenticationTask" />
+ <pd:Task id="getForeignID" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetForeignIDTask" async="true" />
+
+ <!-- Process is triggered either by GenerateIFrameTemplateServlet (upon bku selection) or by AuthenticationManager (upon legacy authentication start using legacy parameters. -->
+ <pd:StartEvent id="start" />
+
+ <pd:Transition from="start" to="initializeBKUAuthentication" />
+
+ <pd:Transition from="initializeBKUAuthentication" to="createIdentityLinkForm" />
+
+ <pd:Transition from="createIdentityLinkForm" to="verifyIdentityLink" />
+
+ <pd:Transition from="verifyIdentityLink" to="certificateReadRequest" conditionExpression="!ctx['identityLinkAvailable'] || ctx['useMandate']" />
+ <pd:Transition from="verifyIdentityLink" to="prepareAuthBlockSignature" />
+
+ <pd:Transition from="prepareAuthBlockSignature" to="verifyAuthBlock" />
+ <!-- Note: verifyAuthBlock still creates a MIS session and redirects the user to the MIS gui. This should be separated from the auth block verification. -->
+
+ <pd:Transition from="certificateReadRequest" to="verifyCertificate" />
+ <!-- Note: verifyCertificate still creates the auth block to be signed which should be separated from certificat verification. -->
+
+ <pd:Transition from="verifyCertificate" to="verifyAuthBlock" conditionExpression="ctx['useMandate']" />
+ <pd:Transition from="verifyCertificate" to="getForeignID" />
+
+ <pd:Transition from="verifyAuthBlock" to="prepareGetMISMandate" conditionExpression="ctx['useMandate']" />
+ <pd:Transition from="verifyAuthBlock" to="finalizeAuthentication" />
+
+ <pd:Transition from="prepareGetMISMandate" to="getMISMandate" />
+
+ <pd:Transition from="getMISMandate" to="finalizeAuthentication" />
+ <pd:Transition from="getForeignID" to="finalizeAuthentication" />
+
+ <pd:Transition from="finalizeAuthentication" to="end" />
+
+ <pd:EndEvent id="end" />
+
+</pd:ProcessDefinition>
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/AllTests.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/AllTests.java
new file mode 100644
index 000000000..d0d104d69
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/AllTests.java
@@ -0,0 +1,79 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ *******************************************************************************/
+///*
+// * Copyright 2003 Federal Chancellery Austria
+// * MOA-ID has been developed in a cooperation between BRZ, the Federal
+// * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+// *
+// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+// * the European Commission - subsequent versions of the EUPL (the "Licence");
+// * You may not use this work except in compliance with the Licence.
+// * You may obtain a copy of the Licence at:
+// * http://www.osor.eu/eupl/
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the Licence is distributed on an "AS IS" basis,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the Licence for the specific language governing permissions and
+// * limitations under the Licence.
+// *
+// * This product combines work with different licenses. See the "NOTICE" text
+// * file for details on the various modules and licenses.
+// * The "NOTICE" text file is part of the distribution. Any derivative works
+// * that you distribute must include a readable copy of the "NOTICE" text file.
+// */
+//
+//
+//package test.at.gv.egovernment.moa.id.auth.builder;
+//
+//import junit.awtui.TestRunner;
+//import junit.framework.Test;
+//import junit.framework.TestSuite;
+//
+///**
+// * @author patrick
+// * @version $Id$
+// */
+//public class AllTests {
+//
+// public static Test suite() {
+// TestSuite suite = new TestSuite();
+//
+//// suite.addTestSuite(AuthenticationBlockAssertionBuilderTest.class);
+// suite.addTestSuite(CreateXMLSignatureBuilderTest.class);
+//// suite.addTestSuite(GetIdentityLinkFormBuilderTest.class);
+//// suite.addTestSuite(InfoboxReadRequestBuilderTest.class);
+//// suite.addTestSuite(PersonDataBuilderTest.class);
+//// suite.addTestSuite(SAMLArtifactBuilderTest.class);
+//
+// return suite;
+// }
+//
+// public static void main(String[] args) {
+// try {
+// TestRunner.run(AllTests.class);
+// } catch (Exception e) {
+// e.printStackTrace();
+// }
+// }
+//}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilderTest.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilderTest.java
new file mode 100644
index 000000000..4c2b3ec8a
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilderTest.java
@@ -0,0 +1,93 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ *******************************************************************************/
+///*
+// * Copyright 2003 Federal Chancellery Austria
+// * MOA-ID has been developed in a cooperation between BRZ, the Federal
+// * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+// *
+// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+// * the European Commission - subsequent versions of the EUPL (the "Licence");
+// * You may not use this work except in compliance with the Licence.
+// * You may obtain a copy of the Licence at:
+// * http://www.osor.eu/eupl/
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the Licence is distributed on an "AS IS" basis,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the Licence for the specific language governing permissions and
+// * limitations under the Licence.
+// *
+// * This product combines work with different licenses. See the "NOTICE" text
+// * file for details on the various modules and licenses.
+// * The "NOTICE" text file is part of the distribution. Any derivative works
+// * that you distribute must include a readable copy of the "NOTICE" text file.
+// */
+//
+//
+//package test.at.gv.egovernment.moa.id.auth.builder;
+//
+//import test.at.gv.egovernment.moa.id.UnitTestCase;
+//
+//import at.gv.egovernment.moa.id.auth.builder.AuthenticationBlockAssertionBuilder;
+//
+///**
+// * @author Paul Ivancsics
+// * @version $Id$
+// */
+//public class AuthenticationBlockAssertionBuilderTest extends UnitTestCase {
+// private static final String nl = "\n";
+// private static final String ISSUER = "Hugo Mustermann";
+// private static final String ISSUE_INSTANT = "2003-03-15T22:50:21+01:00";
+// private static final String AUTH_URL = "https://auth.moa.gv.at/";
+// private static final String TARGET = "Grundbuch";
+// private static final String OA_URL = "https://grundbuch.gv.at/";
+// private static final String GEB_DAT = "2004-01-02";
+//
+// // wird auch von CreateXMLSignatureBuilderTest verwendet !
+// public static final String ASSERTION_SHOULD =
+//"<saml:Assertion xmlns:saml='urn:oasis:names:tc:SAML:1.0:assertion' MajorVersion='1' MinorVersion='0' AssertionID='any' Issuer='" + ISSUER + "' IssueInstant='" + ISSUE_INSTANT + "'>" + nl +
+//" <saml:AttributeStatement>" + nl +
+//" <saml:Subject>" + nl +
+//" <saml:NameIdentifier>" + AUTH_URL + "</saml:NameIdentifier>" + nl +
+//" </saml:Subject>" + nl +
+//" <saml:Attribute AttributeName='Gesch�ftsbereich' AttributeNamespace='http://reference.e-government.gv.at/namespace/moa/20020822#'>" + nl +
+//" <saml:AttributeValue>" + TARGET + "</saml:AttributeValue>" + nl +
+//" </saml:Attribute>" + nl +
+//" <saml:Attribute AttributeName='OA' AttributeNamespace='http://reference.e-government.gv.at/namespace/moa/20020822#'>" + nl +
+//" <saml:AttributeValue>" + OA_URL + "</saml:AttributeValue>" + nl +
+//" </saml:Attribute>" + nl +
+//" </saml:AttributeStatement>" + nl +
+//"</saml:Assertion>";
+//
+// public AuthenticationBlockAssertionBuilderTest(String name) {
+// super(name);
+// }
+//
+// public void testBuild() throws Exception {
+// AuthenticationBlockAssertionBuilder builder = new AuthenticationBlockAssertionBuilder();
+// String assertionBuilt = builder.buildAuthBlock(ISSUER, ISSUE_INSTANT, AUTH_URL, TARGET, null, "", "", OA_URL, GEB_DAT, null, null);
+// assertionBuilt = XML_DECL + assertionBuilt;
+// String assertionShould = XML_DECL + ASSERTION_SHOULD;
+// assertXmlEquals(assertionShould, assertionBuilt);
+// }
+//}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureBuilderTest.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureBuilderTest.java
new file mode 100644
index 000000000..c133602b1
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureBuilderTest.java
@@ -0,0 +1,151 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ *******************************************************************************/
+///*
+// * Copyright 2003 Federal Chancellery Austria
+// * MOA-ID has been developed in a cooperation between BRZ, the Federal
+// * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+// *
+// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+// * the European Commission - subsequent versions of the EUPL (the "Licence");
+// * You may not use this work except in compliance with the Licence.
+// * You may obtain a copy of the Licence at:
+// * http://www.osor.eu/eupl/
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the Licence is distributed on an "AS IS" basis,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the Licence for the specific language governing permissions and
+// * limitations under the Licence.
+// *
+// * This product combines work with different licenses. See the "NOTICE" text
+// * file for details on the various modules and licenses.
+// * The "NOTICE" text file is part of the distribution. Any derivative works
+// * that you distribute must include a readable copy of the "NOTICE" text file.
+// */
+//
+//
+//package test.at.gv.egovernment.moa.id.auth.builder;
+//
+//import at.gv.egovernment.moa.id.auth.builder.CreateXMLSignatureRequestBuilder;
+//
+//import test.at.gv.egovernment.moa.id.UnitTestCase;
+//
+///**
+// * @author Paul Ivancsics
+// * @version $Id$
+// */
+//public class CreateXMLSignatureBuilderTest extends UnitTestCase {
+// private static final String nl = "\n";
+// public static final String TRANSFORMS_INFO =
+// " <sl10:TransformsInfo>" + nl +
+// " <dsig:Transforms>" + nl +
+// " <dsig:Transform Algorithm='http://www.w3.org/2000/09/xmldsig#enveloped-signature'/>" + nl +
+// " <dsig:Transform Algorithm='http://www.w3.org/TR/1999/REC-xslt-19991116'>" + nl +
+//"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:saml='urn:oasis:names:tc:SAML:1.0:assertion' >" + nl +
+//"<xsl:template match='/'>" + nl +
+//"<html>" + nl +
+//"<body>" + nl +
+//"</body>" + nl +
+//"</html>" + nl +
+//"</xsl:template>" + nl +
+//"</xsl:stylesheet>" + nl +
+// " </dsig:Transform>" + nl +
+// " </dsig:Transforms>" + nl +
+// " <sl10:FinalDataMetaInfo>" + nl +
+// " <sl10:MimeType>text/html</sl10:MimeType>" + nl +
+// " </sl10:FinalDataMetaInfo>" + nl +
+// " </sl10:TransformsInfo>" + nl;
+// public static final String REQUEST_SHOULD =
+//"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + nl +
+//"<sl11:CreateXMLSignatureRequest xmlns:dsig=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:sl10=\"http://www.buergerkarte.at/namespaces/securitylayer/20020225#\" xmlns:sl11=\"http://www.buergerkarte.at/namespaces/securitylayer/20020831#\">" + nl +
+//" <sl11:KeyboxIdentifier>SecureSignatureKeypair</sl11:KeyboxIdentifier>" + nl +
+//" <sl11:DataObjectInfo Structure=\"detached\">" + nl +
+//" <sl10:DataObject Reference=\"\"/>" + nl +
+//TRANSFORMS_INFO +
+//" </sl11:DataObjectInfo>" + nl +
+//" <sl11:SignatureInfo>" + nl +
+//" <sl11:SignatureEnvironment>" + nl +
+//" <sl10:XMLContent>" + AuthenticationBlockAssertionBuilderTest.ASSERTION_SHOULD + "</sl10:XMLContent>" + nl +
+//" </sl11:SignatureEnvironment>" + nl +
+//" <sl11:SignatureLocation Index=\"2\">/saml:Assertion</sl11:SignatureLocation>" + nl +
+//" </sl11:SignatureInfo>" + nl +
+//"</sl11:CreateXMLSignatureRequest>";
+//
+//
+// public static final String TRANSFORMS_INFO_SL12 =
+// " <sl:TransformsInfo>" + nl +
+// " <dsig:Transforms>" + nl +
+// " <dsig:Transform Algorithm='http://www.w3.org/2000/09/xmldsig#enveloped-signature'/>" + nl +
+// " <dsig:Transform Algorithm='http://www.w3.org/TR/1999/REC-xslt-19991116'>" + nl +
+//"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:saml='urn:oasis:names:tc:SAML:1.0:assertion' >" + nl +
+//"<xsl:template match='/'>" + nl +
+//"<html>" + nl +
+//"<body>" + nl +
+//"</body>" + nl +
+//"</html>" + nl +
+//"</xsl:template>" + nl +
+//"</xsl:stylesheet>" + nl +
+// " </dsig:Transform>" + nl +
+// " </dsig:Transforms>" + nl +
+// " <sl:FinalDataMetaInfo>" + nl +
+// " <sl:MimeType>text/html</sl:MimeType>" + nl +
+// " </sl:FinalDataMetaInfo>" + nl +
+// " </sl:TransformsInfo>" + nl;
+// public static final String REQUEST_SHOULD_SL12 =
+//"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + nl +
+//"<sl:CreateXMLSignatureRequest xmlns:dsig=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:sl=\"http://www.buergerkarte.at/namespaces/securitylayer/1.2#\">" + nl +
+//" <sl:KeyboxIdentifier>SecureSignatureKeypair</sl:KeyboxIdentifier>" + nl +
+//" <sl:DataObjectInfo Structure=\"detached\">" + nl +
+//" <sl:DataObject Reference=\"\"/>" + nl +
+//TRANSFORMS_INFO_SL12 +
+//" </sl:DataObjectInfo>" + nl +
+//" <sl:SignatureInfo>" + nl +
+//" <sl:SignatureEnvironment>" + nl +
+//" <sl:XMLContent>" + AuthenticationBlockAssertionBuilderTest.ASSERTION_SHOULD + "</sl:XMLContent>" + nl +
+//" </sl:SignatureEnvironment>" + nl +
+//" <sl:SignatureLocation Index=\"2\">/saml:Assertion</sl:SignatureLocation>" + nl +
+//" </sl:SignatureInfo>" + nl +
+//"</sl:CreateXMLSignatureRequest>";
+//
+//
+//
+//
+// public CreateXMLSignatureBuilderTest(String name) {
+// super(name);
+// }
+//
+// public void testBuild() throws Exception {
+// // test build for Security Layer version 1.1 and 1.0
+// String request = new CreateXMLSignatureRequestBuilder().build(
+// AuthenticationBlockAssertionBuilderTest.ASSERTION_SHOULD, "SecureSignatureKeypair",
+// new String[] {TRANSFORMS_INFO},
+// false);
+// assertXmlEquals(REQUEST_SHOULD, request);
+// // test build for Security Layer version 1.2
+// String requestSL12 = new CreateXMLSignatureRequestBuilder().build(
+// AuthenticationBlockAssertionBuilderTest.ASSERTION_SHOULD, "SecureSignatureKeypair",
+// new String[] {TRANSFORMS_INFO},
+// true);
+// assertXmlEquals(REQUEST_SHOULD_SL12, requestSL12);
+// }
+//}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilderTest.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilderTest.java
new file mode 100644
index 000000000..7b364789b
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilderTest.java
@@ -0,0 +1,119 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package test.at.gv.egovernment.moa.id.auth.builder;
+
+import java.text.MessageFormat;
+
+import junit.framework.TestCase;
+
+import at.gv.egovernment.moa.id.auth.builder.CertInfoVerifyXMLSignatureRequestBuilder;
+import at.gv.egovernment.moa.id.auth.builder.GetIdentityLinkFormBuilder;
+import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilder;
+
+/**
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class GetIdentityLinkFormBuilderTest extends TestCase {
+ private static String nl = "\n";
+ public static String FORM =
+ "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" + nl +
+ "<html>" + nl +
+ "<head>" + nl +
+ "<title>Auslesen der Personenbindung</title>" + nl +
+ "</head>" + nl +
+ "<body>" + nl +
+ "<form name=\"GetIdentityLinkForm\"" + nl +
+ " action=\"{0}\"" + nl +
+ " method=\"post\">" + nl +
+ " <input type=\"hidden\" " + nl +
+ " name=\"XMLRequest\"" + nl +
+ " value=\"{1}\"/>" + nl +
+ " <input type=\"hidden\" " + nl +
+ " name=\"DataURL\"" + nl +
+ " value=\"{2}\"/>" + nl +
+ " <input type=\"submit\" value=\"Auslesen der Personenbindung\"/>" + nl +
+ "</form>" + nl +
+ "<form name=\"CertificateInfoForm\"" + nl +
+ " action=\"{0}\"" + nl +
+ " method=\"post\">" + nl +
+ " <input type=\"hidden\" " + nl +
+ " name=\"XMLRequest\"" + nl +
+ " value=\"{3}\"/>" + nl +
+ " <input type=\"hidden\" " + nl +
+ " name=\"DataURL\"" + nl +
+ " value=\"{4}\"/>" + nl +
+ " <input type=\"submit\" value=\"Information zu Wurzelzertifikaten\"/>" + nl +
+ "</form>" + nl +
+ "</body>" + nl +
+ "</html>";
+ public static String BKU =
+ "http://localhost:3495/http-security-layer-request";
+
+ public void testBuild() throws Exception {
+ String xmlRequest = new InfoboxReadRequestBuilder().build(false, null);
+ String dataURL = "https://1.2.3.4/auth/VerifyIdentityLink?MOASessionID=1234567";
+ String infoRequest = new CertInfoVerifyXMLSignatureRequestBuilder().build();
+ String infoDataURL = "https://1.2.3.4/auth/StartAuthentication?Target=gb&OA=https://oa.gv.at/";
+ String form = new GetIdentityLinkFormBuilder().build(null, null, xmlRequest, dataURL, infoRequest, infoDataURL, null, null, null, null);
+ String formShould = MessageFormat.format(
+ FORM, new Object[] { BKU, xmlRequest, dataURL, infoRequest, infoDataURL });
+ assertEquals(formShould, form);
+ }
+ public void testBuildCustomBKU() throws Exception {
+ String xmlRequest = new InfoboxReadRequestBuilder().build(false, null);
+ String dataURL = "https://1.2.3.4/auth/AuthServlet/StartAuthentication?MOASessionID=1234567";
+ String infoRequest = new CertInfoVerifyXMLSignatureRequestBuilder().build();
+ String infoDataURL = "https://1.2.3.4/auth/StartAuthentication?Target=gb&OA=https://oa.gv.at/";
+ String bkuURL = "http://bku.at/";
+ String form = new GetIdentityLinkFormBuilder().build(null, bkuURL, xmlRequest, dataURL, infoRequest, infoDataURL, null, null, null, null);
+ String formShould = MessageFormat.format(
+ FORM, new Object[] { bkuURL, xmlRequest, dataURL, infoRequest, infoDataURL });
+ assertEquals(formShould, form);
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderTest.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderTest.java
new file mode 100644
index 000000000..ec15a209c
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderTest.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package test.at.gv.egovernment.moa.id.auth.builder;
+
+import org.w3c.dom.Document;
+import test.at.gv.egovernment.moa.id.UnitTestCase;
+
+import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilder;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+
+/**
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class InfoboxReadRequestBuilderTest extends UnitTestCase implements Constants {
+
+ public InfoboxReadRequestBuilderTest(String name) {
+ super(name);
+ }
+
+ public void testBuild() throws Exception {
+ InfoboxReadRequestBuilder builder = new InfoboxReadRequestBuilder();
+ String xmlBuilt = builder.build(false, null);
+ Document docBuilt = DOMUtils.parseDocument(xmlBuilt, false, ALL_SCHEMA_LOCATIONS, null);
+ String xmlBuiltSerialized = DOMUtils.serializeNode(docBuilt);
+ // xmlShould was generated by Hot:Sign Tester
+ String xmlShould = "<?xml version='1.0' encoding='utf-8'?><sl10:InfoboxReadRequest xmlns:sl10='http://www.buergerkarte.at/namespaces/securitylayer/20020225#'><sl10:InfoboxIdentifier>IdentityLink</sl10:InfoboxIdentifier><sl10:BinaryFileParameters ContentIsXMLEntity='true'/></sl10:InfoboxReadRequest>";
+ assertXmlEquals(xmlShould, xmlBuiltSerialized);
+ }
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilderTest.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilderTest.java
new file mode 100644
index 000000000..b26fd4738
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilderTest.java
@@ -0,0 +1,97 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package test.at.gv.egovernment.moa.id.auth.builder;
+
+import at.gv.egovernment.moa.id.auth.builder.PersonDataBuilder;
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.parser.InfoboxReadResponseParser;
+import at.gv.egovernment.moa.util.Constants;
+
+import test.at.gv.egovernment.moa.id.UnitTestCase;
+
+/**
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class PersonDataBuilderTest extends UnitTestCase implements Constants {
+
+ /**
+ * Constructor for PersonDataBuilderTest.
+ */
+ public PersonDataBuilderTest(String arg) {
+ super(arg);
+ }
+ public void testBuild() throws Exception {
+ String xmlInfoboxReadResponse = readFile("data/test/xmldata/testperson1/InfoboxReadResponse.xml");
+ IdentityLink il = new InfoboxReadResponseParser(xmlInfoboxReadResponse).parseIdentityLink();
+ String xmlPersonData = new PersonDataBuilder().build(il, true);
+ String xmlPersonDataShould = "<pr:Person xsi:type=\"pr:PhysicalPersonType\"><pr:Identification><pr:Value>123456789012</pr:Value><pr:Type>http://reference.e-government.gv.at/names/persondata/20020228#zmr-zahl</pr:Type></pr:Identification><pr:Name><pr:GivenName>Hermann</pr:GivenName><pr:FamilyName primary=\"undefined\">Muster</pr:FamilyName></pr:Name><pr:DateOfBirth>1968-10-22</pr:DateOfBirth></pr:Person>";
+ assertPersonDataEquals(xmlPersonDataShould, xmlPersonData);
+ }
+ public void testBuildNoZMRZahl() throws Exception {
+ String xmlInfoboxReadResponse = readFile("data/test/xmldata/testperson1/InfoboxReadResponse.xml");
+ IdentityLink il = new InfoboxReadResponseParser(xmlInfoboxReadResponse).parseIdentityLink();
+ String xmlPersonData = new PersonDataBuilder().build(il, false);
+ String xmlPersonDataShould = XML_DECL + "<pr:Person xsi:type=\"pr:PhysicalPersonType\"><pr:Name><pr:GivenName>Hermann</pr:GivenName><pr:FamilyName primary=\"undefined\">Muster</pr:FamilyName></pr:Name><pr:DateOfBirth>1968-10-22</pr:DateOfBirth></pr:Person>";
+ assertPersonDataEquals(xmlPersonDataShould, xmlPersonData);
+ }
+ private void assertPersonDataEquals(String s1, String s2) throws Exception {
+ String ss1 = insertPrNS(s1);
+ String ss2 = insertPrNS(s2);
+ assertXmlEquals(ss1, ss2);
+ }
+ private String insertPrNS(String xmlPersonData) {
+ int startNS = xmlPersonData.indexOf("Person") + "Person".length() + 1;
+ String s =
+ xmlPersonData.substring(0, startNS) +
+ "xmlns:pr=\"" + PD_NS_URI + "\" " +
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
+ xmlPersonData.substring(startNS);
+ return s;
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/AllTests.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/AllTests.java
new file mode 100644
index 000000000..d293ff347
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/AllTests.java
@@ -0,0 +1,75 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ *******************************************************************************/
+///*
+// * Copyright 2003 Federal Chancellery Austria
+// * MOA-ID has been developed in a cooperation between BRZ, the Federal
+// * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+// *
+// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+// * the European Commission - subsequent versions of the EUPL (the "Licence");
+// * You may not use this work except in compliance with the Licence.
+// * You may obtain a copy of the Licence at:
+// * http://www.osor.eu/eupl/
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the Licence is distributed on an "AS IS" basis,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the Licence for the specific language governing permissions and
+// * limitations under the Licence.
+// *
+// * This product combines work with different licenses. See the "NOTICE" text
+// * file for details on the various modules and licenses.
+// * The "NOTICE" text file is part of the distribution. Any derivative works
+// * that you distribute must include a readable copy of the "NOTICE" text file.
+// */
+//
+//
+//package test.at.gv.egovernment.moa.id.auth.parser;
+//
+//import junit.awtui.TestRunner;
+//import junit.framework.Test;
+//import junit.framework.TestSuite;
+//
+///**
+// * @author Paul Ivancsics
+// * @version $Id$
+// */
+//public class AllTests {
+//
+// public static Test suite() {
+// TestSuite suite = new TestSuite();
+//
+// suite.addTestSuite(IdentityLinkAssertionParserTest.class);
+// suite.addTestSuite(SAMLArtifactParserTest.class);
+//
+// return suite;
+// }
+//
+// public static void main(String[] args) {
+// try {
+// TestRunner.run(AllTests.class);
+// } catch (Exception e) {
+// e.printStackTrace();
+// }
+// }
+//}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParserTest.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParserTest.java
new file mode 100644
index 000000000..977764878
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParserTest.java
@@ -0,0 +1,179 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package test.at.gv.egovernment.moa.id.auth.parser;
+
+import iaik.security.rsa.RSAPublicKey;
+
+import java.io.FileOutputStream;
+import java.io.RandomAccessFile;
+import java.security.PublicKey;
+
+import org.w3c.dom.Document;
+
+import test.at.gv.egovernment.moa.id.UnitTestCase;
+import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser;
+import at.gv.egovernment.moa.id.auth.parser.InfoboxReadResponseParser;
+import at.gv.egovernment.moa.id.util.ECDSAKeyValueConverter;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+
+/**
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class IdentityLinkAssertionParserTest extends UnitTestCase {
+
+ IdentityLinkAssertionParser ilap;
+
+ public IdentityLinkAssertionParserTest(String name) {
+ super(name);
+ }
+
+ public void setUp() {
+ try {
+ RandomAccessFile s =
+ new RandomAccessFile(
+ "data/test/xmldata/testperson1/InfoboxReadResponse.xml",
+ "r");
+ byte[] b = new byte[(int) s.length()];
+ s.read(b);
+ String xmlInfoboxReadResponse = new String(b, "UTF-8");
+
+ InfoboxReadResponseParser irrp = new InfoboxReadResponseParser(xmlInfoboxReadResponse);
+ ilap = new IdentityLinkAssertionParser(irrp.parseSAMLAssertion());
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+// public void testParseIdentityLink() throws Exception {
+// IdentityLink idl = ilap.parseIdentityLink();
+// System.out.println(idl.getGivenName());
+// System.out.println(idl.getFamilyName());
+// System.out.println(idl.getDateOfBirth());
+// System.out.println(idl.getIdentificationValue());
+//
+// VerifyXMLSignatureRequestBuilder vx = new VerifyXMLSignatureRequestBuilder();
+//
+// // Element zur�ck bekommen: vx.build(idl.getSamlAssertion());
+//
+// IdentityLinkValidator idVali = IdentityLinkValidator.getInstance();
+// idVali.validate(idl);
+//
+// }
+
+// public void testParseIdentityLinkECC() throws Exception {
+// RandomAccessFile s =
+// new RandomAccessFile(
+// "data/test/xmldata/IL.ResponseToRequest.01.ECDSA.xml",
+// "r");
+// byte[] b = new byte[(int) s.length()];
+// s.read(b);
+// String xmlInfoboxReadResponse = new String(b);
+// InfoboxReadResponseParser irrp = new InfoboxReadResponseParser(xmlInfoboxReadResponse);
+// String SAML = irrp.parseSAMLAssertion();
+// ilap = new IdentityLinkAssertionParser(SAML);
+// IdentityLink idl = ilap.parseIdentityLink();
+// System.out.println(idl.getGivenName());
+// System.out.println(idl.getFamilyName());
+// System.out.println(idl.getDateOfBirth());
+// System.out.println(idl.getIdentificationValue());
+//
+// VerifyXMLSignatureRequestBuilder vx = new VerifyXMLSignatureRequestBuilder();
+//
+// // Element zur�ck bekommen: vx.build(idl.getSamlAssertion());
+//
+// IdentityLinkValidator idVali = IdentityLinkValidator.getInstance();
+// idVali.validate(idl);
+//
+// }
+
+ public void testRSAPublicKeys() throws Exception {
+ if (ilap.getPublicKeys()[0].getClass().getName().equals("iaik.security.rsa.RSAPublicKey"))
+ {
+
+ for (int i = 0; i < ilap.getPublicKeys().length; i++) {
+ RSAPublicKey result = (RSAPublicKey)ilap.getPublicKeys()[i];
+ System.out.println("RSA Public Key No" + i);
+ System.out.println("Modulus: " + result.getModulus());
+ System.out.println("Exponent: " + result.getPublicExponent());
+ }
+
+ }
+ }
+
+ public void testECDSAPublicKeys() throws Exception {
+
+ RandomAccessFile s =
+ new RandomAccessFile(
+ "data/test/xmldata/ECDSAKeyExample.xml",
+ "r");
+ byte[] b = new byte[(int) s.length()];
+ s.read(b);
+ String ecdsaKey = new String(b, "UTF-8");
+ Document e = DOMUtils.parseDocument(ecdsaKey,true,Constants.ALL_SCHEMA_LOCATIONS, null);
+ PublicKey p = ECDSAKeyValueConverter.element2ECDSAPublicKey(e.getDocumentElement());
+
+ }
+
+
+ public void testDsigCertificates() throws Exception {
+
+ String[] result = ilap.getCertificates();
+ for (int i = 0; i < result.length; i++) {
+
+ System.out.println("DSIG Certificate Length: " + result[i].length() + " No" + i + "\n" + result[i]);
+ FileOutputStream raf = new FileOutputStream("data/test/certs/cert" + i + ".cer");
+ raf.write(result[i].getBytes());
+ raf.flush();
+ raf.close();
+ }
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParserTest.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParserTest.java
new file mode 100644
index 000000000..8d7dee597
--- /dev/null
+++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParserTest.java
@@ -0,0 +1,113 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package test.at.gv.egovernment.moa.id.auth.parser;
+
+import java.io.RandomAccessFile;
+
+import test.at.gv.egovernment.moa.id.UnitTestCase;
+
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser;
+import at.gv.egovernment.moa.id.auth.parser.InfoboxReadResponseParser;
+
+/**
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class InfoboxReadResponseParserTest extends UnitTestCase {
+
+ IdentityLinkAssertionParser ilap;
+
+ public InfoboxReadResponseParserTest(String name) {
+ super(name);
+ }
+
+ public void setUp() {
+ }
+
+ public void testParseInfoboxReadResponse() throws Exception {
+ RandomAccessFile s =
+ new RandomAccessFile(
+ "data/test/xmldata/testperson1/InfoboxReadResponse.xml",
+ "r");
+ byte[] b = new byte[(int) s.length()];
+ s.read(b);
+ String xmlInfoboxReadResponse = new String(b, "UTF-8");
+
+ InfoboxReadResponseParser irrp = new InfoboxReadResponseParser(xmlInfoboxReadResponse);
+ ilap = new IdentityLinkAssertionParser(irrp.parseSAMLAssertion());
+
+ IdentityLink idl = ilap.parseIdentityLink();
+ System.out.println(idl.getGivenName());
+ System.out.println(idl.getFamilyName());
+ System.out.println(idl.getDateOfBirth());
+ System.out.println(idl.getIdentificationValue());
+
+ }
+
+ public void testParseInfoboxReadResponseError() throws Exception {
+ RandomAccessFile s =
+ new RandomAccessFile(
+ "data/test/xmldata/ErrorResponse.xml",
+ "r");
+ byte[] b = new byte[(int) s.length()];
+ s.read(b);
+ String xmlInfoboxReadResponse = new String(b, "UTF-8");
+
+ InfoboxReadResponseParser irrp = new InfoboxReadResponseParser(xmlInfoboxReadResponse);
+ ilap = new IdentityLinkAssertionParser(irrp.parseSAMLAssertion());
+
+ IdentityLink idl = ilap.parseIdentityLink();
+ System.out.println(idl.getGivenName());
+ System.out.println(idl.getFamilyName());
+ System.out.println(idl.getDateOfBirth());
+ System.out.println(idl.getIdentificationValue());
+
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-module-openID/pom.xml b/id/server/modules/moa-id-module-openID/pom.xml
new file mode 100644
index 000000000..2a953bcab
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/pom.xml
@@ -0,0 +1,86 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>MOA.id.server.modules</groupId>
+ <artifactId>moa-id-modules</artifactId>
+ <version>${moa-id-version}</version>
+ </parent>
+
+ <groupId>MOA.id.server.modules</groupId>
+ <artifactId>moa-id-module-openID</artifactId>
+ <version>${moa-id-version}</version>
+ <packaging>jar</packaging>
+
+ <name>MOA ID-Module OpenID Connect</name>
+
+ <properties>
+ <repositoryPath>${basedir}/../../../../repository</repositoryPath>
+ </properties>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>${junit.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.http-client</groupId>
+ <artifactId>google-http-client-jackson2</artifactId>
+ <version>1.19.0</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.oauth-client</groupId>
+ <artifactId>google-oauth-client-jetty</artifactId>
+ <version>1.19.0</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>org.mortbay.jetty</groupId>
+ <artifactId>servlet-api</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>com.googlecode.jsontoken</groupId>
+ <artifactId>jsontoken</artifactId>
+ <version>1.1</version>
+ <exclusions>
+ <exclusion>
+ <groupId>javax.servlet</groupId>
+ <artifactId>servlet-api</artifactId>
+ </exclusion>
+ <exclusion>
+ <artifactId>google-collections</artifactId>
+ <groupId>com.google.collections</groupId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ <version>18.0</version>
+ </dependency>
+
+ <!-- TestNG -->
+ <dependency>
+ <groupId>org.testng</groupId>
+ <artifactId>testng</artifactId>
+ <version>6.1.1</version>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+</project> \ No newline at end of file
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java
new file mode 100644
index 000000000..e2ac97535
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * 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.oauth20;
+
+import java.util.Properties;
+
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.util.FileUtils;
+
+public class OAuth20Configuration {
+
+ private static OAuth20Configuration instance;
+
+ public static OAuth20Configuration getInstance() {
+ if (instance == null) {
+ instance = new OAuth20Configuration();
+ }
+ return instance;
+ }
+
+ public static final String JWT_KEYSTORE = "jwt.ks.file";
+ public static final String JWT_KEYSTORE_PASSWORD = "jwt.ks.password";
+ public static final String JWT_KEY_NAME = "jwt.ks.key.name";
+ public static final String JWT_KEY_PASSWORD = "jwt.ks.key.password";
+
+ private Properties props;
+ private String rootDir = null;
+
+ private OAuth20Configuration() {
+ try {
+ props = AuthConfigurationProviderFactory.getInstance().getGeneralOAuth20ProperiesConfig();
+ rootDir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir();
+ }
+ catch (ConfigurationException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public String getJWTKeyStore() {
+ return FileUtils.makeAbsoluteURL(props.getProperty(JWT_KEYSTORE), rootDir);
+ }
+
+ public String getJWTKeyStorePassword() {
+ return props.getProperty(JWT_KEYSTORE_PASSWORD).trim();
+ }
+
+ public String getJWTKeyName() {
+ return props.getProperty(JWT_KEY_NAME).trim();
+ }
+
+ public String getJWTKeyPassword() {
+ return props.getProperty(JWT_KEY_PASSWORD).trim();
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java
new file mode 100644
index 000000000..b0736ff2e
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * 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.oauth20;
+
+public final class OAuth20Constants {
+
+ private OAuth20Constants() {
+ throw new InstantiationError();
+ }
+
+ public static final String ERRORPAGE = "moa_errorcodes.html";
+
+ // error parameters and error codes
+ public static final String PARAM_ERROR = "error";
+ public static final String PARAM_ERROR_DESCRIPTION = "error_description";
+ public static final String PARAM_ERROR_URI = "error_uri";
+
+ public static final String ERROR_INVALID_REQUEST = "invalid_request";
+ public static final String ERROR_UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type";
+ public static final String ERROR_INVALID_CLIENT = "invalid_client";
+ public static final String ERROR_ACCESS_DENIED = "access_denied";
+ public static final String ERROR_SERVER_ERROR = "server_error";
+ public static final String ERROR_INVALID_GRANT = "invalid_grant";
+ public static final String ERROR_UNAUTHORIZED_CLIENT = "unauthorized_client";
+
+ // request parameters
+ //public static final String PARAM_OA_URL = "oaURL";
+ public static final String PARAM_RESPONSE_TYPE = "response_type";
+ public static final String PARAM_REDIRECT_URI = "redirect_uri";
+ public static final String PARAM_STATE = "state";
+ public static final String PARAM_NONCE = "nonce";
+ public static final String PARAM_GRANT_TYPE = "grant_type";
+ public static final String PARAM_GRANT_TYPE_VALUE_AUTHORIZATION_CODE = "authorization_code";
+ public static final String PARAM_CLIENT_ID = "client_id";
+ public static final String PARAM_CLIENT_SECRET = "client_secret";
+ public static final String PARAM_SCOPE = "scope";
+ public static final String PARAM_MOA_MOD = "mod";
+ public static final String PARAM_MOA_ACTION = "action";
+
+
+ // reponse parameters
+ public static final String RESPONSE_CODE = "code";
+ public static final String RESPONSE_TOKEN = "token";
+ public static final String RESPONSE_ACCESS_TOKEN = "access_token";
+ public static final String RESPONSE_ID_TOKEN = "id_token";
+ public static final String RESPONSE_EXPIRES_IN = "expires_in";
+ public static final String RESPONSE_TOKEN_TYPE = "token_type";
+ public static final String RESPONSE_TOKEN_TYPE_VALUE_BEARER = "Bearer";
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java
new file mode 100644
index 000000000..4a33a44b7
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java
@@ -0,0 +1,74 @@
+/*******************************************************************************
+ * 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.oauth20;
+
+import java.io.Serializable;
+import java.util.Map;
+
+import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
+
+public class OAuth20SessionObject implements Serializable {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ private String scope;
+
+ private String code;
+
+ private Map<String, Object> authDataSession;
+
+ public String getScope() {
+ return scope;
+ }
+
+ public void setScope(String scope) {
+ this.scope = scope;
+ }
+
+ /**
+ * @return the code
+ */
+ public String getCode() {
+ return code;
+ }
+
+ /**
+ * @param code
+ * the code to set
+ */
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ public Map<String, Object> getAuthDataSession() {
+ return authDataSession;
+ }
+
+ public void setAuthDataSession(Map<String, Object> idToken) {
+ this.authDataSession = idToken;
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java
new file mode 100644
index 000000000..912060949
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java
@@ -0,0 +1,111 @@
+/*******************************************************************************
+ * 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.oauth20;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.lang.StringUtils;
+
+import com.google.gson.JsonObject;
+
+public final class OAuth20Util {
+
+ public static final String REGEX_HTTPS = "^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
+ public static final String REGEX_FILE = "^(file):/.[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
+
+ private OAuth20Util() {
+ throw new InstantiationError();
+ }
+
+ /**
+ * Simple helper function to add parameter to a url
+ *
+ * @param url
+ * @param name
+ * @param value
+ * @throws UnsupportedEncodingException
+ */
+ public static void addParameterToURL(final StringBuilder url, final String name, final String value)
+ throws UnsupportedEncodingException {
+ if (url.indexOf("?") < 0) {
+ url.append("?");
+ } else {
+ url.append("&");
+ }
+ // URLEncoder.encode(value, "UTF-8")
+ url.append(name).append("=").append(value);
+ }
+
+ public static boolean isUrl(final String url) {
+ Pattern urlPattern;
+ if (url.startsWith("file")) {
+ urlPattern = Pattern.compile(REGEX_FILE, Pattern.CASE_INSENSITIVE);
+ } else {
+ urlPattern = Pattern.compile(REGEX_HTTPS, Pattern.CASE_INSENSITIVE);
+ }
+
+ Matcher matcher = urlPattern.matcher(url);
+ return matcher.find();
+ }
+
+ public static boolean isValidStateValue(String state) {
+ Pattern urlPattern = Pattern.compile("javascript|<|>|&|;", Pattern.CASE_INSENSITIVE);
+ Matcher matcher = urlPattern.matcher(state);
+ return !matcher.find();
+ }
+
+ public static void addProperytiesToJsonObject(JsonObject jsonObject, Map<String, Object> params) {
+ for (Map.Entry<String, Object> param : params.entrySet()) {
+
+ if (!StringUtils.isEmpty(param.getKey()) && param.getValue() != null) {
+
+ // check for integer
+ try {
+ int i = Integer.parseInt(String.valueOf(param.getValue()));
+ jsonObject.addProperty(param.getKey(), i);
+ continue;
+ }
+ catch (NumberFormatException e) {
+ }
+
+ // check for long
+ try {
+ long l = Long.parseLong(String.valueOf(param.getValue()));
+ jsonObject.addProperty(param.getKey(), l);
+ continue;
+ }
+ catch (NumberFormatException e) {
+ }
+
+ // string
+ if (param.getValue() instanceof String) {
+ jsonObject.addProperty(param.getKey(), String.valueOf(param.getValue()));
+ }
+ }
+ }
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java
new file mode 100644
index 000000000..eb3cfcccb
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java
@@ -0,0 +1,45 @@
+/*******************************************************************************
+ * 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.oauth20;
+
+public class Pair<P1, P2> {
+ private final P1 first;
+ private final P2 second;
+
+ private Pair(final P1 newFirst, final P2 newSecond) {
+ this.first = newFirst;
+ this.second = newSecond;
+ }
+
+ public P1 getFirst() {
+ return this.first;
+ }
+
+ public P2 getSecond() {
+ return this.second;
+ }
+
+ public static <P1, P2> Pair<P1, P2> newInstance(final P1 newFirst, final P2 newSecond) {
+ return new Pair<P1, P2>(newFirst, newSecond);
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java
new file mode 100644
index 000000000..bb180d8e9
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java
@@ -0,0 +1,299 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.lang.StringUtils;
+
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.protocols.oauth20.Pair;
+import at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20AuthRequest;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.BPKAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDAuthBlock;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDCcsURL;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDCitizenQAALevelAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDIdentityLinkBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDIssuingNationAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSTORKTOKEN;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSectorForIDAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSignerCertificate;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSourcePIN;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSourcePINType;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateLegalPersonFullNameAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateLegalPersonSourcePinAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateLegalPersonSourcePinTypeAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateNaturalPersonBPKAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateNaturalPersonBirthDateAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateNaturalPersonFamilyNameAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateNaturalPersonGivenNameAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateNaturalPersonSourcePinAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateNaturalPersonSourcePinTypeAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateProfRepDescAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateProfRepOIDAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateReferenceValueAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateTypeAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+import at.gv.egovernment.moa.logging.Logger;
+
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+
+public final class OAuth20AttributeBuilder {
+
+ private OAuth20AttributeBuilder() {
+ throw new InstantiationError();
+ }
+
+ private static IAttributeGenerator<Pair<String, JsonPrimitive>> generator = new IAttributeGenerator<Pair<String, JsonPrimitive>>() {
+
+ public Pair<String, JsonPrimitive> buildStringAttribute(final String friendlyName, final String name, final String value) {
+ return Pair.newInstance(friendlyName, new JsonPrimitive(value));
+ }
+
+ public Pair<String, JsonPrimitive> buildIntegerAttribute(final String friendlyName, final String name, final int value) {
+ return Pair.newInstance(friendlyName, new JsonPrimitive(value));
+ }
+
+ public Pair<String, JsonPrimitive> buildLongAttribute(final String friendlyName, final String name, final long value) {
+ return Pair.newInstance(friendlyName, new JsonPrimitive(value));
+ }
+
+ public Pair<String, JsonPrimitive> buildEmptyAttribute(final String friendlyName, final String name) {
+ return Pair.newInstance(friendlyName, new JsonPrimitive(""));
+ }
+
+ };
+
+ private static final List<IAttributeBuilder> buildersOpenId = new ArrayList<IAttributeBuilder>();
+ private static final List<IAttributeBuilder> buildersProfile = new ArrayList<IAttributeBuilder>();
+ private static final List<IAttributeBuilder> buildersEID = new ArrayList<IAttributeBuilder>();
+ private static final List<IAttributeBuilder> buildersEIDGov = new ArrayList<IAttributeBuilder>();
+ private static final List<IAttributeBuilder> buildersMandate = new ArrayList<IAttributeBuilder>();
+ private static final List<IAttributeBuilder> buildersSTORK = new ArrayList<IAttributeBuilder>();
+ static {
+ // openId
+ buildersOpenId.add(new OpenIdIssuerAttribute());
+ buildersOpenId.add(new OpenIdSubjectIdentifierAttribute());
+ buildersOpenId.add(new OpenIdExpirationTimeAttribute());
+ buildersOpenId.add(new OpenIdIssueInstantAttribute());
+ buildersOpenId.add(new OpenIdAuthenticationTimeAttribute());
+ buildersOpenId.add(new OpenIdAudiencesAttribute());
+ buildersOpenId.add(new OpenIdNonceAttribute());
+
+ // profile
+ buildersProfile.add(new ProfileGivenNameAttribute());
+ buildersProfile.add(new ProfileFamilyNameAttribute());
+ buildersProfile.add(new ProfileDateOfBirthAttribute());
+
+ // EID
+ buildersEID.add(new EIDCcsURL());
+ buildersEID.add(new EIDCitizenQAALevelAttributeBuilder());
+ buildersEID.add(new EIDIssuingNationAttributeBuilder());
+ buildersEID.add(new EIDSectorForIDAttributeBuilder());
+ buildersEID.add(new EIDAuthBlock());
+ buildersEID.add(new EIDSignerCertificate());
+ buildersEID.add(new BPKAttributeBuilder());
+
+ // eID_gov
+ buildersEIDGov.add(new EIDSourcePIN());
+ buildersEIDGov.add(new EIDSourcePINType());
+ buildersEIDGov.add(new EIDIdentityLinkBuilder());
+
+ // mandate
+ buildersMandate.add(new MandateTypeAttributeBuilder());
+ buildersMandate.add(new MandateReferenceValueAttributeBuilder());
+
+ buildersMandate.add(new MandateNaturalPersonSourcePinAttributeBuilder());
+ buildersMandate.add(new MandateNaturalPersonSourcePinTypeAttributeBuilder());
+ buildersMandate.add(new MandateNaturalPersonBPKAttributeBuilder());
+ buildersMandate.add(new MandateNaturalPersonFamilyNameAttributeBuilder());
+ buildersMandate.add(new MandateNaturalPersonGivenNameAttributeBuilder());
+ buildersMandate.add(new MandateNaturalPersonBirthDateAttributeBuilder());
+
+ buildersMandate.add(new MandateLegalPersonSourcePinAttributeBuilder());
+ buildersMandate.add(new MandateLegalPersonSourcePinTypeAttributeBuilder());
+ buildersMandate.add(new MandateLegalPersonFullNameAttributeBuilder());
+
+ buildersMandate.add(new MandateProfRepOIDAttributeBuilder());
+ buildersMandate.add(new MandateProfRepDescAttributeBuilder());
+
+ // STORK
+ buildersSTORK.add(new EIDSTORKTOKEN());
+
+ IAttributeBuilder attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.ADOPTEDFAMILYNAME_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.AGE_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.CANONICALRESIDENCEADDRESS_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.CONTRYCODEOFBIRTH_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.FISCALNUMBER_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.GENDER_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.INHERITEDFAMILYNAME_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.ISAGEOVER_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.MARITALSTATUS_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.NATIONALITYCODE_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.PSEUDONYM_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.RESIDENCEPERMIT_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.RESIDENCEADDRESS_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+
+ attr = PVPAttributeBuilder.getAttributeBuilder(STORKConstants.TITLE_NAME);
+ if (attr != null)
+ buildersSTORK.add(attr);
+ }
+
+ private static void addAttibutes(final List<IAttributeBuilder> builders, final JsonObject jsonObject,
+ final OAAuthParameter oaParam, final IAuthData authData, OAuth20AuthRequest oAuthRequest) {
+ for (IAttributeBuilder b : builders) {
+ try {
+ //TODO: better solution requires more refactoring :(
+ Pair<String, JsonPrimitive> attribute = null;
+ if (b instanceof OpenIdNonceAttribute) {
+ OpenIdNonceAttribute nonceBuilder = (OpenIdNonceAttribute) b;
+ attribute = nonceBuilder.build(oaParam, authData, oAuthRequest, generator);
+
+ } else
+ attribute = b.build(oaParam, authData, generator);
+
+ if (attribute != null && !StringUtils.isEmpty(attribute.getSecond().getAsString())) {
+ jsonObject.add(attribute.getFirst(), attribute.getSecond());
+ }
+ }
+ catch (AttributeException e) {
+ Logger.info("Cannot add attribute " + b.getName());
+ }
+ }
+ }
+
+ public static void addScopeOpenId(final JsonObject jsonObject,
+ final OAAuthParameter oaParam, final IAuthData authData,
+ final OAuth20AuthRequest oAuthRequest) {
+ addAttibutes(buildersOpenId, jsonObject, oaParam, authData, oAuthRequest);
+ }
+
+ public static void addScopeProfile(final JsonObject jsonObject,
+ final OAAuthParameter oaParam, final IAuthData authData) {
+ addAttibutes(buildersProfile, jsonObject, oaParam, authData, null);
+ }
+
+ public static void addScopeEID(final JsonObject jsonObject,
+ final OAAuthParameter oaParam, final IAuthData authData) {
+ addAttibutes(buildersEID, jsonObject, oaParam, authData, null);
+ }
+
+ public static void addScopeEIDGov(final JsonObject jsonObject,
+ final OAAuthParameter oaParam, final IAuthData authData) {
+ addAttibutes(buildersEIDGov, jsonObject, oaParam, authData, null);
+ }
+
+ public static void addScopeMandate(final JsonObject jsonObject,
+ final OAAuthParameter oaParam, final IAuthData authData) {
+ addAttibutes(buildersMandate, jsonObject, oaParam, authData, null);
+ }
+
+ public static void addScopeSTORK(final JsonObject jsonObject,
+ final OAAuthParameter oaParam, final IAuthData authData) {
+ addAttibutes(buildersSTORK, jsonObject, oaParam, authData, null);
+ }
+
+ /**
+ * @return the buildersprofile
+ */
+ public static List<IAttributeBuilder> getBuildersprofile() {
+ return buildersProfile;
+ }
+
+ /**
+ * @return the builderseid
+ */
+ public static List<IAttributeBuilder> getBuilderseid() {
+ return buildersEID;
+ }
+
+ /**
+ * @return the builderseidgov
+ */
+ public static List<IAttributeBuilder> getBuilderseidgov() {
+ return buildersEIDGov;
+ }
+
+ /**
+ * @return the buildersmandate
+ */
+ public static List<IAttributeBuilder> getBuildersmandate() {
+ return buildersMandate;
+ }
+
+ /**
+ * @return the buildersstork
+ */
+ public static List<IAttributeBuilder> getBuildersstork() {
+ return buildersSTORK;
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAudiencesAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAudiencesAttribute.java
new file mode 100644
index 000000000..e81132ca7
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAudiencesAttribute.java
@@ -0,0 +1,48 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class OpenIdAudiencesAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "aud";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildStringAttribute(this.getName(), "", oaParam.getPublicURLPrefix());
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
+
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java
new file mode 100644
index 000000000..c4260db82
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class OpenIdAuthenticationTimeAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "auth_time";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildLongAttribute(this.getName(), "", ((long) (authData.getIssueInstant().getTime() / 1000)));
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java
new file mode 100644
index 000000000..6008eede1
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java
@@ -0,0 +1,51 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+import java.util.Date;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class OpenIdExpirationTimeAttribute implements IAttributeBuilder {
+
+ public static final int expirationTime = 5 * 60; // in seconds
+
+ public String getName() {
+ return "exp";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildLongAttribute(this.getName(), "", (long) (new Date().getTime() / 1000 + expirationTime));
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java
new file mode 100644
index 000000000..ad7fe68b9
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+import java.util.Date;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class OpenIdIssueInstantAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "iat";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildLongAttribute(this.getName(), "", (long) (new Date().getTime() / 1000));
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java
new file mode 100644
index 000000000..5c4fe02df
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class OpenIdIssuerAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "iss";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildStringAttribute(this.getName(), "", authData.getIssuer());
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java
new file mode 100644
index 000000000..d2636c259
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.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.oauth20.attributes;
+
+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.protocols.oauth20.protocol.OAuth20AuthRequest;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+import at.gv.egovernment.moa.util.MiscUtil;
+
+public class OpenIdNonceAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "nonce";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildStringAttribute(this.getName(), "", null);
+ }
+
+ public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, OAuth20AuthRequest oAuthRequest,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ if (MiscUtil.isNotEmpty(oAuthRequest.getNonce()))
+ return g.buildStringAttribute(this.getName(), "", oAuthRequest.getNonce());
+ else
+ return null;
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
+
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java
new file mode 100644
index 000000000..10af9cc32
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class OpenIdSubjectIdentifierAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "sub";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildStringAttribute(this.getName(), "", authData.getBPK());
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java
new file mode 100644
index 000000000..4262d6bb3
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class ProfileDateOfBirthAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "birthdate";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildStringAttribute(this.getName(), "", authData.getFormatedDateOfBirth());
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java
new file mode 100644
index 000000000..da4f76e2d
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class ProfileFamilyNameAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "family_name";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildStringAttribute(this.getName(), "", authData.getFamilyName());
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java
new file mode 100644
index 000000000..04a6ec60b
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java
@@ -0,0 +1,47 @@
+/*******************************************************************************
+ * 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.oauth20.attributes;
+
+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.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class ProfileGivenNameAttribute implements IAttributeBuilder {
+
+ public String getName() {
+ return "given_name";
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+ return g.buildStringAttribute(this.getName(), "", authData.getGivenName());
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(this.getName(), "");
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java
new file mode 100644
index 000000000..25a30bfcf
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20AccessDeniedException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20AccessDeniedException() {
+ super(OAuth20Constants.ERROR_ACCESS_DENIED, "oauth20.05", new Object[] {});
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java
new file mode 100644
index 000000000..a938d1544
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20CertificateErrorException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20CertificateErrorException(final String name) {
+ super(OAuth20Constants.ERROR_SERVER_ERROR, "oauth20.09", new Object[] { name });
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java
new file mode 100644
index 000000000..307615fbd
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java
@@ -0,0 +1,71 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.util.MOAIDMessageProvider;
+
+public class OAuth20Exception extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ private String messageId;
+
+ private String errorCode;
+
+ public OAuth20Exception(final String errorCode, final String messageId, final Object[] parameters) {
+ super(MOAIDMessageProvider.getInstance().getMessage(messageId, parameters));
+ this.errorCode = errorCode;
+ this.messageId = messageId;
+ }
+
+ /**
+ * @return the messageId
+ */
+ public String getMessageId() {
+ return messageId;
+ }
+
+ /**
+ * @param messageId
+ * the messageId to set
+ */
+ public void setMessageId(String messageId) {
+ this.messageId = messageId;
+ }
+
+ /**
+ * @return the errorCode
+ */
+ public String getErrorCode() {
+ return errorCode;
+ }
+
+ /**
+ * @param errorCode
+ * the errorCode to set
+ */
+ public void setErrorCode(String errorCode) {
+ this.errorCode = errorCode;
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java
new file mode 100644
index 000000000..9c2875cef
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20InvalidClientException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20InvalidClientException() {
+ super(OAuth20Constants.ERROR_INVALID_CLIENT, "oauth20.05", new Object[] {});
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java
new file mode 100644
index 000000000..c0f03c735
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20InvalidGrantException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20InvalidGrantException() {
+ super(OAuth20Constants.ERROR_INVALID_GRANT, "oauth20.07", new Object[] {});
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java
new file mode 100644
index 000000000..b980840c2
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java
@@ -0,0 +1,35 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20InvalidRequestException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20InvalidRequestException() {
+ super(OAuth20Constants.ERROR_INVALID_REQUEST, "oauth20.04", new Object[] {});
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20OANotSupportedException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20OANotSupportedException.java
new file mode 100644
index 000000000..0edeb89bc
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20OANotSupportedException.java
@@ -0,0 +1,44 @@
+/*
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+/**
+ * @author tlenz
+ *
+ */
+public class OAuth20OANotSupportedException extends OAuth20Exception {
+
+ private static final long serialVersionUID = -8713091674236329339L;
+
+ /**
+ * @param errorCode
+ * @param messageId
+ * @param parameters
+ */
+ public OAuth20OANotSupportedException() {
+ super(OAuth20Constants.ERROR_SERVER_ERROR, "oauth20.06", new Object[] {});
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java
new file mode 100644
index 000000000..8de854821
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20ResponseTypeException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20ResponseTypeException() {
+ super(OAuth20Constants.ERROR_UNSUPPORTED_RESPONSE_TYPE, "oauth20.03", new Object[] {});
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java
new file mode 100644
index 000000000..470507f08
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20ServerErrorException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20ServerErrorException() {
+ super(OAuth20Constants.ERROR_SERVER_ERROR, "oauth20.10", new Object[] {});
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java
new file mode 100644
index 000000000..ee7b4d7d6
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20UnauthorizedClientException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20UnauthorizedClientException() {
+ super(OAuth20Constants.ERROR_UNAUTHORIZED_CLIENT, "oauth20.08", new Object[] {});
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java
new file mode 100644
index 000000000..48267d88c
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java
@@ -0,0 +1,34 @@
+/*******************************************************************************
+ * 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.oauth20.exceptions;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+
+public class OAuth20WrongParameterException extends OAuth20Exception {
+ private static final long serialVersionUID = 1L;
+
+ public OAuth20WrongParameterException(final String name) {
+ super(OAuth20Constants.ERROR_INVALID_REQUEST, "oauth20.02", new Object[] { name });
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java
new file mode 100644
index 000000000..50e57bdc1
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java
@@ -0,0 +1,121 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/**
+ * Copyright 2010 Google Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the License
+ * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
+ * or implied. See the License for the specific language governing permissions and limitations under
+ * the License.
+ *
+ */
+package at.gv.egovernment.moa.id.protocols.oauth20.json;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivateKey;
+import java.security.Signature;
+import java.security.SignatureException;
+
+import net.oauth.jsontoken.crypto.AbstractSigner;
+import net.oauth.jsontoken.crypto.RsaSHA256Signer;
+import net.oauth.jsontoken.crypto.SignatureAlgorithm;
+
+/**
+ * Signer that can sign byte arrays using a {@link PrivateKey} and SHA-256. <br/>
+ * This is something like a copy of the {@link RsaSHA256Signer}.
+ *
+ */
+public class OAuth20SHA256Signer extends AbstractSigner implements OAuthSigner {
+
+ private final Signature signature;
+ private final PrivateKey signingKey;
+ private final OAuthSignatureAlgorithm algorithm;
+
+ /**
+ * Public constructor.
+ *
+ * @param issuer
+ * The id of this signer, to be included in the JSON Token's envelope.
+ * @param keyId
+ * The id of the key used by this signer, to be included in the JSON Token's
+ * envelope.
+ * @param key
+ * the private key to be used for signing.
+ * @throws InvalidKeyException
+ * if the key is unsuitable for RSA signing.
+ */
+ public OAuth20SHA256Signer(final String issuer, final String keyId, final PrivateKey key) throws InvalidKeyException {
+ super(issuer, keyId);
+
+ this.signingKey = key;
+ this.algorithm = OAuth20SignatureUtil.findSignature(key);
+
+ try {
+ this.signature = this.algorithm.getSignatureInstance();
+ this.signature.initSign(signingKey);
+ }
+ catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("Cannot get algorithm for the given private key", e);
+ }
+ catch (NoSuchProviderException e) {
+ throw new IllegalStateException("Cannot get algorithm for the given private key", e);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see net.oauth.jsontoken.crypto.Signer#getSignatureAlgorithm()
+ */
+ public SignatureAlgorithm getSignatureAlgorithm() {
+ // it is fine to return RS256 because we overwrite the JsonToken for the algorithm name. But
+ // we need the internal SHA256 which is used.
+ return SignatureAlgorithm.RS256;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see net.oauth.jsontoken.crypto.Signer#sign(byte[])
+ */
+ public byte[] sign(byte[] source) throws SignatureException {
+ try {
+ signature.initSign(signingKey);
+ }
+ catch (InvalidKeyException e) {
+ throw new RuntimeException("key somehow became invalid since calling the constructor");
+ }
+ signature.update(source);
+ return signature.sign();
+ }
+
+ public OAuthSignatureAlgorithm getOAuthSignatureAlgorithm() {
+ return this.algorithm;
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java
new file mode 100644
index 000000000..374320a5a
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java
@@ -0,0 +1,84 @@
+/*******************************************************************************
+ * 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.oauth20.json;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PublicKey;
+import java.security.Signature;
+import java.security.SignatureException;
+
+import net.oauth.jsontoken.crypto.RsaSHA256Verifier;
+import net.oauth.jsontoken.crypto.Verifier;
+
+/**
+ * A verifier that can verify signatures on byte arrays using a {@link PublicKey} and SHA-256. <br/>
+ * This is something like a copy of the {@link RsaSHA256Verifier}.
+ */
+public class OAuth20SHA256Verifier implements Verifier {
+
+ private final PublicKey verificationKey;
+ private final Signature signer;
+
+ /**
+ * Public Constructor.
+ *
+ * @param verificationKey
+ * the key used to verify the signature.
+ */
+ public OAuth20SHA256Verifier(final PublicKey verificationKey) {
+ this.verificationKey = verificationKey;
+
+ try {
+ this.signer = OAuth20SignatureUtil.findSignature(verificationKey).getSignatureInstance();
+ this.signer.initVerify(verificationKey);
+ }
+ catch (InvalidKeyException e) {
+ throw new IllegalStateException("key is invalid", e);
+ }
+ catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("Cannot get algorithm for the given private key", e);
+ }
+ catch (NoSuchProviderException e) {
+ throw new IllegalStateException("Cannot get algorithm for the given private key", e);
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see net.oauth.jsontoken.crypto.Verifier#verifySignature(byte[], byte[])
+ */
+ public void verifySignature(byte[] source, byte[] signature) throws SignatureException {
+ try {
+ signer.initVerify(verificationKey);
+ }
+ catch (InvalidKeyException e) {
+ throw new RuntimeException("key someone become invalid since calling the constructor");
+ }
+ signer.update(source);
+ if (!signer.verify(signature)) {
+ throw new SignatureException("signature did not verify");
+ }
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java
new file mode 100644
index 000000000..9f20ee956
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java
@@ -0,0 +1,116 @@
+/*******************************************************************************
+ * 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.oauth20.json;
+
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+import java.security.interfaces.ECPrivateKey;
+import java.security.interfaces.ECPublicKey;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+
+import org.apache.commons.lang.StringUtils;
+import org.opensaml.xml.security.x509.BasicX509Credential;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Configuration;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20CertificateErrorException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.KeyStoreUtils;
+
+public final class OAuth20SignatureUtil {
+
+ private OAuth20SignatureUtil() {
+ throw new InstantiationError();
+ }
+
+ static OAuthSignatureAlgorithm findSignature(final PrivateKey key) {
+ Logger.debug("OAuth - Looking for signature for key " + key.getClass());
+ if (key instanceof RSAPrivateKey) {
+ Logger.debug("OAuth - going to uses SHA256withRSA signature");
+ return OAuthSignatureAlgorithm.RS256;
+ } else if (key instanceof ECPrivateKey) {
+ Logger.debug("OAuth - going to uses SHA256withECDSA signature");
+ return OAuthSignatureAlgorithm.ECDSA256;
+ } else if (key instanceof iaik.security.ecc.ecdsa.ECPrivateKey) {
+ Logger.debug("OAuth - going to uses SHA256withECDSA signature with iaik");
+ return OAuthSignatureAlgorithm.ECDSA256_IAKIK;
+ } else {
+ throw new IllegalStateException("Cannot find an alorithm for the given private key");
+ }
+ }
+
+ static OAuthSignatureAlgorithm findSignature(final PublicKey key) {
+ if (key instanceof RSAPublicKey) {
+ Logger.debug("OAuth - going to uses SHA256withRSA signature");
+ return OAuthSignatureAlgorithm.RS256;
+ } else if (key instanceof ECPublicKey) {
+ Logger.debug("OAuth - going to uses SHA256withECDSA signature");
+ return OAuthSignatureAlgorithm.ECDSA256;
+ } else if (key instanceof iaik.security.ecc.ecdsa.ECPublicKey) {
+ Logger.debug("OAuth - going to uses SHA256withECDSA signature with iaik");
+ return OAuthSignatureAlgorithm.ECDSA256_IAKIK;
+ } else {
+ throw new IllegalStateException("Cannot find an alorithm for the given private key");
+ }
+ }
+
+ public static OAuthSigner loadSigner(String issuer) throws OAuth20Exception {
+ OAuth20Configuration globalConfig = OAuth20Configuration.getInstance();
+
+ if (StringUtils.isEmpty(globalConfig.getJWTKeyStore())) {
+ throw new OAuth20CertificateErrorException("keystore");
+ }
+
+ if (StringUtils.isEmpty(globalConfig.getJWTKeyName())) {
+ throw new OAuth20CertificateErrorException("key name");
+ }
+
+ try {
+ KeyStore ks = KeyStoreUtils.loadKeyStore(globalConfig.getJWTKeyStore(), globalConfig.getJWTKeyStorePassword());
+
+ X509Certificate certificate = (X509Certificate) ks.getCertificate(globalConfig.getJWTKeyName());
+
+ PrivateKey privateKey = (PrivateKey) ks.getKey(globalConfig.getJWTKeyName(), globalConfig.getJWTKeyPassword()
+ .toCharArray());
+ BasicX509Credential credential = new BasicX509Credential();
+ credential.setEntityCertificate(certificate);
+ credential.setPrivateKey(privateKey);
+
+ // Logger.debug("Going to use X509Certificate:");
+ // Logger.debug(certificate);
+ // Logger.debug("Going to use private key:");
+ // Logger.debug(privateKey);
+
+ return new OAuth20SHA256Signer(issuer, globalConfig.getJWTKeyName(), credential.getPrivateKey());
+
+ }
+ catch (Exception e) {
+ Logger.error(e.getMessage(), e);
+ throw new OAuth20CertificateErrorException("keystore");
+ }
+
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java
new file mode 100644
index 000000000..af17825fd
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.oauth20.json;
+
+import net.oauth.jsontoken.JsonToken;
+
+import com.google.gson.JsonObject;
+
+public class OAuthJsonToken extends JsonToken {
+
+ private final OAuthSigner signer;
+
+ public OAuthJsonToken(OAuthSigner signer) {
+ super(signer);
+ this.signer = signer;
+ }
+
+ @Override
+ public JsonObject getHeader() {
+ JsonObject header = new JsonObject();
+ header.addProperty(ALGORITHM_HEADER, signer.getOAuthSignatureAlgorithm().getAlgorithm());
+ String keyId = getKeyId();
+ if (keyId != null) {
+ header.addProperty(KEY_ID_HEADER, keyId);
+ }
+ return header;
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java
new file mode 100644
index 000000000..db15516e7
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java
@@ -0,0 +1,63 @@
+package at.gv.egovernment.moa.id.protocols.oauth20.json;
+
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Signature;
+
+import org.apache.commons.lang.StringUtils;
+
+/**
+ * Enum of the signature algorithms supported by this package.
+ */
+public enum OAuthSignatureAlgorithm {
+ ECDSA256("SHA256withECDSA", "ECDSA256", null), RS256("SHA256withRSA", "RS256", null), ECDSA256_IAKIK("SHA1withECDSA", "ECDSA256",
+ "IAIK_ECC");
+
+ private final String signatureName;
+ private final String algorithm;
+ private final String providerName;
+
+ private OAuthSignatureAlgorithm(final String signatureName, final String hashAlg, final String providerName) {
+ this.signatureName = signatureName;
+ this.algorithm = hashAlg;
+ this.providerName = providerName;
+ }
+
+ /**
+ * What the signature algorithm is named in the "alg" parameter in a JSON Token's envelope.
+ */
+ public String getAlgorithm() {
+ return this.algorithm;
+ }
+
+ /**
+ *
+ * @return the signature name like SHA256withECDSA or SHA256withRSA
+ */
+ public String getSignatureName() {
+ return this.signatureName;
+ }
+
+ /**
+ * Calls {@link Signature#getInstance(String)} with the defined signature name
+ *
+ * @return
+ * @throws NoSuchAlgorithmException
+ * @throws NoSuchProviderException
+ */
+ public Signature getSignatureInstance() throws NoSuchAlgorithmException, NoSuchProviderException {
+ if (!StringUtils.isEmpty(this.providerName)) {
+ //return Signature.getInstance(this.signatureName, this.providerName);
+ return Signature.getInstance(this.signatureName, this.providerName);
+ } else {
+ return Signature.getInstance(this.signatureName);
+ }
+ }
+
+ /**
+ * Given the name of the algorithm in the envelope, returns the corresponding enum instance.
+ */
+ public static OAuthSignatureAlgorithm getFromJsonName(String name) {
+ return OAuthSignatureAlgorithm.valueOf(name);
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java
new file mode 100644
index 000000000..3904f8cef
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java
@@ -0,0 +1,29 @@
+/*******************************************************************************
+ * 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.oauth20.json;
+
+import net.oauth.jsontoken.crypto.Signer;
+
+public interface OAuthSigner extends Signer {
+ public abstract OAuthSignatureAlgorithm getOAuthSignatureAlgorithm();
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java
new file mode 100644
index 000000000..88e26da76
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java
@@ -0,0 +1,214 @@
+/*******************************************************************************
+ * 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.oauth20.protocol;
+
+import java.security.SignatureException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.data.SLOInformationImpl;
+import at.gv.egovernment.moa.id.data.SLOInformationInterface;
+import at.gv.egovernment.moa.id.moduls.IAction;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject;
+import at.gv.egovernment.moa.id.protocols.oauth20.Pair;
+import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OAuth20AttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OpenIdExpirationTimeAttribute;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException;
+import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuth20SignatureUtil;
+import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthJsonToken;
+import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthSigner;
+import at.gv.egovernment.moa.id.storage.AssertionStorage;
+import at.gv.egovernment.moa.id.util.Random;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.MiscUtil;
+
+class OAuth20AuthAction implements IAction {
+
+ public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp,
+ IAuthData authData) throws MOAIDException {
+
+ OAuth20AuthRequest oAuthRequest = (OAuth20AuthRequest) req;
+ String responseType = oAuthRequest.getResponseType();
+
+ MOAReversionLogger.getInstance().logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_OPENIDCONNECT_AUTHREQUEST);
+
+ String code = Random.nextRandom();
+
+ try {
+
+ String accessToken = UUID.randomUUID().toString();
+
+ Logger.debug("Stored session with id: " + code);
+ OAuth20SessionObject o = new OAuth20SessionObject();
+ if (responseType.equals(OAuth20Constants.RESPONSE_CODE)) {
+ o.setScope(oAuthRequest.getScope());
+ o.setCode(code);
+
+ //generate idToken from MOASession
+ Map<String, Object> idToken = generateIDToken(o, oAuthRequest, authData, accessToken);
+ o.setAuthDataSession(idToken);
+
+ } else if (responseType.equals(OAuth20Constants.RESPONSE_TOKEN)) {
+ throw new OAuth20ResponseTypeException();
+ }
+
+ // store data in oath session
+ AssertionStorage.getInstance().put(code, o);
+
+ Logger.debug("Saved OAuth20SessionObject in session with id: " + code);
+
+ // add code and state to redirect url
+ httpResp.setStatus(HttpServletResponse.SC_FOUND);
+ String redirectURI = oAuthRequest.getRedirectUri();
+ String state = oAuthRequest.getState();
+
+ redirectURI = this.addURLParameter(redirectURI, OAuth20Constants.RESPONSE_CODE, code);
+ redirectURI = this.addURLParameter(redirectURI, OAuth20Constants.PARAM_STATE, state);
+
+ String finalUrl = redirectURI;
+ httpResp.addHeader("Location", finalUrl);
+ Logger.debug("REDIRECT TO: " + finalUrl.toString());
+
+
+ //TODO: maybe add bPK / wbPK to SLO information
+ SLOInformationInterface sloInformation = new SLOInformationImpl(req.getAuthURL(), accessToken, null, null, req.requestedModule());
+
+ return sloInformation;
+ }
+ catch (Exception e) {
+ Logger.warn("An error occur during OpenID-Connect idToken generation.", e);
+
+ //remove OAuthSessionObject if it already exists
+ if (AssertionStorage.getInstance().containsKey(code)) {
+ AssertionStorage.getInstance().remove(code);
+ }
+
+ if (e instanceof OAuth20Exception) {
+ throw (OAuth20Exception) e;
+ }
+ throw new OAuth20ServerErrorException();
+ }
+
+ }
+
+ private Map<String, Object> generateIDToken(OAuth20SessionObject auth20SessionObject,
+ OAuth20AuthRequest oAuthRequest, IAuthData authData, String accessToken) throws SignatureException, MOAIDException {
+
+ // create response
+ Map<String, Object> params = new HashMap<String, Object>();
+ params.put(OAuth20Constants.RESPONSE_ACCESS_TOKEN, accessToken);
+ params.put(OAuth20Constants.RESPONSE_TOKEN_TYPE, OAuth20Constants.RESPONSE_TOKEN_TYPE_VALUE_BEARER);
+ params.put(OAuth20Constants.RESPONSE_EXPIRES_IN, OpenIdExpirationTimeAttribute.expirationTime);
+ // build id token and scope
+ Pair<String, String> pair = buildIdToken(auth20SessionObject.getScope(), oAuthRequest,
+ authData);
+ Logger.debug("RESPONSE ID_TOKEN: " + pair.getFirst());
+ params.put(OAuth20Constants.RESPONSE_ID_TOKEN, pair.getFirst());
+ Logger.debug("RESPONSE SCOPE: " + pair.getSecond());
+ params.put(OAuth20Constants.PARAM_SCOPE, pair.getSecond());
+
+ return params;
+
+ }
+
+ private Pair<String, String> buildIdToken(String scope, OAuth20AuthRequest oAuthRequest, IAuthData authData)
+ throws MOAIDException, SignatureException {
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL());
+
+ OAuthSigner signer = OAuth20SignatureUtil.loadSigner(authData.getIssuer());
+ OAuthJsonToken token = new OAuthJsonToken(signer);
+
+ StringBuilder resultScopes = new StringBuilder();
+ // always fill with open id
+ OAuth20AttributeBuilder.addScopeOpenId(token.getPayloadAsJsonObject(), oaParam, authData, oAuthRequest);
+ resultScopes.append("openId");
+
+ for (String s : scope.split(" ")) {
+ if (s.equalsIgnoreCase("profile")) {
+ OAuth20AttributeBuilder.addScopeProfile(token.getPayloadAsJsonObject(), oaParam, authData);
+ resultScopes.append(" profile");
+ } else if (s.equalsIgnoreCase("eID")) {
+ OAuth20AttributeBuilder.addScopeEID(token.getPayloadAsJsonObject(), oaParam, authData);
+ resultScopes.append(" eID");
+ } else if (s.equalsIgnoreCase("eID_gov")) {
+ OAuth20AttributeBuilder.addScopeEIDGov(token.getPayloadAsJsonObject(), oaParam, authData);
+ resultScopes.append(" eID_gov");
+ } else if (s.equalsIgnoreCase("mandate")) {
+ OAuth20AttributeBuilder.addScopeMandate(token.getPayloadAsJsonObject(), oaParam, authData);
+ resultScopes.append(" mandate");
+ } else if (s.equalsIgnoreCase("stork")) {
+ OAuth20AttributeBuilder.addScopeSTORK(token.getPayloadAsJsonObject(), oaParam, authData);
+ resultScopes.append(" stork");
+ }
+ }
+
+ // add properties and sign
+ // HmacSHA256Signer signer = new HmacSHA256Signer("testSigner", "key_id",
+ // "super_secure_pwd".getBytes());
+ // Signer signer = OAuth20Util.loadSigner(authData.getIssuer(), oaParam.getoAuth20Config());
+
+ return Pair.newInstance(token.serializeAndSign(), resultScopes.toString());
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
+ * at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls
+ * .IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) {
+ return true;
+ }
+
+ private String addURLParameter(String url, String name, String value) {
+ String param = name + "=" + value;
+ if (url.indexOf("?") < 0) {
+ return url + "?" + param;
+ } else {
+ return url + "&" + param;
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName()
+ */
+ public String getDefaultActionName() {
+ return OAuth20Protocol.AUTH_ACTION;
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java
new file mode 100644
index 000000000..e5d8db873
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java
@@ -0,0 +1,243 @@
+/*******************************************************************************
+ * 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.oauth20.protocol;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.opensaml.saml2.core.Attribute;
+
+import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util;
+import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OAuth20AttributeBuilder;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder;
+import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder;
+import at.gv.egovernment.moa.logging.Logger;
+
+public class OAuth20AuthRequest extends OAuth20BaseRequest {
+
+ /**
+ * @param req
+ * @throws ConfigurationException
+ */
+ public OAuth20AuthRequest(HttpServletRequest req)
+ throws ConfigurationException {
+ super(req);
+ }
+
+ private static final long serialVersionUID = 1L;
+
+ private String responseType;
+ private String state;
+ private String redirectUri;
+ private String scope;
+ private String clientID;
+ private String nonce;
+
+ /**
+ * @return the responseType
+ */
+ public String getResponseType() {
+ return responseType;
+ }
+
+ /**
+ * @param responseType
+ * the responseType to set
+ */
+ public void setResponseType(String responseType) {
+ this.responseType = responseType;
+ }
+
+ /**
+ * @return the state
+ */
+ public String getState() {
+ return state;
+ }
+
+ /**
+ * @param state
+ * the state to set
+ */
+ public void setState(String state) {
+ this.state = state;
+ }
+
+ /**
+ * @return the redirectUri
+ */
+ public String getRedirectUri() {
+ return redirectUri;
+ }
+
+ /**
+ * @param redirectUri
+ * the redirectUri to set
+ */
+ public void setRedirectUri(String redirectUri) {
+ this.redirectUri = redirectUri;
+ }
+
+ /**
+ * @return the scope
+ */
+ public String getScope() {
+ return scope;
+ }
+
+ /**
+ * @param scope
+ * the scope to set
+ */
+ public void setScope(String scope) {
+ this.scope = scope;
+ }
+
+ /**
+ * @return the clientID
+ */
+ public String getClientID() {
+ return clientID;
+ }
+
+ /**
+ * @param clientID
+ * the clientID to set
+ */
+ public void setClientID(String clientID) {
+ this.clientID = clientID;
+ }
+
+
+
+ /**
+ * @return the nonce
+ */
+ public String getNonce() {
+ return nonce;
+ }
+
+ /**
+ * @param nonce the nonce to set
+ */
+ public void setNonce(String nonce) {
+ this.nonce = nonce;
+ }
+
+ @Override
+ protected void populateSpecialParameters(HttpServletRequest request) throws OAuth20Exception {
+ this.setResponseType(this.getParam(request, OAuth20Constants.PARAM_RESPONSE_TYPE, true));
+ this.setState(this.getParam(request, OAuth20Constants.PARAM_STATE, true));
+ this.setRedirectUri(this.getParam(request, OAuth20Constants.PARAM_REDIRECT_URI, true));
+ this.setClientID(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true));
+ this.setScope(this.getParam(request, OAuth20Constants.PARAM_SCOPE, false));
+ this.setNonce(this.getParam(request, OAuth20Constants.PARAM_NONCE, false));
+
+ // check for response type
+ if (!this.responseType.equals(OAuth20Constants.RESPONSE_CODE)) {
+ throw new OAuth20ResponseTypeException();
+ }
+
+ // check state for invalid characters (like < > & ; ... javascript ... to prevent xss)
+ if (!OAuth20Util.isValidStateValue(this.getState())) {
+ throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_STATE);
+ }
+
+ // check if client id and redirect uri are ok
+ try {
+ // OAOAUTH20 cannot be null at this point. check was done in base request
+ OAAuthParameter oAuthConfig = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(this.getOAURL());
+
+
+ if (!this.getClientID().equals(oAuthConfig.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTID))
+ || !this.getRedirectUri().equals(oAuthConfig.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_REDIRECTURL))) {
+ throw new OAuth20AccessDeniedException();
+ }
+
+ this.setOnlineApplicationConfiguration(oAuthConfig);
+ Logger.info("Dispatch OpenIDConnect AuthRequest: ClientID=" + this.clientID);
+
+
+ } catch (ConfigurationException e) {
+ throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID);
+ }
+
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes()
+ */
+ @Override
+ public List<Attribute> getRequestedAttributes() {
+ Map<String, String> reqAttr = new HashMap<String, String>();
+ for (String el : PVP2XProtocol.DEFAULTREQUESTEDATTRFORINTERFEDERATION)
+ reqAttr.put(el, "");
+
+ try {
+ OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(getOAURL());
+
+ for (String s : scope.split(" ")) {
+ if (s.equalsIgnoreCase("profile")) {
+ for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersprofile())
+ reqAttr.put(el.getName(), "");
+
+ } else if (s.equalsIgnoreCase("eID")) {
+ for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuilderseid())
+ reqAttr.put(el.getName(), "");
+
+ } else if (s.equalsIgnoreCase("eID_gov")) {
+ for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuilderseidgov())
+ reqAttr.put(el.getName(), "");
+
+ } else if (s.equalsIgnoreCase("mandate")) {
+ for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersmandate())
+ reqAttr.put(el.getName(), "");
+
+ } else if (s.equalsIgnoreCase("stork")) {
+ for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersstork())
+ reqAttr.put(el.getName(), "");
+
+ }
+ }
+
+ return AttributQueryBuilder.buildSAML2AttributeList(oa, reqAttr.keySet().iterator());
+
+ } catch (ConfigurationException e) {
+ Logger.error("Load configuration for OA " + getOAURL() + " FAILED", e);
+ return null;
+ }
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java
new file mode 100644
index 000000000..5fcac0b2f
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java
@@ -0,0 +1,148 @@
+/*******************************************************************************
+ * 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.oauth20.protocol;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.commons.lang.StringEscapeUtils;
+import org.apache.commons.lang.StringUtils;
+
+import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.moduls.RequestImpl;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidRequestException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20OANotSupportedException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.logging.Logger;
+
+abstract class OAuth20BaseRequest extends RequestImpl {
+
+ private static final long serialVersionUID = 1L;
+
+ protected Set<String> allowedParameters = new HashSet<String>();
+
+ public OAuth20BaseRequest(HttpServletRequest req) throws ConfigurationException {
+ super(req);
+ }
+
+ protected String getParam(final HttpServletRequest request, final String name, final boolean isNeeded) throws OAuth20Exception {
+ String param = request.getParameter(name);
+ Logger.debug("Reading param " + name + " from HttpServletRequest with value " + param);
+
+ if (isNeeded && StringUtils.isEmpty(param)) {
+ throw new OAuth20WrongParameterException(name);
+ }
+
+ this.allowedParameters.add(name);
+
+ return param;
+ }
+
+ protected void populateParameters(final HttpServletRequest request) throws OAuth20Exception {
+
+ // moa id - load oa with client id!
+ try {
+ String oaURL = StringEscapeUtils.escapeHtml(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true));
+ if (!ParamValidatorUtils.isValidOA(oaURL)) {
+ throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID);
+ }
+ this.setOAURL(oaURL);
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oaURL);
+
+ if (oaParam == null) {
+ throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID);
+ }
+ this.setTarget(oaParam.getTarget());
+
+ if (StringUtils.isEmpty(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTSECRET))
+ || StringUtils.isEmpty(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTID))
+ || StringUtils.isEmpty(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_REDIRECTURL))) {
+ throw new OAuth20OANotSupportedException();
+ }
+ }
+ catch (ConfigurationException e) {
+ throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID);
+ }
+
+ // oAuth
+ this.populateSpecialParameters(request);
+
+ // cleanup parameters
+ this.checkAllowedParameters(request);
+ }
+
+ private void checkAllowedParameters(final HttpServletRequest request) {
+ Logger.debug("Going to check for allowed parameters");
+ this.allowedParameters.add(OAuth20Constants.PARAM_MOA_ACTION);
+ this.allowedParameters.add(OAuth20Constants.PARAM_MOA_MOD);
+
+ @SuppressWarnings("rawtypes")
+ Iterator iter = request.getParameterMap().keySet().iterator();
+ while (iter.hasNext()) {
+ String name = (String) iter.next();
+ if (!this.allowedParameters.contains(name)) {
+
+ Logger.debug("Found wrong parameter: " + name);
+ throw new OAuth20WrongParameterException(name);
+ }
+ }
+
+ }
+
+ protected abstract void populateSpecialParameters(final HttpServletRequest request) throws OAuth20Exception;
+
+ public static OAuth20BaseRequest newInstance(final String action, final HttpServletRequest request, String sessionId, String transactionId) throws OAuth20Exception {
+ OAuth20BaseRequest res;
+ try {
+ if (action.equals(OAuth20Protocol.AUTH_ACTION)) {
+ res = new OAuth20AuthRequest(request);
+
+ } else if (action.equals(OAuth20Protocol.TOKEN_ACTION)) {
+ res = new OAuth20TokenRequest(request);
+
+ } else {
+ throw new OAuth20InvalidRequestException();
+ }
+
+ } catch (ConfigurationException e) {
+ Logger.warn(e.getMessage());
+ throw new OAuth20InvalidRequestException();
+
+ }
+
+ res.setAction(action);
+ res.setModule(OAuth20Protocol.NAME);
+
+ res.populateParameters(request);
+ return res;
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java
new file mode 100644
index 000000000..56d86df72
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java
@@ -0,0 +1,215 @@
+package at.gv.egovernment.moa.id.protocols.oauth20.protocol;
+
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.StringUtils;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.moduls.IAction;
+import at.gv.egovernment.moa.id.moduls.IModulInfo;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.id.util.ErrorResponseUtils;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.MiscUtil;
+
+import com.google.gson.JsonObject;
+
+import java.util.Arrays;
+
+public class OAuth20Protocol implements IModulInfo {
+
+ public static final String NAME = OAuth20Protocol.class.getName();
+ public static final String PATH = "id_oauth20";
+
+ public static final String AUTH_ACTION = "AUTH";
+ public static final String TOKEN_ACTION = "TOKEN";
+
+ public static final List<String> DEFAULTREQUESTEDATTRFORINTERFEDERATION = Arrays.asList(
+ new String[] {
+ PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME,
+ PVPConstants.BPK_NAME
+ });
+
+ private static HashMap<String, IAction> actions = new HashMap<String, IAction>();
+
+ static {
+ actions.put(AUTH_ACTION, new OAuth20AuthAction());
+ actions.put(TOKEN_ACTION, new OAuth20TokenAction());
+ }
+
+ public String getName() {
+ return NAME;
+ }
+
+ public String getPath() {
+ return PATH;
+ }
+
+ public IAction getAction(String action) {
+ return actions.get(action);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
+ * at.gv.egovernment.moa.id.moduls.IModulInfo#preProcess(javax.servlet.http.HttpServletRequest,
+ * javax.servlet.http.HttpServletResponse, java.lang.String)
+ */
+ public IRequest preProcess(HttpServletRequest request, HttpServletResponse resp, String action,
+ String sessionId, String transactionId) throws MOAIDException {
+ // validation is done inside creation
+ OAuth20BaseRequest res = OAuth20BaseRequest.newInstance(action, request, sessionId, transactionId);
+ Logger.debug("Created: " + res);
+ return res;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
+ * at.gv.egovernment.moa.id.moduls.IModulInfo#canHandleRequest(javax.servlet.http.HttpServletRequest
+ * , javax.servlet.http.HttpServletResponse)
+ */
+ public IAction canHandleRequest(HttpServletRequest request, HttpServletResponse response) {
+ if (!StringUtils.isEmpty(request.getParameter("action"))) {
+ if (request.getParameter("action").equals(AUTH_ACTION)) {
+ return getAction(AUTH_ACTION);
+ } else if (request.getParameter("action").equals(TOKEN_ACTION)) {
+ return getAction(TOKEN_ACTION);
+ }
+ }
+
+ return null;// getAction(AUTH_ACTION);
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IModulInfo#generateErrorMessage(java.lang.Throwable,
+ * javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
+ * at.gv.egovernment.moa.id.moduls.IRequest)
+ */
+ public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest)
+ throws Throwable {
+
+ // get error code and description
+ String errorCode;
+ String errorDescription;
+ String errorUri = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix()
+ +"/" + OAuth20Constants.ERRORPAGE;
+ String moaError = null;
+
+ ErrorResponseUtils errorUtils = ErrorResponseUtils.getInstance();
+
+ if (e instanceof OAuth20Exception) {
+ errorCode = ((OAuth20Exception) e).getErrorCode();
+ errorDescription = URLEncoder.encode(((OAuth20Exception) e).getMessageId() + ": " + e.getMessage(), "UTF-8");
+ moaError = errorUtils.mapInternalErrorToExternalError(((OAuth20Exception) e).getMessageId());
+
+ } else {
+ errorCode = OAuth20Constants.ERROR_SERVER_ERROR;
+ errorDescription = URLEncoder.encode(e.getMessage(), "UTF-8");
+ moaError = errorUtils.getResponseErrorCode(e);
+ }
+
+ String paramRedirect = null;
+ String state = null;
+ boolean isAuthRequest = false;
+ if (protocolRequest != null) {
+ if (protocolRequest instanceof OAuth20AuthRequest) {
+ isAuthRequest = true;
+
+ paramRedirect = ((OAuth20AuthRequest) protocolRequest).getRedirectUri();
+ state = ((OAuth20AuthRequest) protocolRequest).getState();
+ } else {
+ isAuthRequest = false;
+ }
+ } else {
+ String action = request.getParameter("action");
+ if (MiscUtil.isNotEmpty(action)) {
+ if (action.equals(AUTH_ACTION)) {
+
+ paramRedirect = request.getParameter(OAuth20Constants.PARAM_REDIRECT_URI);
+ state = request.getParameter(OAuth20Constants.PARAM_STATE);
+ isAuthRequest = true;
+ }
+ } else {
+ throw new MOAIDException("oauth20.01", new Object[] {});
+ }
+ }
+
+ // if (action.equals(AUTH_ACTION)) {
+ if (isAuthRequest) {
+ Logger.debug("Going to throw O OAuth20Exception for auth request");
+
+ StringBuilder url = new StringBuilder();
+
+ // check if given redirect url is ok
+ if (StringUtils.isNotEmpty(paramRedirect) && OAuth20Util.isUrl(paramRedirect)) {
+ url.append(paramRedirect);
+
+ // otherwise throw an
+ } else {
+ throw new MOAIDException("oauth20.01", new Object[] {});
+ }
+
+ OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR, errorCode);
+ OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR_DESCRIPTION, errorDescription);
+ if (MiscUtil.isNotEmpty(moaError))
+ OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_ERROR_URI, errorUri + "#" + moaError);
+ OAuth20Util.addParameterToURL(url, OAuth20Constants.PARAM_STATE, state);
+
+ response.setContentType("text/html");
+ response.setStatus(HttpServletResponse.SC_FOUND);
+ response.addHeader("Location", url.toString());
+ Logger.debug("REDIRECT TO: " + url.toString());
+ return true;
+
+ } else {
+ Logger.debug("Going to throw O OAuth20Exception for token request");
+
+ Map<String, Object> params = new HashMap<String, Object>();
+ params.put(OAuth20Constants.PARAM_ERROR, errorCode);
+ params.put(OAuth20Constants.PARAM_ERROR_DESCRIPTION, errorDescription);
+ params.put(OAuth20Constants.PARAM_ERROR_URI, errorUri + "#" + moaError);
+
+ // create response
+ JsonObject jsonObject = new JsonObject();
+ OAuth20Util.addProperytiesToJsonObject(jsonObject, params);
+ String jsonResponse = jsonObject.toString();
+ Logger.debug("JSON Response: " + jsonResponse);
+
+ // write respone to http response
+ response.setContentType("application/json");
+ response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+ response.getOutputStream().print(jsonResponse);
+ response.getOutputStream().close();
+
+ return true;
+ }
+
+ // return false;
+
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
+ * at.gv.egovernment.moa.id.moduls.IModulInfo#validate(javax.servlet.http.HttpServletRequest,
+ * javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.moduls.IRequest)
+ */
+ public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) {
+ // we validate in the preProcess
+ return true;
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java
new file mode 100644
index 000000000..2238a25e1
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java
@@ -0,0 +1,124 @@
+/*******************************************************************************
+ * 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.oauth20.protocol;
+
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+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.data.IAuthData;
+import at.gv.egovernment.moa.id.data.SLOInformationInterface;
+import at.gv.egovernment.moa.id.moduls.IAction;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20UnauthorizedClientException;
+import at.gv.egovernment.moa.id.storage.AssertionStorage;
+import at.gv.egovernment.moa.logging.Logger;
+
+import com.google.gson.JsonObject;
+
+class OAuth20TokenAction implements IAction {
+
+ public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp,
+ IAuthData authData) throws MOAIDException {
+
+
+ OAuth20SessionObject auth20SessionObject = null;
+ try {
+ OAuth20TokenRequest oAuthRequest = (OAuth20TokenRequest) req;
+
+ MOAReversionLogger.getInstance().logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_OPENIDCONNECT_TOKENREQUEST);
+
+ try {
+ Logger.debug("Loaded OAuth20SessionObject from session: " + oAuthRequest.getCode());
+
+ auth20SessionObject =
+ AssertionStorage.getInstance().get(oAuthRequest.getCode(), OAuth20SessionObject.class);
+
+ } catch (MOADatabaseException e) {
+ throw new OAuth20UnauthorizedClientException();
+
+ }
+
+ // do checking for different grant types and code
+ if (auth20SessionObject == null || !auth20SessionObject.getCode().equals(oAuthRequest.getCode())) {
+ throw new OAuth20UnauthorizedClientException();
+ } else {
+ Logger.debug("Loaded of OAuth20SessionObject was successful");
+ }
+
+ // create response
+ JsonObject jsonObject = new JsonObject();
+ OAuth20Util.addProperytiesToJsonObject(jsonObject, auth20SessionObject.getAuthDataSession());
+ String jsonResponse = jsonObject.toString();
+ Logger.debug("JSON Response: " + jsonResponse);
+
+ // write respone to http response
+ httpResp.setContentType("application/json");
+ httpResp.setStatus(HttpServletResponse.SC_OK);
+ httpResp.getOutputStream().print(jsonResponse);
+ httpResp.getOutputStream().close();
+
+ return null;
+ }
+ catch (Exception e) {
+ Logger.error(e.getMessage(), e);
+ throw new OAuth20ServerErrorException();
+ }
+
+ finally {
+ if (auth20SessionObject != null) {
+ // destroy session for clean up
+
+ Logger.debug("Going to destroy session: " + auth20SessionObject.getCode());
+ AssertionStorage.getInstance().remove(auth20SessionObject.getCode());
+
+ }
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see
+ * at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls
+ * .IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) {
+ return false;
+ }
+
+ /*
+ * (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName()
+ */
+ public String getDefaultActionName() {
+ return OAuth20Protocol.TOKEN_ACTION;
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java
new file mode 100644
index 000000000..abfe4ce15
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java
@@ -0,0 +1,166 @@
+/*******************************************************************************
+ * 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.oauth20.protocol;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.opensaml.saml2.core.Attribute;
+
+import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidGrantException;
+import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException;
+import at.gv.egovernment.moa.logging.Logger;
+
+class OAuth20TokenRequest extends OAuth20BaseRequest {
+
+ /**
+ * @param req
+ * @throws ConfigurationException
+ */
+ public OAuth20TokenRequest(HttpServletRequest req)
+ throws ConfigurationException {
+ super(req);
+ }
+
+ private static final long serialVersionUID = 1L;
+
+ private String code;
+ private String grantType;
+ private String clientID;
+ private String clientSecret;
+
+ /**
+ * @return the code
+ */
+ public String getCode() {
+ return code;
+ }
+
+ /**
+ * @param code
+ * the code to set
+ */
+ public void setCode(String code) {
+ this.code = code;
+ }
+
+ /**
+ * @return the grantType
+ */
+ public String getGrantType() {
+ return grantType;
+ }
+
+ /**
+ * @param grantType
+ * the grantType to set
+ */
+ public void setGrantType(String grantType) {
+ this.grantType = grantType;
+ }
+
+ /**
+ * @return the clientID
+ */
+ public String getClientID() {
+ return clientID;
+ }
+
+ /**
+ * @param clientID
+ * the clientID to set
+ */
+ public void setClientID(String clientID) {
+ this.clientID = clientID;
+ }
+
+ /**
+ * @return the clientSecret
+ */
+ public String getClientSecret() {
+ return clientSecret;
+ }
+
+ /**
+ * @param clientSecret
+ * the clientSecret to set
+ */
+ public void setClientSecret(String clientSecret) {
+ this.clientSecret = clientSecret;
+ }
+
+ @Override
+ protected void populateSpecialParameters(HttpServletRequest request) throws OAuth20Exception {
+ this.setCode(this.getParam(request, OAuth20Constants.RESPONSE_CODE, true));
+ this.setGrantType(this.getParam(request, OAuth20Constants.PARAM_GRANT_TYPE, true));
+ this.setClientID(this.getParam(request, OAuth20Constants.PARAM_CLIENT_ID, true));
+ this.setClientSecret(this.getParam(request, OAuth20Constants.PARAM_CLIENT_SECRET, true));
+
+ // check for grant type
+ if (!this.getGrantType().equals(OAuth20Constants.PARAM_GRANT_TYPE_VALUE_AUTHORIZATION_CODE)) {
+ throw new OAuth20InvalidGrantException();
+ }
+
+ // check if client id and secret are ok
+ try {
+ // OAOAUTH20 cannot be null at this point. check was done in base request
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(this.getOAURL());
+
+ if (!this.getClientID().equals(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTID))) {
+ throw new OAuth20AccessDeniedException();
+ }
+
+ if (!this.getClientSecret().equals(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTSECRET))) {
+ throw new OAuth20AccessDeniedException();
+ }
+
+ this.setOnlineApplicationConfiguration(oaParam);
+
+ }
+ catch (ConfigurationException e) {
+ throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID);
+ }
+
+ Logger.info("Dispatch OpenIDConnect TokenRequest: ClientID=" + this.clientID);
+
+ //add valid parameters
+ this.allowedParameters.add(OAuth20Constants.PARAM_SCOPE);
+ this.allowedParameters.add(OAuth20Constants.PARAM_REDIRECT_URI);
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes()
+ */
+ @Override
+ public List<Attribute> getRequestedAttributes() {
+ return null;
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo b/id/server/modules/moa-id-module-openID/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo
new file mode 100644
index 000000000..b653c91c3
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo
@@ -0,0 +1 @@
+at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20Protocol \ No newline at end of file
diff --git a/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/CertTest.java b/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/CertTest.java
new file mode 100644
index 000000000..6cf1e8280
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/CertTest.java
@@ -0,0 +1,131 @@
+/*******************************************************************************
+ * 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 test.at.gv.egovernment.moa.id.auth.oauth;
+
+import iaik.security.ecc.provider.ECCProvider;
+
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+
+import net.oauth.jsontoken.crypto.Signer;
+import net.oauth.jsontoken.crypto.Verifier;
+
+import org.opensaml.xml.security.x509.BasicX509Credential;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuth20SHA256Signer;
+import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuth20SHA256Verifier;
+import at.gv.egovernment.moa.util.KeyStoreUtils;
+
+public class CertTest {
+
+ /** KeyStore Path */
+ private String rsaKeyStorePath = "file:/D:/dev/work/exthex/workspace/OAuthTesting/resources/keys/test_keystore.jks";
+
+ private String ecdsaKeyStorePath = "file:/D:/dev/work/exthex/workspace/OAuthTesting/resources/keys/ECDSA_keystore.jks";
+
+ /** KeyStore Password */
+ private String keyStorePassword = "test12";
+
+ /** Specific Key Name as Credential */
+ private String keyName = "1";
+
+ /** Key password */
+ private String keyPassword = "test12";
+
+ private BasicX509Credential getCredentials(String keyStorePath) {
+ Assert.assertNotNull(keyStorePath);
+
+ // KeyStorePassword optional
+ // if (StringUtils.isEmpty(this.keyStorePassword))
+ // throw new SAMLException("No keyStorePassword specified");
+
+ Assert.assertNotNull(this.keyName);
+
+ // KeyStorePassword optional
+ // if (StringUtils.isEmpty(this.keyPassword))
+ // throw new SAMLException("No keyPassword specified");
+
+ KeyStore ks = null;
+ try {
+ ks = KeyStoreUtils.loadKeyStore(keyStorePath, this.keyStorePassword);
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ // return new KeyStoreX509CredentialAdapter(ks, keyName, keyPwd.toCharArray());
+ BasicX509Credential credential = null;
+ try {
+ X509Certificate certificate = (X509Certificate) ks.getCertificate(this.keyName);
+
+ PrivateKey privateKey = (PrivateKey) ks.getKey(this.keyName, this.keyPassword.toCharArray());
+
+ // System.out.println("KS Provider:" + privateKey.getClass());
+ credential = new BasicX509Credential();
+ credential.setEntityCertificate(certificate);
+ credential.setPrivateKey(privateKey);
+
+ System.out.println("Private Key: " + privateKey);
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+
+ }
+
+ return credential;
+ }
+
+ private void signAndVerify(BasicX509Credential credential) throws Exception {
+ String data = "someData";
+
+ Signer signer = new OAuth20SHA256Signer("signer1", keyName, credential.getPrivateKey());
+
+ byte[] signedData = signer.sign(data.getBytes());
+
+ Verifier verifier = new OAuth20SHA256Verifier(credential.getPublicKey());
+ verifier.verifySignature(data.getBytes(), signedData);
+ }
+
+ @Test
+ // (enabled = false)
+ public void testRSA() throws Exception {
+ BasicX509Credential credential = this.getCredentials(this.rsaKeyStorePath);
+
+ // System.out.println(credential);
+ this.signAndVerify(credential);
+ }
+
+ @Test
+ public void testECDSA() throws Exception {
+ ECCProvider.addAsProvider();
+
+ // Security.addProvider(new ECCProvider());
+ BasicX509Credential credential = this.getCredentials(this.ecdsaKeyStorePath);
+ this.signAndVerify(credential);
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20ErrorsTests.java b/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20ErrorsTests.java
new file mode 100644
index 000000000..abfca4f36
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20ErrorsTests.java
@@ -0,0 +1,184 @@
+package test.at.gv.egovernment.moa.id.auth.oauth;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.lang.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants;
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util;
+
+import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver;
+import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
+
+public class OAuth20ErrorsTests {
+
+ final static Logger log = LoggerFactory.getLogger(OAuth20ErrorsTests.class);
+
+ private static VerificationCodeReceiver receiver;
+
+ // base uri
+ private static String OAUTH2_BASE_URI = "https://localhost/moa-id-auth/";
+ // auth action
+ private static String OAUTH2_AUTH_URI = OAUTH2_BASE_URI + "oauth2/auth";
+ // token action
+ private static String OAUTH2_TOKEN_URI = OAUTH2_BASE_URI + "oauth2/token";
+
+ // client id
+ private static String CLIENT_ID = "http://test";
+ // client secret
+ private static String CLIENT_SECRET = "d435cf0a-3933-48f7-b142-339710c8f070";
+ // OAuth 2.0 scopes
+ //private static List<String> SCOPES = Arrays.asList("testScope1", "testScope2");
+ // state
+ private static String STATE = "testState";
+ // code
+ private static String CODE = "code";
+ // redirect uri
+ private static String REDIRECT_URI = "http://localhost:59542/Callback";
+
+ @BeforeMethod
+ public void beforeTest() throws Exception {
+ receiver = new LocalServerReceiver.Builder().setPort(59542).build();
+ // REDIRECT_URI = receiver.getRedirectUri();
+ // start
+ receiver.getRedirectUri();
+ }
+
+ @AfterMethod
+ public void afterTest() {
+ try {
+ receiver.stop();
+ }
+ catch (IOException e) {
+ }
+ }
+
+ private void checkParam(final String paramString, final String paramName) {
+ String[] help = paramString.split("=");
+ Assert.assertEquals(help[0], paramName);
+ Assert.assertTrue(StringUtils.isNotEmpty(help[1]));
+ }
+
+ private void checkParams(final String queryString) {
+ // System.out.println("QueryString: " + queryString);
+
+ System.out.println("Result url: " + queryString);
+
+ String[] params = queryString.split("&");
+
+ this.checkParam(params[0], OAuth20Constants.PARAM_ERROR);
+ this.checkParam(params[1], OAuth20Constants.PARAM_ERROR_DESCRIPTION);
+ // this.checkParam(params[2], OAuth20Constants.PARAM_ERROR_URI);
+ // this.checkParam(params[3], OAuth20Constants.PARAM_STATE);
+ this.checkParam(params[2], OAuth20Constants.PARAM_STATE);
+ }
+
+ class OAuthRequestParameters {
+ String redirectUri;
+ String clientId;
+ String responseType;
+ String scope;
+ String state;
+ String error;
+
+ public OAuthRequestParameters(String redirectUri, String clientId, String responseType, String scope, String state,
+ String error) {
+ this.redirectUri = redirectUri;
+ this.clientId = clientId;
+ this.responseType = responseType;
+ this.scope = scope;
+ this.state = state;
+ this.error = error;
+ }
+ }
+
+ @DataProvider(name = "parameter")
+ public Object[][] parameterProvider() {
+ // parameter is missing
+ // OAuthRequestParameters p0 = new OAuthRequestParameters(null, OA_URL, CLIENT_ID, CODE,
+ // "testScope1", null,
+ // "User authorization failed (invalid_request)");
+ // OAuthRequestParameters p1 = new OAuthRequestParameters(REDIRECT_URI, CLIENT_ID, CODE,
+ // "testScope1", STATE,
+ // "User authorization failed (invalid_request)");
+ OAuthRequestParameters p2 = new OAuthRequestParameters(REDIRECT_URI, null, CODE, "testScope1", STATE,
+ "User authorization failed (invalid_request)");
+ OAuthRequestParameters p3 = new OAuthRequestParameters(REDIRECT_URI, CLIENT_ID, null, "testScope1", STATE,
+ "User authorization failed (invalid_request)");
+ OAuthRequestParameters p4 = new OAuthRequestParameters(REDIRECT_URI, CLIENT_ID, CODE, null, STATE, null);
+ OAuthRequestParameters p5 = new OAuthRequestParameters(REDIRECT_URI, CLIENT_ID, CODE, "testScope1", null,
+ "User authorization failed (invalid_request)");
+
+ // wrong response type
+ OAuthRequestParameters p6 = new OAuthRequestParameters(REDIRECT_URI, CLIENT_ID, "WRONG_CODE", "testScope1", STATE,
+ "User authorization failed (unsupported_response_type)");
+ // wrong client id
+ OAuthRequestParameters p7 = new OAuthRequestParameters(REDIRECT_URI, "wrongClient", CODE, "testScope1", STATE,
+ "User authorization failed (invalid_request)");
+ // wrong redirect uri
+ // OAuthRequestParameters p9 = new OAuthRequestParameters("wrongURI", OA_URL, "wrongClient",
+ // CODE, "testScope1", STATE,
+ // "User authorization failed (access_denied)");
+
+ return new Object[][] { { p2 }, { p3 }, { p4 }, { p5 }, { p6 }, { p7 } };
+ }
+
+ @Test(dataProvider = "parameter", enabled = false)
+ public void testMissingParams(OAuthRequestParameters p) throws Exception {
+ StringBuilder url = new StringBuilder();
+ url.append(OAUTH2_AUTH_URI);
+
+ if (StringUtils.isNotEmpty(p.redirectUri)) OAuth20Util.addParameterToURL(url, "redirect_uri", p.redirectUri);
+ if (StringUtils.isNotEmpty(p.clientId)) OAuth20Util.addParameterToURL(url, "client_id", p.clientId);
+ if (StringUtils.isNotEmpty(p.responseType)) OAuth20Util.addParameterToURL(url, "response_type", p.responseType);
+ if (StringUtils.isNotEmpty(p.scope)) OAuth20Util.addParameterToURL(url, "scope", p.scope);
+ if (StringUtils.isNotEmpty(p.state)) OAuth20Util.addParameterToURL(url, "state", p.state);
+
+ String finalUrl = url.toString();
+ System.out.println("Calling: " + finalUrl);
+
+ HttpClient client = new HttpClient();
+ GetMethod get = new GetMethod(finalUrl);
+ int res = client.executeMethod(get);
+ Assert.assertEquals(res, HttpServletResponse.SC_OK);
+
+ // assert
+
+ if (p.error == null) {
+ Assert.assertFalse(get.getQueryString().contains("error"));
+ // receiver.waitForCode();
+ } else {
+ // check if all error params are returned
+ this.checkParams(get.getQueryString());
+ try {
+ receiver.waitForCode();
+ Assert.assertTrue(false);
+ }
+ catch (Exception e) {
+ Assert.assertEquals(e.getMessage(), p.error);
+ }
+ }
+ }
+
+ @Test(enabled = false)
+ public void testTokenErrorResponse() throws Exception {
+ HttpClient client = new HttpClient();
+ GetMethod get = new GetMethod(OAUTH2_TOKEN_URI + "&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET
+ + "&code=test&grant_type=authorization_code");
+ int res = client.executeMethod(get);
+
+ System.out.println(res);
+ System.out.println(get.getResponseBodyAsString());
+ }
+}
diff --git a/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20GoogleClientTestCase.java b/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20GoogleClientTestCase.java
new file mode 100644
index 000000000..53c7ad496
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20GoogleClientTestCase.java
@@ -0,0 +1,158 @@
+/*******************************************************************************
+ * 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 test.at.gv.egovernment.moa.id.auth.oauth;
+
+import java.awt.Desktop;
+import java.awt.Desktop.Action;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.URI;
+import java.security.SecureRandom;
+import java.util.Arrays;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
+import com.google.api.client.auth.oauth2.AuthorizationCodeRequestUrl;
+import com.google.api.client.auth.oauth2.BearerToken;
+import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
+import com.google.api.client.auth.oauth2.TokenResponse;
+import com.google.api.client.auth.openidconnect.IdToken;
+import com.google.api.client.extensions.java6.auth.oauth2.VerificationCodeReceiver;
+import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
+import com.google.api.client.http.GenericUrl;
+import com.google.api.client.http.HttpExecuteInterceptor;
+import com.google.api.client.http.HttpTransport;
+import com.google.api.client.http.javanet.NetHttpTransport;
+import com.google.api.client.json.JsonFactory;
+import com.google.api.client.json.jackson2.JacksonFactory;
+
+public class OAuth20GoogleClientTestCase {
+
+ final static Logger log = LoggerFactory.getLogger(OAuth20GoogleClientTestCase.class);
+
+ // private static FileDataStoreFactory DATA_STORE_FACTORY;
+
+ // Global instance of the HTTP transport.
+ private static HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
+ // Global instance of the JSON factory.
+ private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
+
+ private static String ISS = "https://localhost/moa-id-auth/";
+
+ // base uri
+ //private static String OAUTH2_BASE_URI = ISS + "dispatcher";
+ // auth action
+ //private static String OAUTH2_AUTH_URI = OAUTH2_BASE_URI + "?mod=id_oauth20&action=AUTH";
+ private static String OAUTH2_AUTH_URI = ISS + "oauth2/auth";
+
+ // token action
+ //private static String OAUTH2_TOKEN_URI = OAUTH2_BASE_URI + "?mod=id_oauth20&action=TOKEN";
+ private static String OAUTH2_TOKEN_URI = ISS + "oauth2/token";
+
+ // client id
+ private static String CLIENT_ID = "http://test";
+ // client secret
+ private static String CLIENT_SECRET = "d435cf0a-3933-48f7-b142-339710c8f070";
+ // OAuth 2.0 scopes
+ private static final List<String> SCOPES = Arrays.asList("profile", "eID", "eID_gov", "mandate");
+
+ // open browser for bku login
+ private void openURL(String url) {
+ Assert.assertNotNull(url);
+ log.info("Please open the following URL in your browser:");
+ log.info(url);
+ if (Desktop.isDesktopSupported()) {
+ Desktop desktop = Desktop.getDesktop();
+ if (desktop.isSupported(Action.BROWSE)) {
+ try {
+ desktop.browse(URI.create(url));
+ return;
+ }
+ catch (IOException e) {
+ // handled below
+ }
+ }
+ }
+
+ }
+
+ private TokenResponse authorize() throws Exception {
+ // set up a receiver for the callback
+ VerificationCodeReceiver receiver = new LocalServerReceiver.Builder().setPort(59542).build();
+
+ // create AuthorizationCodeFlow
+ GenericUrl token_uri = new GenericUrl(OAUTH2_TOKEN_URI);
+ HttpExecuteInterceptor credentials = new ClientParametersAuthentication(CLIENT_ID, CLIENT_SECRET);
+ AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken.queryParameterAccessMethod(), HTTP_TRANSPORT,
+ JSON_FACTORY, token_uri, credentials, CLIENT_ID, OAUTH2_AUTH_URI).setScopes(SCOPES).build();
+ // .setDataStoreFactory(DATA_STORE_FACTORY)
+
+ // create AuthorizationCodeRequestUrl
+ try {
+ String redirectUri = receiver.getRedirectUri();
+ String state = new BigInteger(130, new SecureRandom()).toString(32);
+ AuthorizationCodeRequestUrl authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUri).setState(state);
+
+ // open in browser
+ this.openURL(authorizationUrl.build());
+
+ // receive authorization code and exchange it for an access token
+ String code = receiver.waitForCode();
+ System.out.println(code);
+ TokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
+ return response;
+ }
+ finally {
+ // if anything fails, stop the receiver
+ receiver.stop();
+ }
+
+ }
+
+ // eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJpc3MiOiJodHRwczovL2xvY2FsaG9zdC9tb2EtaWQtYXV0aC8iLCJleHAiOi02MzE5MDMsInN1YiI6IncveThQY2pNTHBFTGZmUHRTSDNtbmd6M24rRVx1MDAzZCIsImJpcnRoZGF0ZSI6IjE5ODUtMDItMDEiLCJmYW1pbHlfbmFtZSI6IkhpZXNzIiwiZ2l2ZW5fbmFtZSI6Ik1pY2hhZWwiLCJpYXQiOi02MzIyMDN9.Z_jveITHlTtktPOOV3n_sMbg50YQ4YcOEcSUs_RJ-4FGedj1sVxk9gmlUQcBPfQaBrPgC6RoiPLTy8CKu2PBClEyv9c9HdzIGqBjWzaTSNASx_QL5bfG4EQ8VZmSEI9d0whzlaBgkUFNfhx-Q2ZVh-g8SJ-0JO0zFR18OSRNTxPTJ4PPl0APqn2H-98sU331_zQKiZxNOvl_6OG26VoIYwEuW5m_N5tsf4lLAlqYcdHR3iNTeu8AkAOvlEwv7Z3BeeOiP4u-OWuc6VusWBPxaI2NwmDIoorpyIxY-wEFb4CWICuyk61Wlq1SCNdl-f-ODwJBK3rlj0IMlYbAjKSB0g
+ private void verifyIdToken(TokenResponse response) throws Exception {
+ String id_token = (String) response.getUnknownKeys().get("id_token");
+ log.info("going to parse id token: {}", id_token);
+
+ IdToken idToken = IdToken.parse(JSON_FACTORY, id_token);
+ Assert.assertTrue(idToken.verifyIssuer(ISS));
+
+ log.info(idToken.getPayload().toPrettyString());
+ log.info(idToken.getHeader().toPrettyString());
+
+ }
+
+ @Test(enabled = false)
+ public void testServerFlow() throws Exception {
+ TokenResponse response = this.authorize();
+ log.info(response.toPrettyString());
+
+ this.verifyIdToken(response);
+ }
+
+}
diff --git a/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20UtilTest.java b/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20UtilTest.java
new file mode 100644
index 000000000..8e18adc08
--- /dev/null
+++ b/id/server/modules/moa-id-module-openID/src/test/java/test/at/gv/egovernment/moa/id/auth/oauth/OAuth20UtilTest.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * 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 test.at.gv.egovernment.moa.id.auth.oauth;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util;
+
+public class OAuth20UtilTest {
+
+ @Test
+ public void validateURL() {
+ Assert.assertTrue(OAuth20Util.isUrl("file:/D:/dev/work/exthex/workspace/OAuthTesting/resources/keys/test_keystore.jks"));
+ Assert.assertTrue(OAuth20Util.isUrl("https://www.google.at/"));
+ Assert.assertTrue(OAuth20Util.isUrl("http://test"));
+ Assert.assertTrue(OAuth20Util.isUrl("http://localhost:59542/Callback"));
+
+
+ Assert.assertFalse(OAuth20Util.isUrl("http://"));
+ Assert.assertFalse(OAuth20Util.isUrl("123http://test"));
+ Assert.assertFalse(OAuth20Util.isUrl("test"));
+ }
+
+ @Test
+ public void validateState() {
+ // check state for invalid characters (like < > & ; ... javascript ... to prevent xss)
+
+ Assert.assertFalse(OAuth20Util.isValidStateValue("javascript"));
+ Assert.assertFalse(OAuth20Util.isValidStateValue("<Test"));
+ Assert.assertFalse(OAuth20Util.isValidStateValue("Test>"));
+ Assert.assertFalse(OAuth20Util.isValidStateValue("Tas<est"));
+ Assert.assertFalse(OAuth20Util.isValidStateValue("Te>st"));
+ Assert.assertFalse(OAuth20Util.isValidStateValue("Tes&t"));
+ Assert.assertFalse(OAuth20Util.isValidStateValue("Tes;t"));
+ Assert.assertTrue(OAuth20Util.isValidStateValue("secure_state"));
+ }
+
+
+ @Test
+ public void testExp() {
+ Pattern urlPattern = Pattern.compile("/oauth2/auth\\?(.*)$", Pattern.CASE_INSENSITIVE);
+ Matcher matcher = urlPattern.matcher("https://localhost/moa-id-auth/oauth2/auth?client_id=http://test&redirect_uri=http://localhost:59542/Callback&response_type=code&scope=profile%20eID%20eID_gov%20mandate&state=7gfnabf112ogg9segnnrfpi83q");
+ System.out.println(matcher.find());
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/pom.xml b/id/server/modules/moa-id-modules-saml1/pom.xml
new file mode 100644
index 000000000..9c43ae277
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/pom.xml
@@ -0,0 +1,44 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>MOA.id.server.modules</groupId>
+ <artifactId>moa-id-modules</artifactId>
+ <version>${moa-id-version}</version>
+ </parent>
+
+ <groupId>MOA.id.server.modules</groupId>
+ <artifactId>moa-id-module-saml1</artifactId>
+ <version>${moa-id-version}</version>
+ <packaging>jar</packaging>
+
+ <name>MOA ID-Module SAML1</name>
+
+ <properties>
+ <repositoryPath>${basedir}/../../../../repository</repositoryPath>
+ </properties>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>MOA.id.server</groupId>
+ <artifactId>moa-id-lib</artifactId>
+ <scope>test</scope>
+ <type>test-jar</type>
+ <version>3.0.3-Snapshot</version>
+ </dependency>
+
+ <dependency>
+ <groupId>MOA</groupId>
+ <artifactId>moa-common</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>MOA.id.server.modules</groupId>
+ <artifactId>moa-id-modul-citizencard_authentication</artifactId>
+ </dependency>
+ </dependencies>
+
+
+</project> \ No newline at end of file
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataAssertionBuilder.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataAssertionBuilder.java
new file mode 100644
index 000000000..fc04fa9a7
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataAssertionBuilder.java
@@ -0,0 +1,458 @@
+/*******************************************************************************
+ * 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.builder;
+
+import java.text.MessageFormat;
+import java.util.Calendar;
+import java.util.List;
+
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.id.data.AuthenticationData;
+import at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DateTimeUtils;
+import at.gv.egovernment.moa.util.StringUtils;
+
+/**
+ * Builder for the authentication data <code>&lt;saml:Assertion&gt;</code>
+ * to be provided by the MOA ID Auth component.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class AuthenticationDataAssertionBuilder extends AuthenticationAssertionBuilder implements Constants {
+
+ /** 5 minutes (=300 seconds) default length of the assertion */
+ private static int DEFAULT_CONDITIONS_LENGTH = 300;
+
+ /** private static String NL contains the NewLine representation in Java*/
+ private static final String NL = "\n";
+ /**
+ * XML template for the <code>&lt;saml:Assertion&gt;</code> to be built
+ */
+ private static final String AUTH_DATA =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + NL +
+ "<saml:Assertion xmlns:saml=''" + SAML_NS_URI + "'' xmlns:pr=''" + PD_NS_URI + "'' xmlns:xsi=''" + XSI_NS_URI + "''" +
+ " xmlns:si=''" + XSI_NS_URI + "''" +
+ " MajorVersion=''1'' MinorVersion=''0'' AssertionID=''{0}'' Issuer=''{1}'' IssueInstant=''{2}''>" + NL +
+ " <saml:AttributeStatement>" + NL +
+ " <saml:Subject>" + NL +
+ " <saml:NameIdentifier NameQualifier=''{3}''>{4}</saml:NameIdentifier>" + NL +
+ " <saml:SubjectConfirmation>" + NL +
+ " <saml:ConfirmationMethod>" + MOA_NS_URI + "cm</saml:ConfirmationMethod>" + NL +
+ " <saml:SubjectConfirmationData>{5}{6}</saml:SubjectConfirmationData>" + NL +
+ " </saml:SubjectConfirmation>" + NL +
+ " </saml:Subject>" + NL +
+ " <saml:Attribute AttributeName=''PersonData'' AttributeNamespace=''" + PD_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{7}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''isQualifiedCertificate'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{8}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''bkuURL'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{9}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ "{10}" +
+ "{11}" +
+ "{12}" +
+ " </saml:AttributeStatement>" + NL +
+ "</saml:Assertion>";
+
+ /**
+ * XML template for the <code>&lt;saml:Assertion&gt;</code> to be built (with Conditions)
+ */
+ private static final String AUTH_DATA_WITH_CONDITIONS =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + NL +
+ "<saml:Assertion xmlns:saml=''" + SAML_NS_URI + "'' xmlns:pr=''" + PD_NS_URI + "'' xmlns:xsi=''" + XSI_NS_URI + "''" +
+ " xmlns:si=''" + XSI_NS_URI + "''" +
+ " MajorVersion=''1'' MinorVersion=''0'' AssertionID=''{0}'' Issuer=''{1}'' IssueInstant=''{2}''>" + NL +
+ "<saml:Conditions NotBefore=''{3}'' NotOnOrAfter=''{4}''/>" + NL +
+ " <saml:AttributeStatement>" + NL +
+ " <saml:Subject>" + NL +
+ " <saml:NameIdentifier NameQualifier=''{5}''>{6}</saml:NameIdentifier>" + NL +
+ " <saml:SubjectConfirmation>" + NL +
+ " <saml:ConfirmationMethod>" + MOA_NS_URI + "cm</saml:ConfirmationMethod>" + NL +
+ " <saml:SubjectConfirmationData>{7}{8}</saml:SubjectConfirmationData>" + NL +
+ " </saml:SubjectConfirmation>" + NL +
+ " </saml:Subject>" + NL +
+ " <saml:Attribute AttributeName=''PersonData'' AttributeNamespace=''" + PD_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{9}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''isQualifiedCertificate'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{10}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''bkuURL'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{11}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ "{12}" +
+ "{13}" +
+ "{14}" +
+ " </saml:AttributeStatement>" + NL +
+ "</saml:Assertion>";
+
+ /**
+ * XML template for the <code>&lt;saml:Assertion&gt;</code> to be built
+ */
+ private static final String AUTH_DATA_MANDATE =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + NL +
+ "<saml:Assertion xmlns:saml=''" + SAML_NS_URI + "'' xmlns:pr=''" + PD_NS_URI + "'' xmlns:xsi=''" + XSI_NS_URI + "''" +
+ " xmlns:si=''" + XSI_NS_URI + "''" +
+ " MajorVersion=''1'' MinorVersion=''0'' AssertionID=''{0}'' Issuer=''{1}'' IssueInstant=''{2}''>" + NL +
+ " <saml:AttributeStatement>" + NL +
+ " <saml:Subject>" + NL +
+ " <saml:NameIdentifier NameQualifier=''{3}''>{4}</saml:NameIdentifier>" + NL +
+ " <saml:SubjectConfirmation>" + NL +
+ " <saml:ConfirmationMethod>" + MOA_NS_URI + "cm</saml:ConfirmationMethod>" + NL +
+ " <saml:SubjectConfirmationData>{5}{6}</saml:SubjectConfirmationData>" + NL +
+ " </saml:SubjectConfirmation>" + NL +
+ " </saml:Subject>" + NL +
+ " <saml:Attribute AttributeName=''PersonData'' AttributeNamespace=''" + PD_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{7}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''MandateData'' AttributeNamespace=''" + PD_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{8}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''isQualifiedCertificate'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{9}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''bkuURL'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{10}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ "{11}" +
+ "{12}" +
+ "{13}" +
+ " </saml:AttributeStatement>" + NL +
+ "</saml:Assertion>";
+
+ /**
+ * XML template for the <code>&lt;saml:Assertion&gt;</code> to be built
+ */
+ private static final String AUTH_DATA_MANDATE_WITH_CONDITIONS =
+ "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + NL +
+ "<saml:Assertion xmlns:saml=''" + SAML_NS_URI + "'' xmlns:pr=''" + PD_NS_URI + "'' xmlns:xsi=''" + XSI_NS_URI + "''" +
+ " xmlns:si=''" + XSI_NS_URI + "''" +
+ " MajorVersion=''1'' MinorVersion=''0'' AssertionID=''{0}'' Issuer=''{1}'' IssueInstant=''{2}''>" + NL +
+ "<saml:Conditions NotBefore=''{3}'' NotOnOrAfter=''{4}''/>" + NL +
+ " <saml:AttributeStatement>" + NL +
+ " <saml:Subject>" + NL +
+ " <saml:NameIdentifier NameQualifier=''{5}''>{6}</saml:NameIdentifier>" + NL +
+ " <saml:SubjectConfirmation>" + NL +
+ " <saml:ConfirmationMethod>" + MOA_NS_URI + "cm</saml:ConfirmationMethod>" + NL +
+ " <saml:SubjectConfirmationData>{7}{8}</saml:SubjectConfirmationData>" + NL +
+ " </saml:SubjectConfirmation>" + NL +
+ " </saml:Subject>" + NL +
+ " <saml:Attribute AttributeName=''PersonData'' AttributeNamespace=''" + PD_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{9}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''MandateData'' AttributeNamespace=''" + PD_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{10}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''isQualifiedCertificate'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{11}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ " <saml:Attribute AttributeName=''bkuURL'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{12}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL +
+ "{13}" +
+ "{14}" +
+ "{15}" +
+ " </saml:AttributeStatement>" + NL +
+ "</saml:Assertion>";
+ /**
+ * XML template for the <code>&lt;saml:Attribute&gt;</code> named <code>"isPublicAuthority"</code>,
+ * to be inserted into the <code>&lt;saml:Assertion&gt;</code>
+ */
+ private static final String PUBLIC_AUTHORITY_ATT =
+ " <saml:Attribute AttributeName=''isPublicAuthority'' AttributeNamespace=''urn:oid:1.2.40.0.10.1.1.1''>" + NL +
+ " <saml:AttributeValue>{0}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL;
+
+ private static final String SIGNER_CERTIFICATE_ATT =
+ " <saml:Attribute AttributeName=''SignerCertificate'' AttributeNamespace=''" + MOA_NS_URI + "''>" + NL +
+ " <saml:AttributeValue>{0}</saml:AttributeValue>" + NL +
+ " </saml:Attribute>" + NL;
+
+ /**
+ * Constructor for AuthenticationDataAssertionBuilder.
+ */
+ public AuthenticationDataAssertionBuilder() {
+ super();
+ }
+
+ /**
+ * Builds the authentication data <code>&lt;saml:Assertion&gt;</code>.
+ *
+ * @param authData the <code>AuthenticationData</code> to build the
+ * <code>&lt;saml:Assertion&gt;</code> from
+ * @param xmlPersonData <code>lt;pr:Person&gt;</code> element as a String
+ * @param xmlAuthBlock authentication block to be included in a
+ * <code>lt;saml:SubjectConfirmationData&gt;</code> element; may include
+ * the <code>"Stammzahl"</code> or not; may be empty
+ * @param xmlIdentityLink the IdentityLink
+ * @param signerCertificateBase64 Base64 encoded certificate of the signer. Maybe
+ * an empty string if the signer certificate should not be provided.
+ * Will be ignored if the <code>businessService</code> parameter is
+ * set to <code>false</code>.
+ * @param businessService <code>true</code> if the online application is a
+ * business service, otherwise <code>false</code>
+ * @return the <code>&lt;saml:Assertion&gt;</code>
+ * @throws BuildException if an error occurs during the build process
+ */
+ public String build(
+ SAML1AuthenticationData authData,
+ String xmlPersonData,
+ String xmlAuthBlock,
+ String xmlIdentityLink,
+ String bkuURL,
+ String signerCertificateBase64,
+ boolean businessService,
+ List<ExtendedSAMLAttribute> extendedSAMLAttributes,
+ boolean useCondition,
+ int conditionLength)
+ throws BuildException
+ {
+
+ String isQualifiedCertificate = authData.isQualifiedCertificate() ? "true" : "false";
+
+ String publicAuthorityAttribute = "";
+ if (authData.isPublicAuthority()) {
+ String publicAuthorityIdentification = authData.getPublicAuthorityCode();
+ if (publicAuthorityIdentification == null)
+ publicAuthorityIdentification = "True";
+ publicAuthorityAttribute = MessageFormat.format(
+ PUBLIC_AUTHORITY_ATT, new Object[] { publicAuthorityIdentification });
+ }
+
+
+ String signerCertificateAttribute = "";
+ if (signerCertificateBase64 != "") {
+ signerCertificateAttribute = MessageFormat.format(
+ SIGNER_CERTIFICATE_ATT, new Object[] { signerCertificateBase64 });
+ }
+
+ String pkType;
+ String pkValue;
+ if (businessService) {
+ pkType = authData.getBPKType();
+ pkValue = authData.getBPK();
+
+ } else {
+ // <saml:NameIdentifier NameQualifier> always has the bPK as type/value
+ pkType = URN_PREFIX_BPK;
+ pkValue = authData.getBPK();
+ }
+
+// System.out.println("pkType; " + pkType);
+// System.out.println("pkValue; " + pkValue);
+
+ String assertion;
+ try {
+
+ if (!useCondition) {
+ assertion = MessageFormat.format(AUTH_DATA, new Object[] {
+ authData.getAssertionID(),
+ authData.getIssuer(),
+ authData.getIssueInstantString(),
+ pkType,
+ pkValue,
+ StringUtils.removeXMLDeclaration(xmlAuthBlock),
+ StringUtils.removeXMLDeclaration(xmlIdentityLink),
+ StringUtils.removeXMLDeclaration(xmlPersonData),
+ isQualifiedCertificate,
+ bkuURL,
+ publicAuthorityAttribute,
+ signerCertificateAttribute,
+ buildExtendedSAMLAttributes(extendedSAMLAttributes)});
+ }
+ else {
+ Calendar cal = Calendar.getInstance();
+ String notBefore = DateTimeUtils.buildDateTimeUTC(cal);
+ if (conditionLength <= 0)
+ cal.add(Calendar.SECOND, DEFAULT_CONDITIONS_LENGTH);
+ else
+ cal.add(Calendar.SECOND, conditionLength);
+
+ String notOnOrAfter = DateTimeUtils.buildDateTimeUTC(cal);
+
+ assertion = MessageFormat.format(AUTH_DATA_WITH_CONDITIONS, new Object[] {
+ authData.getAssertionID(),
+ authData.getIssuer(),
+ authData.getIssueInstantString(),
+ notBefore,
+ notOnOrAfter,
+ pkType,
+ pkValue,
+ StringUtils.removeXMLDeclaration(xmlAuthBlock),
+ StringUtils.removeXMLDeclaration(xmlIdentityLink),
+ StringUtils.removeXMLDeclaration(xmlPersonData),
+ isQualifiedCertificate,
+ bkuURL,
+ publicAuthorityAttribute,
+ signerCertificateAttribute,
+ buildExtendedSAMLAttributes(extendedSAMLAttributes)});
+ }
+
+
+ } catch (ParseException e) {
+ Logger.error("Error on building Authentication Data Assertion: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "Authentication Data Assertion", e.toString()});
+ }
+ return assertion;
+ }
+
+ /**
+ * Builds the authentication data <code>&lt;saml:Assertion&gt;</code>.
+ *
+ * @param authData the <code>AuthenticationData</code> to build the
+ * <code>&lt;saml:Assertion&gt;</code> from
+ * @param xmlPersonData <code>lt;pr:Person&gt;</code> element as a String
+ * @param xmlAuthBlock authentication block to be included in a
+ * <code>lt;saml:SubjectConfirmationData&gt;</code> element; may include
+ * the <code>"Stammzahl"</code> or not; may be empty
+ * @param xmlIdentityLink the IdentityLink
+ * @param signerCertificateBase64 Base64 encoded certificate of the signer. Maybe
+ * an empty string if the signer certificate should not be provided.
+ * Will be ignored if the <code>businessService</code> parameter is
+ * set to <code>false</code>.
+ * @param businessService <code>true</code> if the online application is a
+ * business service, otherwise <code>false</code>
+ * @return the <code>&lt;saml:Assertion&gt;</code>
+ * @throws BuildException if an error occurs during the build process
+ */
+ public String buildMandate(
+ SAML1AuthenticationData authData,
+ String xmlPersonData,
+ String xmlMandateData,
+ String xmlAuthBlock,
+ String xmlIdentityLink,
+ String bkuURL,
+ String signerCertificateBase64,
+ boolean businessService,
+ List<ExtendedSAMLAttribute> extendedSAMLAttributes,
+ boolean useCondition,
+ int conditionLength)
+ throws BuildException
+ {
+
+ String isQualifiedCertificate = authData.isQualifiedCertificate() ? "true" : "false";
+ String publicAuthorityAttribute = "";
+ if (authData.isPublicAuthority()) {
+ String publicAuthorityIdentification = authData.getPublicAuthorityCode();
+ if (publicAuthorityIdentification == null)
+ publicAuthorityIdentification = "True";
+ publicAuthorityAttribute = MessageFormat.format(
+ PUBLIC_AUTHORITY_ATT, new Object[] { publicAuthorityIdentification });
+ }
+
+
+ String signerCertificateAttribute = "";
+ if (signerCertificateBase64 != "") {
+ signerCertificateAttribute = MessageFormat.format(
+ SIGNER_CERTIFICATE_ATT, new Object[] { signerCertificateBase64 });
+ }
+
+ String pkType;
+ String pkValue;
+ if (businessService) {
+ pkType = authData.getBPKType();
+ pkValue = authData.getBPK();
+
+ } else {
+ // <saml:NameIdentifier NameQualifier> always has the bPK as type/value
+ pkType = URN_PREFIX_BPK;
+ pkValue = authData.getBPK();
+ }
+
+// System.out.println("pkType; " + pkType);
+// System.out.println("pkValue; " + pkValue);
+
+ String assertion;
+ try {
+
+
+
+ if (!useCondition) {
+ assertion = MessageFormat.format(AUTH_DATA_MANDATE, new Object[] {
+ authData.getAssertionID(),
+ authData.getIssuer(),
+ authData.getIssueInstantString(),
+ pkType,
+ pkValue,
+ StringUtils.removeXMLDeclaration(xmlAuthBlock),
+ StringUtils.removeXMLDeclaration(xmlIdentityLink),
+ StringUtils.removeXMLDeclaration(xmlPersonData),
+ StringUtils.removeXMLDeclaration(xmlMandateData),
+ isQualifiedCertificate,
+ bkuURL,
+ publicAuthorityAttribute,
+ signerCertificateAttribute,
+ buildExtendedSAMLAttributes(extendedSAMLAttributes)});
+ }
+ else {
+ Calendar cal = Calendar.getInstance();
+ String notBefore = DateTimeUtils.buildDateTimeUTC(cal);
+ if (conditionLength <= 0)
+ cal.add(Calendar.SECOND, DEFAULT_CONDITIONS_LENGTH);
+ else
+ cal.add(Calendar.SECOND, conditionLength);
+
+ String notOnOrAfter = DateTimeUtils.buildDateTimeUTC(cal);
+
+ assertion = MessageFormat.format(AUTH_DATA_MANDATE_WITH_CONDITIONS, new Object[] {
+ authData.getAssertionID(),
+ authData.getIssuer(),
+ authData.getIssueInstantString(),
+ notBefore,
+ notOnOrAfter,
+ pkType,
+ pkValue,
+ StringUtils.removeXMLDeclaration(xmlAuthBlock),
+ StringUtils.removeXMLDeclaration(xmlIdentityLink),
+ StringUtils.removeXMLDeclaration(xmlPersonData),
+ StringUtils.removeXMLDeclaration(xmlMandateData),
+ isQualifiedCertificate,
+ bkuURL,
+ publicAuthorityAttribute,
+ signerCertificateAttribute,
+ buildExtendedSAMLAttributes(extendedSAMLAttributes)});
+ }
+
+
+
+
+
+
+ } catch (ParseException e) {
+ Logger.error("Error on building Authentication Data Assertion: " + e.getMessage());
+ throw new BuildException("builder.00", new Object[] { "Authentication Data Assertion", e.toString()});
+ }
+ return assertion;
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilder.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilder.java
new file mode 100644
index 000000000..eeca78e60
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilder.java
@@ -0,0 +1,167 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.builder;
+
+import java.io.ByteArrayOutputStream;
+import java.security.MessageDigest;
+
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Base64Utils;
+
+/**
+ * Builder for the SAML artifact, as defined in the
+ * Browser/Artifact profile of SAML.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class SAMLArtifactBuilder {
+
+ /**
+ * The generic configuration parameter for an alternative SourceID.
+ */
+// private static final String GENERIC_CONFIG_PARAM_SOURCEID = "AuthenticationServer.SourceID";
+
+ /**
+ * Constructor for SAMLArtifactBuilder.
+ */
+ public SAMLArtifactBuilder() {
+ super();
+ }
+
+ /**
+ * Builds the SAML artifact, encoded BASE64.
+ * <ul>
+ * <li><code>TypeCode</code>: <code>0x0001</code>.</li>
+ * <li><code>SourceID</code>: SHA-1 hash of the authURL</li>
+ * <li><code>AssertionHandle</code>: SHA-1 hash of the <code>MOASessionID</code></li>
+ * </ul>
+ * @param authURL URL auf the MOA-ID Auth component to be used for construction
+ * of <code>SourceID</code>
+ * @param sessionID <code>MOASessionID</code> to be used for construction
+ * of <code>AssertionHandle</code>
+ * @return the 42-byte SAML artifact, encoded BASE64
+ */
+ public String build(String authURL, String sessionID, String sourceIdParam) throws BuildException {
+ try {
+ MessageDigest md = MessageDigest.getInstance("SHA-1");
+ byte[] sourceID;
+ // alternative sourceId
+ String alternativeSourceID = AuthConfigurationProviderFactory.getInstance().getAlternativeSourceID();
+
+ // if sourceID is given in GET/POST param - use this as source id
+ if (!ParepUtils.isEmpty(sourceIdParam)) {
+ // if GET/POST parameter sourceID is set, use that sourceID instead of authURL;
+ //sourceID = md.digest(sourceIdParam.getBytes());
+
+ // if sourceIdParam is too short (must have 20 characters) - add " "
+ int length = sourceIdParam.length();
+ if (length < 20) {
+ int l = 20 - length;
+ for (int i = 0; i < l; i++) {
+ sourceIdParam += " ";
+ }
+ }
+
+ sourceID = sourceIdParam.getBytes();
+ Logger.info("Building SAMArtifact from sourceID \"" + sourceIdParam + "\" instead of authURL \"" + authURL + "\".");
+
+ byte[] assertionHandle = md.digest(sessionID.getBytes());
+ ByteArrayOutputStream out = new ByteArrayOutputStream(42);
+ out.write(0);
+ out.write(1);
+ out.write(sourceID, 0, 20);
+ out.write(assertionHandle, 0, 20);
+ byte[] samlArtifact = out.toByteArray();
+ String samlArtifactBase64 = Base64Utils.encode(samlArtifact);
+ return samlArtifactBase64;
+ }
+
+ // if generic config parameter "AuthenticationServer.SourceID" is given, use that sourceID instead of authURL;
+ if (!ParepUtils.isEmpty(alternativeSourceID)) {
+ sourceID = md.digest(alternativeSourceID.getBytes());
+ Logger.info("Building SAMArtifact from sourceID \"" + alternativeSourceID + "\" instead of authURL \"" + authURL + "\".");
+
+ byte[] assertionHandle = md.digest(sessionID.getBytes());
+ ByteArrayOutputStream out = new ByteArrayOutputStream(42);
+ out.write(0);
+ out.write(1);
+ out.write(sourceID, 0, 20);
+ out.write(assertionHandle, 0, 20);
+ byte[] samlArtifact = out.toByteArray();
+ String samlArtifactBase64 = Base64Utils.encode(samlArtifact);
+ return samlArtifactBase64;
+ }
+
+ // default: sourecID from authURL
+ sourceID = md.digest(authURL.getBytes());
+ byte[] assertionHandle = md.digest(sessionID.getBytes());
+ ByteArrayOutputStream out = new ByteArrayOutputStream(42);
+ out.write(0);
+ out.write(1);
+ out.write(sourceID, 0, 20);
+ out.write(assertionHandle, 0, 20);
+ byte[] samlArtifact = out.toByteArray();
+ String samlArtifactBase64 = Base64Utils.encode(samlArtifact);
+ return samlArtifactBase64;
+
+ //System.out.println("sourceID: " + new String(sourceID));
+
+
+ }
+ catch (Throwable ex) {
+ throw new BuildException(
+ "builder.00",
+ new Object[] {"SAML Artifact, MOASessionID=" + sessionID, ex.toString()},
+ ex);
+ }
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParser.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParser.java
new file mode 100644
index 000000000..0e0b42cde
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParser.java
@@ -0,0 +1,104 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.auth.parser;
+
+import java.io.IOException;
+
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.util.Base64Utils;
+
+/**
+ * Parser for a SAML artifact.
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class SAMLArtifactParser {
+ /** byte array containing the SamlArtifact bytes */
+ private byte[] samlArtifactBytes;
+
+ /**
+ * Constructor
+ * @param samlArtifact as String
+ * @throws ParseException on any parsing error
+ */
+ public SAMLArtifactParser(String samlArtifact) throws ParseException {
+ try {
+ samlArtifactBytes = Base64Utils.decode(samlArtifact, false);
+ }
+ catch (IOException ex) {
+ throw new ParseException("parser.02", new Object[] {ex.toString()}, ex);
+ }
+ }
+ /**
+ * Parses the type code.
+ * @return type code
+ * @throws ParseException when SAML artifact is invalid
+ */
+ public byte[] parseTypeCode() throws ParseException {
+ try {
+ byte[] typeCode = new byte[] {samlArtifactBytes[0], samlArtifactBytes[1]};
+ return typeCode;
+ }
+ catch (Throwable ex) {
+ throw new ParseException("parser.02", new Object[] {ex.toString()}, ex);
+ }
+ }
+ /**
+ * Parses the assertion handle.
+ * @return assertion handle
+ * @throws ParseException when SAML artifact is invalid
+ */
+ public String parseAssertionHandle() throws ParseException {
+ try {
+ return new String(samlArtifactBytes, 22, 20);
+ }
+ catch (Throwable ex) {
+ throw new ParseException("parser.02", new Object[] {ex.toString()}, ex);
+ }
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java
new file mode 100644
index 000000000..d4e73690f
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java
@@ -0,0 +1,141 @@
+/*******************************************************************************
+ * 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.saml1;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
+import at.gv.egovernment.moa.id.auth.servlet.RedirectServlet;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.data.SLOInformationImpl;
+import at.gv.egovernment.moa.id.data.SLOInformationInterface;
+import at.gv.egovernment.moa.id.moduls.IAction;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.URLEncoder;
+
+public class GetArtifactAction implements IAction {
+
+ public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq,
+ HttpServletResponse httpResp, IAuthData obj) throws AuthenticationException {
+
+ String oaURL = (String) req.getOAURL();
+
+ String sourceID = null;
+ if (req instanceof SAML1RequestImpl) {
+ SAML1RequestImpl saml1req = (SAML1RequestImpl) req;
+ sourceID = saml1req.getSourceID();
+
+ }
+
+ SAML1AuthenticationData authData;
+ if (obj instanceof SAML1AuthenticationData) {
+ authData = (SAML1AuthenticationData) obj;
+
+ } else {
+ Logger.error("AuthDate is NOT of type SAML1AuthenticationData.");
+ throw new AuthenticationException("AuthDate is NOT of type SAML1AuthenticationData.", new Object[]{});
+ }
+
+ try {
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(oaURL);
+
+ SAML1AuthenticationServer saml1server = SAML1AuthenticationServer.getInstace();
+
+ // add other stork attributes to MOA assertion if available
+ if(null != authData.getStorkAttributes()) {
+ List<ExtendedSAMLAttribute> moaExtendedSAMLAttibutes = SAML1AuthenticationServer.addAdditionalSTORKAttributes(authData.getStorkAttributes());
+ authData.getExtendedSAMLAttributesOA().addAll(moaExtendedSAMLAttibutes);
+ Logger.info("MOA assertion assembled and SAML Artifact generated.");
+ }
+
+ String samlArtifactBase64 = saml1server.BuildSAMLArtifact(oaParam, authData, sourceID);
+
+ if (authData.isSsoSession()) {
+ String url = req.getAuthURL() + "/RedirectServlet";
+ url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(oaURL, "UTF-8"));
+ if (!oaParam.getBusinessService())
+ url = addURLParameter(url, MOAIDAuthConstants.PARAM_TARGET, URLEncoder.encode(req.getTarget(), "UTF-8"));
+ url = addURLParameter(url, MOAIDAuthConstants.PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8"));
+ url = httpResp.encodeRedirectURL(url);
+
+ httpResp.setContentType("text/html");
+ httpResp.setStatus(302);
+ httpResp.addHeader("Location", url);
+
+ } else {
+ String redirectURL = oaURL;
+ if (!oaParam.getBusinessService()) {
+ redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_TARGET,
+ URLEncoder.encode(req.getTarget(), "UTF-8"));
+
+ }
+
+ redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SAMLARTIFACT,
+ URLEncoder.encode(samlArtifactBase64, "UTF-8"));
+ redirectURL = httpResp.encodeRedirectURL(redirectURL);
+ httpResp.setContentType("text/html");
+ httpResp.setStatus(302);
+ httpResp.addHeader("Location", redirectURL);
+ Logger.debug("REDIRECT TO: " + redirectURL);
+ }
+
+ SLOInformationInterface sloInformation =
+ new SLOInformationImpl(req.getAuthURL(), authData.getAssertionID(), null, null, req.requestedModule());
+
+ return sloInformation;
+
+ } catch (Exception ex) {
+ Logger.error("SAML1 Assertion build error", ex);
+ throw new AuthenticationException("SAML1 Assertion build error.", new Object[]{}, ex);
+ }
+
+ }
+
+ 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;
+ }
+
+ public boolean needAuthentication(IRequest req, HttpServletRequest httpReq,
+ HttpServletResponse httpResp) {
+ return true;
+ }
+
+ public String getDefaultActionName() {
+ return SAML1Protocol.GETARTIFACT;
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java
new file mode 100644
index 000000000..2b4aaf458
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java
@@ -0,0 +1,213 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.protocols.saml1;
+
+import java.util.Calendar;
+
+import org.apache.axis.AxisFault;
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import at.gv.egovernment.moa.id.auth.builder.SAMLResponseBuilder;
+import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.util.ErrorResponseUtils;
+import at.gv.egovernment.moa.id.util.MOAIDMessageProvider;
+import at.gv.egovernment.moa.id.util.Random;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DOMUtils;
+import at.gv.egovernment.moa.util.DateTimeUtils;
+import at.gv.egovernment.moa.util.XPathUtils;
+
+/**
+ * Web service for picking up authentication data created in the MOA-ID Auth component.
+ *
+ * @author Paul Ivancsics
+ * @version $Id: GetAuthenticationDataService.java 1233 2012-01-26 21:59:33Z kstranacher $
+ * @see at.gv.egovernment.moa.id.auth.AuthenticationServer#getAuthenticationData
+ */
+public class GetAuthenticationDataService implements Constants {
+
+ /**
+ * Constructor for GetAuthenticationDataService.
+ */
+ public GetAuthenticationDataService() {
+ super();
+ }
+
+ /**
+ * Takes a <code>lt;samlp:Request&gt;</code> containing a
+ * <code>SAML artifact</code> and returns the corresponding
+ * authentication data <code>lt;saml:Assertion&gt;</code>
+ * (obtained from the <code>AuthenticationServer</code>),
+ * enclosed in a <code>lt;samlp:Response&gt;</code>.
+ * <br/>Bad requests are mapped into various <code>lt;samlp:StatusCode&gt;</code>s,
+ * possibly containing enclosed sub-<code>lt;samlp:StatusCode&gt;</code>s.
+ * The status codes are defined in the SAML specification.
+ *
+ * @param requests request elements of type <code>lt;samlp:Request&gt;</code>;
+ * only 1 request element is allowed
+ * @return response element of type <code>lt;samlp:Response&gt;</code>,
+ * packed into an <code>Element[]</code>
+ * @throws AxisFault thrown when an error occurs in assembling the
+ * <code>lt;samlp:Response&gt;</code>
+ */
+ public Element[] Request(Element[] requests)
+ throws AxisFault {
+
+ Element request = requests[0];
+ Element[] responses = new Element[1];
+ String requestID = "";
+ String statusCode = "";
+ String subStatusCode = null;
+ String statusMessageCode = null;
+ String statusMessage = null;
+ String samlAssertion = "";
+ if (requests.length > 1) {
+ // more than 1 request given as parameter
+ statusCode = "samlp:Requester";
+ subStatusCode = "samlp:TooManyResponses";
+ statusMessageCode = "1201";
+ }
+ else {
+ try {
+ DOMUtils.validateElement(request, ALL_SCHEMA_LOCATIONS, null);
+ NodeList samlArtifactList = XPathUtils.selectNodeList(request, "samlp:AssertionArtifact");
+ if (samlArtifactList.getLength() == 0) {
+ // no SAML artifact given in request
+ statusCode = "samlp:Requester";
+ statusMessageCode = "1202";
+ }
+ else if (samlArtifactList.getLength() > 1) {
+ // too many SAML artifacts given in request
+ statusCode = "samlp:Requester";
+ subStatusCode = "samlp:TooManyResponses";
+ statusMessageCode = "1203";
+ }
+
+ else {
+ Element samlArtifactElem = (Element)samlArtifactList.item(0);
+ requestID = request.getAttribute("RequestID");
+ String samlArtifact = DOMUtils.getText(samlArtifactElem);
+ SAML1AuthenticationServer saml1server = SAML1AuthenticationServer.getInstace();
+
+ try {
+
+ samlAssertion = saml1server.getSaml1AuthenticationData(samlArtifact);
+
+ // success
+ statusCode = "samlp:Success";
+ statusMessageCode = "1200";
+ }
+
+ catch (ClassCastException ex) {
+
+ try {
+ Throwable error = saml1server.getErrorResponse(samlArtifact);
+ statusCode = "samlp:Responder";
+
+ ErrorResponseUtils errorUtils = ErrorResponseUtils.getInstance();
+
+ if (error instanceof MOAIDException) {
+ statusMessageCode = ((MOAIDException)error).getMessageId();
+ statusMessage = StringEscapeUtils.escapeXml(((MOAIDException)error).getMessage());
+
+ } else {
+ statusMessage = StringEscapeUtils.escapeXml(error.getMessage());
+ }
+ subStatusCode = errorUtils.getResponseErrorCode(error);
+
+ } catch (Exception e) {
+ //no authentication data for given SAML artifact
+ statusCode = "samlp:Requester";
+ subStatusCode = "samlp:ResourceNotRecognized";
+ statusMessage = ex.toString();
+ }
+
+ }
+
+ catch (AuthenticationException ex) {
+ //no authentication data for given SAML artifact
+ statusCode = "samlp:Requester";
+ subStatusCode = "samlp:ResourceNotRecognized";
+ statusMessage = ex.toString();
+ }
+ }
+ }
+ catch (Throwable t) {
+ // invalid request format
+ statusCode = "samlp:Requester";
+ statusMessageCode = "1204";
+ }
+ }
+
+ try {
+ String responseID = Random.nextRandom();
+ String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar.getInstance());
+
+ if (statusMessage == null)
+ statusMessage = MOAIDMessageProvider.getInstance().getMessage(statusMessageCode, null);
+ responses[0] = new SAMLResponseBuilder().build(
+ responseID, requestID, issueInstant, statusCode, subStatusCode, statusMessage, samlAssertion);
+
+ }
+ catch (MOAIDException e) {
+ AxisFault fault = AxisFault.makeFault(e);
+ fault.setFaultDetail(new Element[] { e.toErrorResponse()});
+ throw fault;
+ }
+ catch (Throwable t) {
+ MOAIDException e = new MOAIDException("1299", null, t);
+ AxisFault fault = AxisFault.makeFault(e);
+ fault.setFaultDetail(new Element[] { e.toErrorResponse()});
+ throw fault;
+ }
+ return responses;
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationData.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationData.java
new file mode 100644
index 000000000..d48c0a9bb
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationData.java
@@ -0,0 +1,177 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package at.gv.egovernment.moa.id.protocols.saml1;
+
+import java.text.ParseException;
+import java.util.List;
+
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.data.AuthenticationData;
+import at.gv.egovernment.moa.id.util.Random;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.DateTimeUtils;
+
+/**
+ * Encapsulates authentication data contained in a <code>&lt;saml:Assertion&gt;</code>.
+ *
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+
+public class SAML1AuthenticationData extends AuthenticationData {
+ /**
+ *
+ */
+ private static final long serialVersionUID = -1042697056735596866L;
+/**
+ * major version number of the SAML assertion
+ */
+ private int majorVersion;
+ /**
+ * minor version number of the SAML assertion
+ */
+ private int minorVersion;
+ /**
+ * identifier for this assertion
+ */
+ private String assertionID;
+/**
+ * @return the majorVersion
+ */
+
+ private String samlAssertion = null;
+
+ private List<ExtendedSAMLAttribute> extendedSAMLAttributesOA;
+
+
+ public SAML1AuthenticationData() {
+ this.setMajorVersion(1);
+ this.setMinorVersion(0);
+ this.setAssertionID(Random.nextRandom());
+ }
+
+
+ //this method is only required for MOA-ID Proxy 2.0 Release.
+ //TODO: remove it, if MOA-ID Proxy is not supported anymore.
+ public String getWBPK() {
+ return getBPK();
+ }
+
+public int getMajorVersion() {
+ return majorVersion;
+}
+/**
+ * @param majorVersion the majorVersion to set
+ */
+public void setMajorVersion(int majorVersion) {
+ this.majorVersion = majorVersion;
+}
+/**
+ * @return the minorVersion
+ */
+public int getMinorVersion() {
+ return minorVersion;
+}
+/**
+ * @param minorVersion the minorVersion to set
+ */
+public void setMinorVersion(int minorVersion) {
+ this.minorVersion = minorVersion;
+}
+/**
+ * @return the assertionID
+ */
+public String getAssertionID() {
+ return assertionID;
+}
+/**
+ * @param assertionID the assertionID to set
+ */
+public void setAssertionID(String assertionID) {
+ this.assertionID = assertionID;
+}
+
+public void setIssueInstant(String date) {
+ try {
+ setIssueInstant(DateTimeUtils.parseDateTime(date));
+
+ } catch (ParseException e) {
+ Logger.error("Parse IssueInstant element FAILED.", e);
+
+ }
+}
+
+/**
+ * @return the samlAssertion
+ */
+public String getSamlAssertion() {
+ return samlAssertion;
+}
+
+/**
+ * @param samlAssertion the samlAssertion to set
+ */
+public void setSamlAssertion(String samlAssertion) {
+ this.samlAssertion = samlAssertion;
+}
+
+/**
+ * @return the extendedSAMLAttributesOA
+ */
+public List<ExtendedSAMLAttribute> getExtendedSAMLAttributesOA() {
+ return extendedSAMLAttributesOA;
+}
+
+/**
+ * @param extendedSAMLAttributesOA the extendedSAMLAttributesOA to set
+ */
+public void setExtendedSAMLAttributesOA(
+ List<ExtendedSAMLAttribute> extendedSAMLAttributesOA) {
+ this.extendedSAMLAttributesOA = extendedSAMLAttributesOA;
+}
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java
new file mode 100644
index 000000000..eb869756e
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java
@@ -0,0 +1,635 @@
+/*******************************************************************************
+ * 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.saml1;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.Vector;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.Marshaller;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.TransformerException;
+
+import org.apache.commons.lang3.StringEscapeUtils;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
+import eu.stork.peps.auth.commons.PersonalAttribute;
+
+import at.gv.egovernment.moa.id.auth.AuthenticationServer;
+import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataAssertionBuilder;
+import at.gv.egovernment.moa.id.auth.builder.BPKBuilder;
+import at.gv.egovernment.moa.id.auth.builder.PersonDataBuilder;
+import at.gv.egovernment.moa.id.auth.builder.SAMLArtifactBuilder;
+import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttributeImpl;
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+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.exception.ValidateException;
+import at.gv.egovernment.moa.id.auth.parser.SAMLArtifactParser;
+import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils;
+import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters;
+import at.gv.egovernment.moa.id.data.AuthenticationData;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.storage.AssertionStorage;
+//import at.gv.egovernment.moa.id.util.IdentityLinkReSigner;
+import at.gv.egovernment.moa.id.util.Random;
+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;
+import at.gv.util.xsd.persondata.PersonNameType;
+import at.gv.util.xsd.persondata.PersonNameType.FamilyName;
+import at.gv.util.xsd.persondata.PhysicalPersonType;
+
+public class SAML1AuthenticationServer extends AuthenticationServer {
+
+ private static SAML1AuthenticationServer instance;
+
+ public static SAML1AuthenticationServer getInstace() {
+ if (instance == null)
+ instance = new SAML1AuthenticationServer();
+
+ return instance;
+ }
+
+ private static AssertionStorage authenticationDataStore = AssertionStorage.getInstance();
+
+
+ /**
+ * time out in milliseconds used by {@link cleanup} for authentication data
+ * store
+ */
+ private static final long authDataTimeOut = 2 * 60 * 1000; // default 2 minutes
+
+
+ public Throwable getErrorResponse(String samlArtifact) throws AuthenticationException {
+ try {
+ new SAMLArtifactParser(samlArtifact).parseAssertionHandle();
+
+ } catch (ParseException ex) {
+ throw new AuthenticationException("1205", new Object[] {
+ samlArtifact, ex.toString() });
+ }
+ Throwable error = null;
+ synchronized (authenticationDataStore) {
+ try {
+ error = authenticationDataStore
+ .get(samlArtifact, Throwable.class);
+
+ authenticationDataStore.remove(samlArtifact);
+
+ } catch (MOADatabaseException e) {
+ Logger.error("Assertion not found for SAML Artifact: " + samlArtifact);
+ throw new AuthenticationException("1206", new Object[] { samlArtifact });
+ }
+
+ }
+
+ return error;
+ }
+
+ /**
+ * Transforms additional STORK attributes to MOA Extended attributes
+ * @param iPersonalAttributeList STORK attribute list
+ * @return
+ */
+ public static List<ExtendedSAMLAttribute> addAdditionalSTORKAttributes(IPersonalAttributeList iPersonalAttributeList) {
+ List<ExtendedSAMLAttribute> moaExtendedSAMLAttributeList = new Vector<ExtendedSAMLAttribute>();
+
+ if(null == iPersonalAttributeList)
+ return moaExtendedSAMLAttributeList;
+
+ Logger.trace("Adding the following attributes to MOA assertion: ");
+ int count = 0;
+
+ for (PersonalAttribute attribute : iPersonalAttributeList) {
+ 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);
+ count++;
+ Logger.trace("Additional attribute: " + attribute.getName());
+ }
+
+ Logger.debug("Added " + count + " STORK attribute(s) to the MOA assertion.");
+
+ return moaExtendedSAMLAttributeList;
+ }
+
+
+ /**
+ * Retrieves <code>AuthenticationData</code> indexed by the SAML artifact.
+ * The <code>AuthenticationData</code> is deleted from the store upon end of
+ * this call.
+ *
+ * @return <code>AuthenticationData</code>
+ */
+ public String getSaml1AuthenticationData(String samlArtifact)
+ throws AuthenticationException {
+ try {
+ new SAMLArtifactParser(samlArtifact).parseAssertionHandle();
+
+ } catch (ParseException ex) {
+ throw new AuthenticationException("1205", new Object[] {
+ samlArtifact, ex.toString() });
+ }
+ String authData = null;
+ synchronized (authenticationDataStore) {
+ // System.out.println("assertionHandle: " + assertionHandle);
+
+ try {
+ authData = authenticationDataStore
+ .get(samlArtifact, String.class, authDataTimeOut);
+
+ } catch (MOADatabaseException e) {
+ Logger.error("Assertion not found for SAML Artifact: " + samlArtifact);
+ throw new AuthenticationException("1206", new Object[] { samlArtifact });
+ }
+ }
+
+ authenticationDataStore.remove(samlArtifact);
+
+ Logger.debug("Assertion delivered for SAML Artifact: " + samlArtifact);
+
+ return authData;
+ }
+
+ public String BuildErrorAssertion(Throwable error, IRequest protocolRequest)
+ throws BuildException, MOADatabaseException {
+
+ String samlArtifact = new SAMLArtifactBuilder().build(
+ protocolRequest.getOAURL(), protocolRequest.getRequestID(),
+ null);
+
+ authenticationDataStore.put(samlArtifact, error);
+
+ return samlArtifact;
+ }
+
+ public String BuildSAMLArtifact(OAAuthParameter oaParam,
+ SAML1AuthenticationData authData, String sourceID)
+ throws ConfigurationException, BuildException, AuthenticationException {
+
+ //Load SAML1 Parameter from OA config
+ SAML1ConfigurationParameters saml1parameter = oaParam.getSAML1Parameter();
+
+ boolean useCondition = saml1parameter.isUseCondition();
+ int conditionLength = saml1parameter.getConditionLength();
+
+ try {
+
+ //set BASE64 encoded signer certificate
+ String signerCertificateBase64 = "";
+ if (saml1parameter.isProvideCertificate()) {
+ byte[] signerCertificate = authData.getSignerCertificate();
+ if (signerCertificate != null) {
+
+ signerCertificateBase64 = Base64Utils
+ .encode(signerCertificate);
+ } else {
+ Logger.info("\"provideCertificate\" is \"true\", but no signer certificate available");
+ }
+ }
+
+ //set prPersion
+ boolean provideStammzahl = saml1parameter.isProvideStammzahl()
+ || oaParam.getBusinessService();
+
+ String prPerson = "";
+ String ilAssertion = "";
+ if (authData.getIdentityLink() != null) {
+ prPerson = new PersonDataBuilder().build(authData.getIdentityLink(),
+ provideStammzahl);
+
+ //set IdentityLink for assortion
+ if (saml1parameter.isProvideIdentityLink()) {
+ ilAssertion = authData.getIdentityLink().getSerializedSamlAssertion();
+
+ if (!provideStammzahl)
+ ilAssertion = StringUtils.replaceAll(ilAssertion, authData.getIdentityLink()
+ .getIdentificationValue(), "");
+ }
+ } else {
+ Logger.info("No IdentityLink available! Build attribute 'PersonDate' from givenname, familyname and dateofbirth. ");
+ PhysicalPersonType person = new PhysicalPersonType();
+ PersonNameType name = new PersonNameType();
+ person.setName(name);
+ FamilyName familyName = new FamilyName();
+ name.getFamilyName().add(familyName );
+ IdentificationType id = new IdentificationType();
+ person.getIdentification().add(id );
+ Value value = new Value();
+ id.setValue(value );
+
+ 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());
+ person.setDateOfBirth(authData.getFormatedDateOfBirth());
+
+ JAXBContext jc = JAXBContext.newInstance("at.gv.util.xsd.persondata");
+ Marshaller m = jc.createMarshaller();
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
+
+// m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new NamespacePrefixMapper() {
+// public String getPreferredPrefix(String arg0, String arg1, boolean arg2) {
+// if (Constants.PD_NS_URI.equals(arg0))
+// return Constants.PD_PREFIX;
+// else
+// return arg1;
+// }
+// });
+
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ m.marshal(
+ new JAXBElement<PhysicalPersonType>(new QName(Constants.PD_NS_URI,"Person"), PhysicalPersonType.class, person),
+ stream);
+ prPerson = StringUtils.removeXMLDeclaration(new String(stream.toByteArray(), "UTF-8"));
+ stream.close();
+
+
+
+ }
+
+ //set Authblock
+ String authBlock = "";
+ if (authData.getAuthBlock() != null) {
+ authBlock = saml1parameter.isProvideAUTHBlock() ? authData.getAuthBlock() : "";
+
+ } else {
+ Logger.info("\"provideAuthBlock\" is \"true\", but no authblock available");
+
+ }
+
+ String samlAssertion;
+ if (authData.isUseMandate()) {
+ List<ExtendedSAMLAttribute> oaAttributes = authData.getExtendedSAMLAttributesOA();
+
+ //only provide full mandate if it is included.
+ //In case of federation only a short mandate could be include
+ if (saml1parameter.isProvideFullMandatorData()
+ && authData.getMISMandate().isFullMandateIncluded()) {
+
+ try {
+
+ ExtendedSAMLAttribute[] extendedSAMLAttributes = addExtendedSamlAttributes(
+ authData.getMISMandate(), oaParam.getBusinessService(),
+ saml1parameter.isProvideStammzahl());
+
+ if (extendedSAMLAttributes != null) {
+
+ String identifier = "MISService";
+ String friendlyName ="MISService";
+
+ int length = extendedSAMLAttributes.length;
+ for (int i = 0; i < length; i++) {
+ ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i];
+
+ Object value = verifySAMLAttribute(samlAttribute, i, identifier,
+ friendlyName);
+
+ if ((value instanceof String) || (value instanceof Element)) {
+ switch (samlAttribute.getAddToAUTHBlock()) {
+ case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK:
+ replaceExtendedSAMLAttribute(oaAttributes, samlAttribute);
+ break;
+ case ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK:
+ replaceExtendedSAMLAttribute(oaAttributes, samlAttribute);
+ break;
+ case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY:
+ break;
+ default:
+ Logger
+ .info("Invalid return value from method \"getAddToAUTHBlock()\" ("
+ + samlAttribute.getAddToAUTHBlock()
+ + ") in SAML attribute number "
+ + (i + 1)
+ + " for infobox " + identifier);
+ throw new ValidateException("validator.47", new Object[] {
+ friendlyName, String.valueOf((i + 1)) });
+ }
+ } else {
+ Logger
+ .info("The type of SAML-Attribute number "
+ + (i + 1)
+ + " returned from "
+ + identifier
+ + "-infobox validator is not valid. Must be either \"java.Lang.String\""
+ + " or \"org.w3c.dom.Element\"");
+ throw new ValidateException("validator.46", new Object[] {
+ identifier, String.valueOf((i + 1)) });
+ }
+ }
+ }
+
+ } catch (SAXException e) {
+ throw new AuthenticationException("auth.16",
+ new Object[] { GET_MIS_SESSIONID }, e);
+ } catch (IOException e) {
+ throw new AuthenticationException("auth.16",
+ new Object[] { GET_MIS_SESSIONID }, e);
+ } catch (ParserConfigurationException e) {
+ throw new AuthenticationException("auth.16",
+ new Object[] { GET_MIS_SESSIONID }, e);
+ } catch (TransformerException e) {
+ throw new AuthenticationException("auth.16",
+ new Object[] { GET_MIS_SESSIONID }, e);
+ }
+ }
+
+ String mandateDate = generateMandateDate(oaParam, authData);
+
+ samlAssertion = new AuthenticationDataAssertionBuilder().buildMandate(
+ authData,
+ prPerson,
+ mandateDate,
+ authBlock,
+ ilAssertion,
+ authData.getBkuURL(),
+ signerCertificateBase64,
+ oaParam.getBusinessService(),
+ oaAttributes,
+ useCondition,
+ conditionLength);
+
+ } else {
+ samlAssertion = new AuthenticationDataAssertionBuilder().build(
+ authData,
+ prPerson,
+ authBlock,
+ ilAssertion,
+ authData.getBkuURL(),
+ signerCertificateBase64,
+ oaParam.getBusinessService(),
+ authData.getExtendedSAMLAttributesOA(),
+ useCondition,
+ conditionLength);
+ }
+
+ //authData.setSamlAssertion(samlAssertion);
+
+ String samlArtifact = new SAMLArtifactBuilder().build(
+ authData.getIssuer(), Random.nextRandom(),
+ sourceID);
+
+ storeAuthenticationData(samlArtifact, samlAssertion);
+
+ Logger.info("Anmeldedaten angelegt, SAML Artifakt " + samlArtifact);
+ return samlArtifact;
+
+ } catch (Throwable ex) {
+ throw new BuildException("builder.00", new Object[] {
+ "AuthenticationData", ex.toString() }, ex);
+ }
+
+ }
+
+ private String generateMandateDate(OAAuthParameter oaParam, AuthenticationData authData
+ ) throws AuthenticationException, BuildException,
+ ParseException, ConfigurationException, ServiceException,
+ ValidateException {
+
+ if (authData == null)
+ throw new AuthenticationException("auth.10", new Object[] {
+ REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID });
+
+ IdentityLink tempIdentityLink = null;
+
+ Element mandate = authData.getMandate();
+
+ if (authData.isUseMandate()) {
+ tempIdentityLink = new IdentityLink();
+ Element mandator = ParepUtils.extractMandator(mandate);
+ String dateOfBirth = "";
+ Element prPerson = null;
+ String familyName = "";
+ String givenName = "";
+ String identificationType = "";
+ String identificationValue = "";
+ if (mandator != null) {
+ boolean physical = ParepUtils.isPhysicalPerson(mandator);
+ if (physical) {
+ familyName = ParepUtils.extractText(mandator,
+ "descendant-or-self::pr:Name/pr:FamilyName/text()");
+ givenName = ParepUtils.extractText(mandator,
+ "descendant-or-self::pr:Name/pr:GivenName/text()");
+ dateOfBirth = ParepUtils
+ .extractMandatorDateOfBirth(mandator);
+ } else {
+ familyName = ParepUtils.extractMandatorFullName(mandator);
+ }
+ identificationType = ParepUtils.getIdentification(mandator,
+ "Type");
+ identificationValue = ParepUtils.extractMandatorWbpk(mandator);
+
+ prPerson = ParepUtils.extractPrPersonOfMandate(mandate);
+ if (physical
+ && oaParam.getBusinessService()
+ && identificationType != null
+ && Constants.URN_PREFIX_BASEID
+ .equals(identificationType)) {
+ // now we calculate the wbPK and do so if we got it from the
+ // BKU
+
+
+ //load IdentityLinkDomainType from OAParam
+ String type = oaParam.getIdentityLinkDomainIdentifier();
+ if (type.startsWith(Constants.URN_PREFIX_WBPK + "+"))
+ identificationType = type;
+ else
+ identificationType = Constants.URN_PREFIX_WBPK + "+"
+ + type;
+
+
+ identificationValue = new BPKBuilder().buildWBPK(
+ identificationValue, identificationType);
+ ParepUtils
+ .HideStammZahlen(prPerson, true, null, null, true);
+ }
+
+ tempIdentityLink.setDateOfBirth(dateOfBirth);
+ tempIdentityLink.setFamilyName(familyName);
+ tempIdentityLink.setGivenName(givenName);
+ tempIdentityLink.setIdentificationType(identificationType);
+ tempIdentityLink.setIdentificationValue(identificationValue);
+ tempIdentityLink.setPrPerson(prPerson);
+ try {
+ tempIdentityLink.setSamlAssertion(authData.getIdentityLink()
+ .getSamlAssertion());
+ } catch (Exception e) {
+ throw new ValidateException("validator.64", null);
+ }
+
+ }
+
+ }
+
+ Element mandatePerson = tempIdentityLink.getPrPerson();
+
+ String mandateData = null;
+ try {
+
+ boolean provideStammzahl = oaParam.getSAML1Parameter().isProvideStammzahl();
+
+ String oatargetType;
+
+ if(oaParam.getBusinessService()) {
+ if (oaParam.getIdentityLinkDomainIdentifier().startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
+ oatargetType = oaParam.getIdentityLinkDomainIdentifier();
+ else
+ oatargetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_+oaParam.getIdentityLinkDomainIdentifier();
+
+ } else {
+ oatargetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
+ }
+
+ Element prIdentification = (Element) mandatePerson
+ .getElementsByTagNameNS(Constants.PD_NS_URI,
+ "Identification").item(0);
+
+ if (!oatargetType.equals(tempIdentityLink.getIdentificationType())) {
+
+ String isPrPerson = mandatePerson.getAttribute("xsi:type");
+
+ if (!StringUtils.isEmpty(isPrPerson)) {
+ if (isPrPerson.equalsIgnoreCase("pr:PhysicalPerson")) {
+ String baseid = getBaseId(mandatePerson);
+ Element identificationBpK = createIdentificationBPK(mandatePerson,
+ baseid, oaParam.getTarget());
+
+ if (!provideStammzahl) {
+ prIdentification.getFirstChild().setTextContent("");
+ }
+
+ mandatePerson.insertBefore(identificationBpK,
+ prIdentification);
+ }
+ }
+
+ } else {
+
+// Element identificationBpK = mandatePerson.getOwnerDocument()
+// .createElementNS(Constants.PD_NS_URI, "Identification");
+// Element valueBpK = mandatePerson.getOwnerDocument().createElementNS(
+// Constants.PD_NS_URI, "Value");
+//
+// valueBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode(
+// tempIdentityLink.getIdentificationValue()));
+// Element typeBpK = mandatePerson.getOwnerDocument().createElementNS(
+// Constants.PD_NS_URI, "Type");
+// typeBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode(
+// "urn:publicid:gv.at:cdid+bpk"));
+// identificationBpK.appendChild(valueBpK);
+// identificationBpK.appendChild(typeBpK);
+//
+// mandatePerson.insertBefore(identificationBpK, prIdentification);
+ }
+
+
+ mandateData = DOMUtils.serializeNode(mandatePerson);
+
+ } catch (TransformerException e1) {
+ throw new AuthenticationException("auth.16",
+ new Object[] { GET_MIS_SESSIONID });
+ } catch (IOException e1) {
+ throw new AuthenticationException("auth.16",
+ new Object[] { GET_MIS_SESSIONID });
+ }
+
+ return mandateData;
+ }
+
+
+
+
+ /**
+ * Stores authentication data indexed by the assertion handle contained in
+ * the given saml artifact.
+ *
+ * @param samlArtifact
+ * SAML artifact
+ * @param authData
+ * authentication data
+ * @throws AuthenticationException
+ * when SAML artifact is invalid
+ */
+ private void storeAuthenticationData(String samlArtifact,
+ String samlAssertion) throws AuthenticationException {
+
+ try {
+ SAMLArtifactParser parser = new SAMLArtifactParser(samlArtifact);
+ // check type code 0x0001
+ byte[] typeCode = parser.parseTypeCode();
+ if (typeCode[0] != 0 || typeCode[1] != 1)
+ throw new AuthenticationException("auth.06",
+ new Object[] { samlArtifact });
+ parser.parseAssertionHandle();
+
+ synchronized (authenticationDataStore) {
+ Logger.debug("Assertion stored for SAML Artifact: "
+ + samlArtifact);
+ authenticationDataStore.put(samlArtifact, samlAssertion);
+ }
+
+ } catch (AuthenticationException ex) {
+ throw ex;
+
+ } catch (Throwable ex) {
+ throw new AuthenticationException("auth.06",
+ new Object[] { samlArtifact });
+ }
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java
new file mode 100644
index 000000000..ddd1f1394
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java
@@ -0,0 +1,226 @@
+/*******************************************************************************
+ * 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.saml1;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.StringEscapeUtils;
+
+import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
+import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
+import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException;
+import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
+import at.gv.egovernment.moa.id.auth.servlet.RedirectServlet;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters;
+import at.gv.egovernment.moa.id.moduls.IAction;
+import at.gv.egovernment.moa.id.moduls.IModulInfo;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.MiscUtil;
+import at.gv.egovernment.moa.util.URLEncoder;
+
+public class SAML1Protocol extends MOAIDAuthConstants implements IModulInfo {
+
+ public static final String NAME = SAML1Protocol.class.getName();
+ public static final String PATH = "id_saml1";
+
+ public static final String GETARTIFACT = "GetArtifact";
+
+ public static final List<String> DEFAULTREQUESTEDATTRFORINTERFEDERATION = Arrays.asList(
+ new String[] {
+ PVPConstants.BPK_NAME,
+ PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME,
+ PVPConstants.GIVEN_NAME_NAME,
+ PVPConstants.PRINCIPAL_NAME_NAME,
+ PVPConstants.BIRTHDATE_NAME,
+ PVPConstants.EID_CCS_URL_NAME,
+ PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME,
+ PVPConstants.EID_IDENTITY_LINK_NAME,
+ PVPConstants.EID_SOURCE_PIN_NAME,
+ PVPConstants.EID_SOURCE_PIN_TYPE_NAME
+ });
+
+ private static HashMap<String, IAction> actions = new HashMap<String, IAction>();
+
+ static {
+
+ actions.put(GETARTIFACT, new GetArtifactAction());
+
+ instance = new SAML1Protocol();
+ }
+
+ private static SAML1Protocol instance = null;
+
+ public static SAML1Protocol getInstance() {
+ if (instance == null) {
+ instance = new SAML1Protocol();
+ }
+ return instance;
+ }
+
+ public String getName() {
+ return NAME;
+ }
+
+ public String getPath() {
+ return PATH;
+ }
+
+ public IRequest preProcess(HttpServletRequest request,
+ HttpServletResponse response, String action,
+ String sessionId, String transactionId) throws MOAIDException {
+ SAML1RequestImpl config = new SAML1RequestImpl(request);
+
+ if (!AuthConfigurationProviderFactory.getInstance().getAllowedProtocols().isSAML1Active()) {
+ Logger.info("SAML1 is deaktivated!");
+ throw new ProtocolNotActiveException("auth.22", new Object[] { "SAML 1" });
+
+ }
+
+ String oaURL = (String) request.getParameter(PARAM_OA);
+ //oaURL = StringEscapeUtils.escapeHtml(oaURL);
+
+ String target = (String) request.getParameter(PARAM_TARGET);
+ target = StringEscapeUtils.escapeHtml(target);
+
+ String sourceID = request.getParameter(PARAM_SOURCEID);
+ sourceID = StringEscapeUtils.escapeHtml(sourceID);
+
+ //the target parameter is used to define the OA in SAML1 standard
+ if (target != null && target.startsWith("http")) {
+ oaURL = target;
+ target = null;
+ }
+
+ if (MiscUtil.isEmpty(oaURL)) {
+ Logger.info("Receive SAML1 request with no OA parameter. Authentication STOPPED!");
+ throw new WrongParametersException("StartAuthentication", PARAM_OA,
+ "auth.12");
+
+ }
+
+ if (!ParamValidatorUtils.isValidOA(oaURL))
+ throw new WrongParametersException("StartAuthentication", PARAM_OA,
+ "auth.12");
+
+ config.setOAURL(oaURL);
+
+ Logger.info("Dispatch SAML1 Request: OAURL=" + oaURL);
+
+ if (!ParamValidatorUtils.isValidSourceID(sourceID))
+ throw new WrongParametersException("StartAuthentication", PARAM_SOURCEID, "auth.12");
+
+
+ //load Target only from OA config
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance()
+ .getOnlineApplicationParameter(oaURL);
+
+ if (oaParam == null)
+ throw new InvalidProtocolRequestException("auth.00",
+ new Object[] { null });
+
+ SAML1ConfigurationParameters saml1 = oaParam.getSAML1Parameter();
+ if (saml1 == null || !(saml1.isIsActive() != null && saml1.isIsActive()) ) {
+ Logger.info("Online-Application " + oaURL + " can not use SAML1 for authentication.");
+ throw new InvalidProtocolRequestException("auth.00",
+ new Object[] { null });
+ }
+ config.setOnlineApplicationConfiguration(oaParam);
+ config.setSourceID(sourceID);
+
+ MOAReversionLogger.getInstance().logEvent(sessionId, transactionId, MOAIDEventConstants.AUTHPROTOCOL_SAML1_AUTHNREQUEST);
+
+ if (MiscUtil.isNotEmpty(target))
+ config.setTarget(target);
+
+ else
+ config.setTarget(oaParam.getTarget());
+
+
+ return config;
+ }
+
+ public boolean generateErrorMessage(Throwable e,
+ HttpServletRequest request, HttpServletResponse response,
+ IRequest protocolRequest)
+ throws Throwable{
+
+ OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(protocolRequest.getOAURL());
+ if (!oa.getSAML1Parameter().isProvideAllErrors())
+ return false;
+
+ else {
+ SAML1AuthenticationServer saml1authentication = SAML1AuthenticationServer.getInstace();
+ String samlArtifactBase64 = saml1authentication.BuildErrorAssertion(e, protocolRequest);
+
+ String url = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix() + "/RedirectServlet";
+ url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(protocolRequest.getOAURL(), "UTF-8"));
+ url = addURLParameter(url, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8"));
+ url = response.encodeRedirectURL(url);
+
+ response.setContentType("text/html");
+ response.setStatus(302);
+ response.addHeader("Location", url);
+ Logger.debug("REDIRECT TO: " + url);
+
+ return true;
+ }
+ }
+
+ public IAction getAction(String action) {
+ return actions.get(action);
+ }
+
+ public IAction canHandleRequest(HttpServletRequest request,
+ HttpServletResponse response) {
+ return null;
+ }
+
+ public boolean validate(HttpServletRequest request,
+ HttpServletResponse response, IRequest pending) {
+
+ return true;
+ }
+
+ 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;
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java
new file mode 100644
index 000000000..3da7cab80
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java
@@ -0,0 +1,108 @@
+/*
+ * 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.saml1;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.opensaml.saml2.core.Attribute;
+
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters;
+import at.gv.egovernment.moa.id.moduls.RequestImpl;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * @author tlenz
+ *
+ */
+public class SAML1RequestImpl extends RequestImpl {
+
+ /**
+ * @param req
+ * @throws ConfigurationException
+ */
+ public SAML1RequestImpl(HttpServletRequest req)
+ throws ConfigurationException {
+ super(req);
+
+ }
+
+ private static final long serialVersionUID = -4961979968425683115L;
+
+ private String sourceID = null;
+
+ /**
+ * @return the sourceID
+ */
+ public String getSourceID() {
+ return sourceID;
+ }
+
+ /**
+ * @param sourceID the sourceID to set
+ */
+ public void setSourceID(String sourceID) {
+ this.sourceID = sourceID;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes()
+ */
+ @Override
+ public List<Attribute> getRequestedAttributes() {
+
+ List<String> reqAttr = new ArrayList<String>();
+ reqAttr.addAll(SAML1Protocol.DEFAULTREQUESTEDATTRFORINTERFEDERATION);
+
+ try {
+ OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(getOAURL());
+ SAML1ConfigurationParameters saml1 = oa.getSAML1Parameter();
+ if (saml1 != null) {
+ if (saml1.isProvideAUTHBlock())
+ reqAttr.add(PVPConstants.EID_AUTH_BLOCK_NAME);
+
+ if (saml1.isProvideCertificate())
+ reqAttr.add(PVPConstants.EID_SIGNER_CERTIFICATE_NAME);
+
+ if (saml1.isProvideFullMandatorData())
+ reqAttr.add(PVPConstants.MANDATE_FULL_MANDATE_NAME);
+ }
+
+ return AttributQueryBuilder.buildSAML2AttributeList(oa, reqAttr.iterator());
+
+ } catch (ConfigurationException e) {
+ Logger.error("Load configuration for OA " + getOAURL() + " FAILED", e);
+ return null;
+ }
+
+
+ }
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo b/id/server/modules/moa-id-modules-saml1/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo
new file mode 100644
index 000000000..5bff0dbc2
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo
@@ -0,0 +1 @@
+at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol \ No newline at end of file
diff --git a/id/server/modules/moa-id-modules-saml1/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilderTest.java b/id/server/modules/moa-id-modules-saml1/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilderTest.java
new file mode 100644
index 000000000..ebdec6d22
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/test/java/test/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilderTest.java
@@ -0,0 +1,98 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package test.at.gv.egovernment.moa.id.auth.builder;
+
+import at.gv.egovernment.moa.id.auth.builder.SAMLArtifactBuilder;
+import at.gv.egovernment.moa.id.auth.exception.BuildException;
+import at.gv.egovernment.moa.util.Base64Utils;
+
+import test.at.gv.egovernment.moa.id.UnitTestCase;
+
+/**
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class SAMLArtifactBuilderTest extends UnitTestCase {
+
+ private static final String AUTH_URL = "https://moa.gv.at/auth/";
+ private static final String SESSION_ID_1 = "123456";
+ private static final String SESSION_ID_2 = "123457";
+ private static final String SESSION_ID_3 = "1234567";
+
+ private SAMLArtifactBuilder builder;
+ private byte[] artifact1;
+ private byte[] artifact2;
+ private byte[] artifact3;
+
+ public SAMLArtifactBuilderTest(String name) {
+ super(name);
+ }
+ protected void setUp() throws Exception {
+ builder = new SAMLArtifactBuilder();
+ artifact1 = Base64Utils.decode(builder.build(AUTH_URL, SESSION_ID_1, null), false);
+ artifact2 = Base64Utils.decode(builder.build(AUTH_URL, SESSION_ID_2, null), false);
+ artifact3 = Base64Utils.decode(builder.build(AUTH_URL, SESSION_ID_3, null), false);
+ }
+
+ public void testBuildArtifactLength() throws BuildException {
+ assertEquals(42, artifact1.length);
+ assertEquals(42, artifact2.length);
+ assertEquals(42, artifact3.length);
+ }
+ public void testBuildSameArtifact() throws Exception {
+ byte[] artifact1Clone = Base64Utils.decode(builder.build(AUTH_URL, SESSION_ID_1, null), false);
+ assertEquals(new String(artifact1), new String(artifact1Clone));
+ }
+ public void testBuildDifferentArtifacts() throws BuildException {
+ String msg = "SAML Artifacts should be different";
+ assertFalse(msg, new String(artifact1).equals(new String(artifact2)));
+ assertFalse(msg, new String(artifact1).equals(new String(artifact3)));
+ assertFalse(msg, new String(artifact3).equals(new String(artifact2)));
+ }
+
+
+}
diff --git a/id/server/modules/moa-id-modules-saml1/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParserTest.java b/id/server/modules/moa-id-modules-saml1/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParserTest.java
new file mode 100644
index 000000000..961c8d0b5
--- /dev/null
+++ b/id/server/modules/moa-id-modules-saml1/src/test/java/test/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParserTest.java
@@ -0,0 +1,101 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/*
+ * Copyright 2003 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ */
+
+
+package test.at.gv.egovernment.moa.id.auth.parser;
+
+import at.gv.egovernment.moa.id.auth.builder.SAMLArtifactBuilder;
+import at.gv.egovernment.moa.id.auth.parser.SAMLArtifactParser;
+import at.gv.egovernment.moa.id.util.Random;
+import test.at.gv.egovernment.moa.id.UnitTestCase;
+
+/*
+ * @author Paul Ivancsics
+ * @version $Id$
+ */
+public class SAMLArtifactParserTest extends UnitTestCase {
+
+ private static String URL1 = "http://moa.gv.at/auth";
+ private static String URL2 = "https://moa.gv.at/auth";
+
+ public SAMLArtifactParserTest(String name) {
+ super(name);
+ }
+
+ public void testParseTypeCode() throws Exception {
+ String sessionID = Random.nextRandom();
+ String samlArtifact = new SAMLArtifactBuilder().build(URL1, sessionID, null);
+ byte[] typeCode = new SAMLArtifactParser(samlArtifact).parseTypeCode();
+ assertEquals(typeCode[0], 0);
+ assertEquals(typeCode[1], 1);
+ }
+ public void testParseAssertionHandleSameSessionID() throws Exception {
+ // SAML artifacts for different authURL's but same sessionID MUST give same assertion handle
+ String sessionID = Random.nextRandom();
+ String samlArtifact1 = new SAMLArtifactBuilder().build(URL1, sessionID, null);
+ String samlArtifact2 = new SAMLArtifactBuilder().build(URL2, sessionID, null);
+ String assertionHandle1 = new SAMLArtifactParser(samlArtifact1).parseAssertionHandle();
+ String assertionHandle2 = new SAMLArtifactParser(samlArtifact2).parseAssertionHandle();
+ assertEquals(assertionHandle1, assertionHandle2);
+ }
+ public void testParseAssertionHandleSameURL() throws Exception {
+ // SAML artifacts for same authURL but different sessionID's MUST give different assertion handles
+ String sessionID1 = Random.nextRandom();
+ String sessionID2 = Random.nextRandom();
+ String samlArtifact1 = new SAMLArtifactBuilder().build(URL1, sessionID1, null);
+ String samlArtifact2 = new SAMLArtifactBuilder().build(URL1, sessionID2, null);
+ String assertionHandle1 = new SAMLArtifactParser(samlArtifact1).parseAssertionHandle();
+ String assertionHandle2 = new SAMLArtifactParser(samlArtifact2).parseAssertionHandle();
+ assertFalse(assertionHandle1.equals(assertionHandle2));
+ }
+ public void testParseAssertionHandleSameSAMLArtifact() throws Exception {
+ // SAML artifact parsed twice MUST give same assertion handle each time
+ String sessionID = Random.nextRandom();
+ String samlArtifact = new SAMLArtifactBuilder().build(URL1, sessionID, null);
+ String assertionHandle1 = new SAMLArtifactParser(samlArtifact).parseAssertionHandle();
+ String assertionHandle2 = new SAMLArtifactParser(samlArtifact).parseAssertionHandle();
+ assertEquals(assertionHandle1, assertionHandle2);
+ }
+}
diff --git a/id/server/modules/module-monitoring/pom.xml b/id/server/modules/module-monitoring/pom.xml
index 60ab6b6c0..0718f9017 100644
--- a/id/server/modules/module-monitoring/pom.xml
+++ b/id/server/modules/module-monitoring/pom.xml
@@ -8,9 +8,7 @@
<version>${moa-id-version}</version>
</parent>
- <groupId>MOA.id.server.modules</groupId>
<artifactId>moa-id-module-monitoring</artifactId>
- <version>${moa-id-version}</version>
<packaging>jar</packaging>
<name>MOA ID-Module Monitoring</name>
@@ -19,4 +17,11 @@
<repositoryPath>${basedir}/../../../../repository</repositoryPath>
</properties>
+ <dependencies>
+ <dependency>
+ <groupId>MOA.id.server.modules</groupId>
+ <artifactId>moa-id-modul-citizencard_authentication</artifactId>
+ </dependency>
+ </dependencies>
+
</project>
diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java
index de6c0fed0..824791797 100644
--- a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java
+++ b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/monitoring/IdentityLinkTestModule.java
@@ -68,7 +68,7 @@ public class IdentityLinkTestModule implements TestModuleInterface {
// builds a <VerifyXMLSignatureRequest> for a call of MOA-SP
Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder()
.build(identityLink, config
- .getMoaSpIdentityLinkTrustProfileID());
+ .getMoaSpIdentityLinkTrustProfileID(false));
// invokes the call
Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker()
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java
index 989f2b6bd..efc1cd498 100644
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java
@@ -16,7 +16,6 @@ import javax.xml.xpath.XPathFactory;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
-import org.bouncycastle.util.encoders.Base64;
import org.springframework.util.xml.SimpleNamespaceContext;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
@@ -24,6 +23,7 @@ import org.xml.sax.SAXException;
import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
import at.gv.egovernment.moa.id.auth.servlet.ProcessEngineSignalServlet;
import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Base64Utils;
/**
* STORK module specific servlet, overloading {@link ProcessEngineSignalServlet}'s method
@@ -66,7 +66,7 @@ public class STORKProcessEngineSignalServlet extends ProcessEngineSignalServlet
if (sessionId == null) {
String base64SamlToken = request.getParameter("SAMLResponse");
if (base64SamlToken != null) {
- byte[] samlToken = Base64.decode(base64SamlToken);
+ byte[] samlToken = Base64Utils.decode(base64SamlToken, false);
Document samlResponse = parseDocument(new ByteArrayInputStream(samlToken));
XPath xPath = XPathFactory.newInstance().newXPath();
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java
index 1acebe78e..ad1df27da 100644
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java
@@ -43,9 +43,8 @@ import eu.stork.peps.auth.commons.STORKAuthnRequest;
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.BaseAuthenticationServer;
import at.gv.egovernment.moa.id.auth.builder.CreateXMLSignatureRequestBuilder;
-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;
@@ -62,7 +61,6 @@ import at.gv.egovernment.moa.id.config.stork.STORKConfig;
import at.gv.egovernment.moa.id.config.stork.StorkAttribute;
import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
-import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventLog;
import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
import at.gv.egovernment.moa.id.moduls.IRequest;
import at.gv.egovernment.moa.id.moduls.RequestStorage;
@@ -118,13 +116,14 @@ public class CreateStorkAuthRequestFormTask extends AbstractAuthServletTask {
try {
setNoCachingHeaders(resp);
- sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID));
+ sessionID = (String) executionContext.get(PARAM_SESSIONID);
+ pendingRequestID = (String) executionContext.get("pendingRequestID");
+
// check parameter
if (!ParamValidatorUtils.isValidSessionID(sessionID)) {
throw new WrongParametersException("CreateStorkAuthRequestFormTask", PARAM_SESSIONID, "auth.12");
}
- AuthenticationSession moasession = AuthenticationServer.getSession(sessionID);
- pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID);
+ AuthenticationSession moasession = BaseAuthenticationServer.getSession(sessionID);
IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
if (StringUtils.isEmpty(moasession.getCcc())) {
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java
index a631489be..7b9fa3f12 100644
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java
@@ -19,7 +19,7 @@ import org.apache.velocity.app.VelocityEngine;
import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-import at.gv.egovernment.moa.id.auth.AuthenticationServer;
+import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
@@ -112,7 +112,7 @@ public class PepsConnectorHandleLocalSignResponseTask extends AbstractPepsConnec
try {
// load MOASession from database
- AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
+ AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
// change MOASessionID
moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java
index 6e0ab3ac9..e84c33d5d 100644
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java
@@ -21,7 +21,7 @@ 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.BaseAuthenticationServer;
import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
@@ -190,7 +190,7 @@ public class PepsConnectorHandleResponseWithoutSignatureTask extends AbstractPep
IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
// load MOASession from database
- AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
+ AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
// change MOASessionID
moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java
index 01dad4ebb..b505605ab 100644
--- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java
@@ -35,7 +35,8 @@ import org.w3c.dom.Node;
import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-import at.gv.egovernment.moa.id.auth.AuthenticationServer;
+
+import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
import at.gv.egovernment.moa.id.auth.data.IdentityLink;
@@ -225,7 +226,7 @@ public class PepsConnectorTask extends AbstractAuthServletTask {
IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
// load MOASession from database
- AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
+ AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
// change MOASessionID
moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java
new file mode 100644
index 000000000..79641d085
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java
@@ -0,0 +1,64 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/**
+ *
+ */
+package at.gv.egovernment.moa.id.auth.stork;
+
+
+/**
+ * Exception thrown if error occurs in STORK processing
+ * @author bzwattendorfer
+ *
+ */
+public class STORKException extends Exception{
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ public STORKException() {
+ super();
+
+ }
+
+ public STORKException(String message, Throwable cause) {
+ super(message, cause);
+
+ }
+
+ public STORKException(String message) {
+ super(message);
+
+ }
+
+ public STORKException(Throwable cause) {
+ super(cause);
+
+ }
+
+
+
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java
new file mode 100644
index 000000000..65a3637a9
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java
@@ -0,0 +1,286 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ ******************************************************************************/
+/**
+ *
+ */
+package at.gv.egovernment.moa.id.auth.stork;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.List;
+import java.util.Vector;
+
+import javax.activation.DataSource;
+import javax.xml.transform.Source;
+import javax.xml.transform.TransformerConfigurationException;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.stream.StreamSource;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang3.StringEscapeUtils;
+
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute;
+import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttributeImpl;
+import at.gv.egovernment.moa.id.auth.data.IdentityLink;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
+import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser;
+import at.gv.egovernment.moa.id.client.SZRGWClientException;
+import at.gv.egovernment.moa.id.client.utils.SZRGWClientUtils;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Constants;
+import at.gv.egovernment.moa.util.DateTimeUtils;
+import at.gv.egovernment.moa.util.StringUtils;
+import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse;
+import eu.stork.oasisdss.api.ApiUtils;
+import eu.stork.oasisdss.api.LightweightSourceResolver;
+import eu.stork.oasisdss.api.exceptions.ApiUtilsException;
+import eu.stork.oasisdss.api.exceptions.UtilsException;
+import eu.stork.oasisdss.profile.SignResponse;
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
+import eu.stork.peps.auth.commons.PersonalAttribute;
+
+/**
+ *
+ * Handles all functionality for the processing of a STORK response
+ * @author bzwattendorfer
+ *
+ */
+public class STORKResponseProcessor {
+
+ /** OASIS DSS Namespace */
+ public static final String OASIS_DSS_NS = "urn:oasis:names:tc:dss:1.0:core:schema";
+
+ /** OASIS DSS Success Message */
+ public static final String OASIS_DSS_SUCCESS_MSG = "urn:oasis:names:tc:dss:1.0:resultmajor:Success";
+
+ /**
+ * Checks for attribute.
+ *
+ * @param attributeName the attribute name
+ * @param attributeList the attribute list
+ * @return true, if successful
+ */
+ public static boolean hasAttribute(String attributeName, IPersonalAttributeList attributeList) {
+ try {
+ getAttributeValue(attributeName, attributeList);
+ return true;
+ } catch(STORKException e) {
+ return false;
+ }
+ }
+
+ /**
+ * helper for reading attributes. Handles logging and error handling.
+ *
+ * @param attributeName the attribute name
+ * @param attributeList the attribute list
+ * @return the attribute value
+ * @throws STORKException the sTORK exception
+ */
+ private static String getAttributeValue(String attributeName, IPersonalAttributeList attributeList) throws STORKException {
+ return getAttributeValue(attributeName, attributeList, true);
+ }
+ public static String getAttributeValue(String attributeName, IPersonalAttributeList attributeList, boolean throwException) throws STORKException {
+ try {
+ String result = attributeList.get(attributeName).getValue().get(0);
+ Logger.trace(attributeName + " : " + result);
+ return result;
+ } catch(Exception e) {
+ Logger.error(attributeName + " not found in response");
+ if(throwException)
+ throw new STORKException(attributeName + " not found in response");
+ else
+ return null;
+ }
+ }
+
+ /**
+ * Handels connection to SZR-GW and returns Identity Link on success.
+ *
+ * @param attributeList the attribute list
+ * @param oaFriendlyName the oa friendly name
+ * @param targetType the target type
+ * @param targetValue the target value
+ * @param filters the filters
+ * @param citizenSignature2
+ * @return Identity Link
+ * @throws STORKException the sTORK exception
+ * @throws MOAIDException
+ */
+ public static IdentityLink connectToSZRGateway(IPersonalAttributeList attributeList, String oaFriendlyName, String targetType, String targetValue, List<String> filters, String citizenSignature) throws STORKException, MOAIDException {
+ Logger.trace("Calling SZR Gateway with the following attributes:");
+
+ CreateIdentityLinkResponse identityLinkResponse = null;
+ IdentityLink identityLink = null;
+ try {
+ Logger.trace("Starting call...");
+
+ // if there is no signedDoc attribute, we cannot go on
+ if(citizenSignature==null || citizenSignature.length()==0)
+ {
+ String signResponseString = getAttributeValue("signedDoc", attributeList);
+
+ //Extract signature from SIgnResponse
+ Source response1 = new StreamSource(new java.io.StringReader(signResponseString));
+ SignResponse dssSignResponse = ApiUtils.unmarshal(response1, SignResponse.class);
+ citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse);
+ }
+
+ String fiscalNumber = getAttributeValue("fiscalNumber", attributeList, false);
+
+ // if we have a signedDoc we test for a representation case
+ // - according to stork samlengine and commons
+ if(hasAttribute("mandate", attributeList)) {
+ // we have a representation case
+ String mandate = getAttributeValue("mandate", attributeList, false);
+
+ if(!hasAttribute("dateOfBirth", attributeList)) {
+ // if we get here, we have a natural person representing a legal person
+ String organizationAddress = getAttributeValue("canonicalRegisteredAddress", attributeList, false);
+ String organizationType = getAttributeValue("translateableType", attributeList, false);
+
+ identityLinkResponse = SZRGWClientUtils.getIdentityLink(citizenSignature, null, null, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
+ } else {
+ // if we get here, we have a natural person representing another natural person
+ String eIdentifier = getAttributeValue("eIdentifier", attributeList, false);
+ String givenName = getAttributeValue("givenName", attributeList, false);
+ String lastName = getAttributeValue("surname", attributeList, false);
+ String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false);
+
+ // gender attribute is mandatory here because of some legal stuff
+ String gender = getAttributeValue("gender", attributeList, false);
+
+ if (!StringUtils.isEmpty(dateOfBirth))
+ dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth);
+
+ identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier,
+ givenName, lastName, dateOfBirth, gender, citizenSignature, null,
+ null, mandate, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
+ }
+ }
+ // - according to stork spec
+ else if(hasAttribute("mandateContent", attributeList) || hasAttribute("representative", attributeList) || hasAttribute("represented", attributeList)) {
+ // we have a representation case
+ String representative = getAttributeValue("representative", attributeList, false);
+ String represented = getAttributeValue("represented", attributeList, false);
+ String mandate = getAttributeValue("mandateContent", attributeList, false);
+
+ if(!hasAttribute("dateOfBirth", attributeList)) {
+ // if we get here, we have a natural person representing a legal person
+ String organizationAddress = getAttributeValue("canonicalRegisteredAddress", attributeList, false);
+ String organizationType = getAttributeValue("translateableType", attributeList, false);
+
+ identityLinkResponse = SZRGWClientUtils.getIdentityLink(citizenSignature, representative, represented, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
+ } else {
+ // if we get here, we have a natural person representing another natural person
+ String eIdentifier = getAttributeValue("eIdentifier", attributeList, false);
+ String givenName = getAttributeValue("givenName", attributeList, false);
+ String lastName = getAttributeValue("surname", attributeList, false);
+ String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false);
+
+ // gender attribute is mandatory here because of some legal stuff
+ String gender = getAttributeValue("gender", attributeList, false);
+
+ if (!StringUtils.isEmpty(dateOfBirth))
+ dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth);
+
+ identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier,
+ givenName, lastName, dateOfBirth, gender, citizenSignature, representative,
+ represented, mandate, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
+ }
+ } else {
+ // we do not have a representation case
+ String eIdentifier = getAttributeValue("eIdentifier", attributeList, false);
+ String givenName = getAttributeValue("givenName", attributeList, false);
+ String lastName = getAttributeValue("surname", attributeList, false);
+ String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false);
+ if (!StringUtils.isEmpty(dateOfBirth))
+ dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth);
+ identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, citizenSignature, fiscalNumber);
+ }
+
+ if (null != identityLinkResponse.getErrorResponse()){
+ throw new SZRGWClientException("service.08", (String)identityLinkResponse.getErrorResponse().getErrorCode(),
+ (String)identityLinkResponse.getErrorResponse().getInfo());
+ }
+ else {
+ IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream(identityLinkResponse.getIdentityLink()));
+ identityLink = ilParser.parseIdentityLink();
+
+ Logger.debug("Received Identity Link from SZR Gateway");
+ //TODO: is this ok?
+// if (StringUtils.isEmpty(identityLink.getDateOfBirth())) {
+// identityLink.setDateOfBirth("9999-12-31");
+// }
+
+ }
+
+ } catch (ParseException e) {
+ Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
+ throw new MOAIDException("auth.25", null, e);
+ } catch (ApiUtilsException e) {
+ Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
+ throw new MOAIDException("auth.25", null, e);
+ } catch (IllegalArgumentException e) {
+ Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
+ throw new MOAIDException("auth.25", null, e);
+ } catch (TransformerConfigurationException e) {
+ Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
+ throw new MOAIDException("auth.25", null, e);
+ } catch (UtilsException e) {
+ Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
+ throw new MOAIDException("auth.25", null, e);
+ } catch (TransformerException e) {
+ Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
+ throw new MOAIDException("auth.25", null, e);
+ } catch (TransformerFactoryConfigurationError e) {
+ Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
+ throw new MOAIDException("auth.25", null, e);
+ } catch (IOException e) {
+ Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e);
+ throw new MOAIDException("auth.25", null, e);
+ }
+
+ return identityLink;
+
+ }
+
+ private static String getCitizienSignatureFromSignResponse(SignResponse dssSignResponse) throws IllegalArgumentException, TransformerConfigurationException, UtilsException, TransformerException, TransformerFactoryConfigurationError, IOException, ApiUtilsException
+ {
+ // fetch signed doc
+ DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse);
+ if(ds == null){
+ throw new ApiUtilsException("No datasource found in response");
+ }
+
+ InputStream incoming = ds.getInputStream();
+ String citizenSignature = IOUtils.toString(incoming);
+ incoming.close();
+
+ return citizenSignature;
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java
new file mode 100644
index 000000000..124e490f2
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKAdoptedFamilyNameAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.ADOPTEDFAMILYNAME_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.ADOPTEDFAMILYNAME_FRIENDLYNAME, STORKConstants.ADOPTEDFAMILYNAME_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.ADOPTEDFAMILYNAME_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.ADOPTEDFAMILYNAME_FRIENDLYNAME, STORKConstants.ADOPTEDFAMILYNAME_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAgeAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAgeAttributBuilder.java
new file mode 100644
index 000000000..dff93139c
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAgeAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKAgeAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.AGE_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.AGE_FRIENDLYNAME, STORKConstants.AGE_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.AGE_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.AGE_FRIENDLYNAME, STORKConstants.AGE_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAttributHelper.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAttributHelper.java
new file mode 100644
index 000000000..9a0598cf6
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAttributHelper.java
@@ -0,0 +1,69 @@
+/*
+ * 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.builder.attributes;
+
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
+import eu.stork.peps.auth.commons.PersonalAttribute;
+import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * @author tlenz
+ *
+ */
+public class STORKAttributHelper {
+
+ public static String getAttribut(String attributName,
+ IAuthData authSession) throws UnavailableAttributeException {
+
+ if (!authSession.isForeigner()) {
+ throw new UnavailableAttributeException(attributName);
+
+ } else {
+ IPersonalAttributeList storkAttributes = authSession.getStorkAttributes();
+
+ if ( storkAttributes == null ) {
+ throw new UnavailableAttributeException(attributName);
+
+ }
+
+ try {
+ PersonalAttribute attribut = storkAttributes.get(attributName);
+ if (attribut != null) {
+
+ return attribut.getValue().get(0);
+
+ } else
+ throw new UnavailableAttributeException(attributName);
+
+ } catch (Exception e) {
+ Logger.warn("Attribut " + attributName + " generation error", e);
+ throw new UnavailableAttributeException(attributName);
+ }
+ }
+
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java
new file mode 100644
index 000000000..66d8a6bc1
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKCanonicalResidenceAddressAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.CANONICALRESIDENCEADDRESS_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.CANONICALRESIDENCEADDRESS_FRIENDLYNAME, STORKConstants.CANONICALRESIDENCEADDRESS_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.CANONICALRESIDENCEADDRESS_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.CANONICALRESIDENCEADDRESS_FRIENDLYNAME, STORKConstants.CANONICALRESIDENCEADDRESS_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java
new file mode 100644
index 000000000..706f5dd3a
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKCountryCodeOfBirthAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.CONTRYCODEOFBIRTH_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.CONTRYCODEOFBIRTH_FRIENDLYNAME, STORKConstants.CONTRYCODEOFBIRTH_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.CONTRYCODEOFBIRTH_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.CONTRYCODEOFBIRTH_FRIENDLYNAME, STORKConstants.CONTRYCODEOFBIRTH_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKFiscalNumberAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKFiscalNumberAttributBuilder.java
new file mode 100644
index 000000000..adc1d28da
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKFiscalNumberAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKFiscalNumberAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.FISCALNUMBER_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.FISCALNUMBER_FRIENDLYNAME, STORKConstants.FISCALNUMBER_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.FISCALNUMBER_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.FISCALNUMBER_FRIENDLYNAME, STORKConstants.FISCALNUMBER_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKGenderAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKGenderAttributBuilder.java
new file mode 100644
index 000000000..2faeaf2d7
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKGenderAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKGenderAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.GENDER_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.GENDER_FRIENDLYNAME, STORKConstants.GENDER_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.GENDER_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.GENDER_FRIENDLYNAME, STORKConstants.GENDER_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java
new file mode 100644
index 000000000..b6d29d42f
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKInhertedFamilyNameAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.INHERITEDFAMILYNAME_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.INHERITEDFAMILYNAME_FRIENDLYNAME, STORKConstants.INHERITEDFAMILYNAME_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.INHERITEDFAMILYNAME_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.INHERITEDFAMILYNAME_FRIENDLYNAME, STORKConstants.INHERITEDFAMILYNAME_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKIsAgeOverAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKIsAgeOverAttributBuilder.java
new file mode 100644
index 000000000..2ac3e2aaa
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKIsAgeOverAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKIsAgeOverAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.ISAGEOVER_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.ISAGEOVER_FRIENDLYNAME, STORKConstants.ISAGEOVER_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.ISAGEOVER_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.ISAGEOVER_FRIENDLYNAME, STORKConstants.ISAGEOVER_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKMaritalStatusAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKMaritalStatusAttributBuilder.java
new file mode 100644
index 000000000..c4e42029e
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKMaritalStatusAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKMaritalStatusAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.MARITALSTATUS_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.MARITALSTATUS_FRIENDLYNAME, STORKConstants.MARITALSTATUS_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.MARITALSTATUS_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.MARITALSTATUS_FRIENDLYNAME, STORKConstants.MARITALSTATUS_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKNationalityCodeAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKNationalityCodeAttributBuilder.java
new file mode 100644
index 000000000..47fbdd145
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKNationalityCodeAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKNationalityCodeAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.NATIONALITYCODE_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.NATIONALITYCODE_FRIENDLYNAME, STORKConstants.NATIONALITYCODE_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.NATIONALITYCODE_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.NATIONALITYCODE_FRIENDLYNAME, STORKConstants.NATIONALITYCODE_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKPseudonymAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKPseudonymAttributBuilder.java
new file mode 100644
index 000000000..6b079b8d4
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKPseudonymAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKPseudonymAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.PSEUDONYM_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.PSEUDONYM_FRIENDLYNAME, STORKConstants.PSEUDONYM_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.PSEUDONYM_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.PSEUDONYM_FRIENDLYNAME, STORKConstants.PSEUDONYM_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKResidencePermitAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKResidencePermitAttributBuilder.java
new file mode 100644
index 000000000..5728a3979
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKResidencePermitAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKResidencePermitAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.RESIDENCEPERMIT_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.RESIDENCEPERMIT_FRIENDLYNAME, STORKConstants.RESIDENCEPERMIT_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.RESIDENCEPERMIT_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.RESIDENCEPERMIT_FRIENDLYNAME, STORKConstants.RESIDENCEPERMIT_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTextResidenceAddressAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTextResidenceAddressAttributBuilder.java
new file mode 100644
index 000000000..1879eb42a
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTextResidenceAddressAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKTextResidenceAddressAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.TEXTRESIDENCEADDRESS_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.TEXTRESIDENCEADDRESS_FRIENDLYNAME, STORKConstants.TEXTRESIDENCEADDRESS_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.TEXTRESIDENCEADDRESS_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.TEXTRESIDENCEADDRESS_FRIENDLYNAME, STORKConstants.TEXTRESIDENCEADDRESS_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTitleAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTitleAttributBuilder.java
new file mode 100644
index 000000000..107386b5a
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTitleAttributBuilder.java
@@ -0,0 +1,49 @@
+/*******************************************************************************
+ * 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.builder.attributes;
+
+import at.gv.egovernment.moa.id.auth.stork.STORKConstants;
+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.protocols.pvp2x.builder.attributes.exceptions.AttributeException;
+
+public class STORKTitleAttributBuilder implements IPVPAttributeBuilder {
+
+ public String getName() {
+ return STORKConstants.TITLE_NAME;
+ }
+
+ public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData,
+ IAttributeGenerator<ATT> g) throws AttributeException {
+
+ return g.buildStringAttribute(STORKConstants.TITLE_FRIENDLYNAME, STORKConstants.TITLE_NAME,
+ STORKAttributHelper.getAttribut(STORKConstants.TITLE_NAME, authData));
+
+ }
+
+ public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) {
+ return g.buildEmptyAttribute(STORKConstants.TITLE_FRIENDLYNAME, STORKConstants.TITLE_NAME);
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java
new file mode 100644
index 000000000..7757f5af6
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java
@@ -0,0 +1,367 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+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.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.data.SLOInformationImpl;
+import at.gv.egovernment.moa.id.data.SLOInformationInterface;
+import at.gv.egovernment.moa.id.moduls.IAction;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider;
+import at.gv.egovernment.moa.id.storage.AssertionStorage;
+import at.gv.egovernment.moa.logging.Logger;
+import eu.stork.peps.auth.commons.*;
+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.opensaml.common.impl.SecureRandomIdentifierGenerator;
+
+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 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.
+ *
+ * TODO how do we treat mandatory and optional attributes?
+ */
+public class AttributeCollector implements IAction {
+
+ /**
+ * The Constant ARTIFACT_ID.
+ */
+ private static final String ARTIFACT_ID = "artifactId";
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.auth.data.AuthenticationSession)
+ */
+ public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException {
+
+ // - fetch the container
+ String artifactId = (String) httpReq.getParameter(ARTIFACT_ID);
+ DataContainer container;
+ try {
+ container = AssertionStorage.getInstance().get(artifactId, DataContainer.class);
+ } catch (MOADatabaseException e) {
+ Logger.error("Error fetching incomplete Stork response from temporary storage. Most likely a timeout occured.", e);
+ throw new MOAIDException("stork.11", null);
+ }
+
+
+ if (httpReq.getParameter("SAMLResponse") != null) {
+ Logger.info("Got SAML response from external attribute provider.");
+
+ MOASTORKResponse STORK2Response = new MOASTORKResponse(httpReq);
+
+ //extract STORK Response from HTTP Request
+ byte[] decSamlToken;
+ try {
+ decSamlToken = PEPSUtil.decodeSAMLToken(httpReq.getParameter("SAMLResponse"));
+ } catch (NullPointerException e) {
+ if (httpReq.getRemoteHost().contains("129.27.142")) {
+ Logger.warn("Availability check by " + httpReq.getRemoteHost() + " on URI: " + httpReq.getRequestURI());
+ } else {
+ Logger.error("Unable to retrieve STORK Request for host: " + httpReq.getRemoteHost() + " and URI: " + httpReq.getRequestURI(), e);
+ }
+ throw new MOAIDException("stork.04", null);
+ }
+
+ //Get SAMLEngine instance
+ STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
+
+ STORKAuthnResponse authnResponse = null;
+
+
+ // check if valid authn response is contained
+ try {
+ authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, httpReq.getRemoteAddr());
+ } catch (STORKSAMLEngineException ex) {
+ Logger.error("Unable to validate Stork AuthenticationResponse: " + ex.getMessage());
+ }
+
+ 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()));
+ }
+
+ }
+
+ // end addition
+
+
+ // read configuration parameters of OA
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(container.getRequest().getAssertionConsumerServiceURL());
+ if (oaParam == null)
+ throw new AuthenticationException("stork.12", new Object[]{container.getRequest().getAssertionConsumerServiceURL()});
+
+ // find the attribute provider plugin that can handle the response
+ IPersonalAttributeList newAttributes = null;
+
+ Iterator<AttributeProvider> attibuteProvidersInterator = AttributeProviderFactory.getConfiguredPlugins(oaParam.getStorkAPs());
+ while(attibuteProvidersInterator.hasNext())
+ try {
+ newAttributes = attibuteProvidersInterator.next().parse(httpReq);
+
+ // stop as soon as we hit a capable plugin
+ break;
+ } catch (UnsupportedAttributeException e1) {
+ // the current provider cannot find anything familiar within the
+ // provided httpreq. Try the next one.
+ }
+
+ if (null == newAttributes) {
+ // we do not have a provider which is capable of fetching something
+ // from the received httpreq.
+ Logger.error("No attribute could be retrieved from the response the attribute provider gave us.");
+ }
+
+ // - insert the embedded attribute(s) into the container
+ if (null != 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);
+
+ if (sloInfo == null) {
+ sloInfo = new SLOInformationImpl(req.getAuthURL(), null, null, null, req.requestedModule());
+ }
+
+ return sloInfo;
+
+ }
+
+ /**
+ * Checks if there are missing attributes and tries to fetch them. If there are no more attribute to fetch,
+ * this very method creates and sends the protocol result to the asking S-PEPS.
+ *
+ * @param container the {@link DataContainer} representing the status of the overall query.
+ * @return the string
+ * @throws MOAIDException
+ */
+ public SLOInformationInterface processRequest(DataContainer container, HttpServletRequest request, HttpServletResponse response, IAuthData authData, OAAuthParameter oaParam) throws MOAIDException {
+ // check if there are attributes we need to fetch
+
+ IPersonalAttributeList requestAttributeList = container.getRequest().getPersonalAttributeList();
+ IPersonalAttributeList responseAttributeList = container.getResponse().getPersonalAttributeList();
+ List<PersonalAttribute> missingAttributes = new ArrayList<PersonalAttribute>();
+ 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()))) {
+ // 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");
+
+ // Try to get all missing attributes
+ try {
+ // for each attribute still missing
+ for (PersonalAttribute currentAttribute : missingAttributes) {
+
+ /*
+ * prefill attributes with "notAvailable". If we get them later, we override the value and status.
+ * This way, there is no error case in which an attribute is left unanswered.
+ */
+ IPersonalAttributeList aquiredAttributes = new PersonalAttributeList();
+ currentAttribute.setStatus(AttributeStatusType.NOT_AVAILABLE.value());
+ aquiredAttributes.add((PersonalAttribute) currentAttribute.clone());
+ container.getResponse().setPersonalAttributeList(
+ addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes));
+ // - check if we can find a suitable AttributeProvider Plugin
+
+ Iterator<AttributeProvider> attibuteProvidersInterator = AttributeProviderFactory.getConfiguredPlugins(oaParam.getStorkAPs());
+ while(attibuteProvidersInterator.hasNext()) {
+ AttributeProvider currentProvider = attibuteProvidersInterator.next();
+
+ // build a section of attribute provider's predefined attributes and missing attributes
+ // only missing attributes that can be handled by attribute provider will be sent to it
+ List<PersonalAttribute> currentProviderConfiguredAttributes = new ArrayList<PersonalAttribute>();
+ for (String attributeName : currentProvider.getSupportedAttributeNames()) {
+ for (PersonalAttribute missingAttribute : missingAttributes) {
+ if (missingAttribute.getName().equals(attributeName)) {
+ currentProviderConfiguredAttributes.add(missingAttribute);
+ break;
+ }
+ }
+ }
+
+ try {
+ // - hand over control to the suitable plugin
+ Logger.info(currentProvider.getClass().getSimpleName() + " called to handle attribute '" + currentAttribute.getName() + "'");
+
+ //aquiredAttributes = currentProvider.acquire(currentAttribute, container.getRequest().getSpCountry(), moasession);
+ //aquiredAttributes = currentProvider.acquire(missingAttributes, container.getRequest().getSpCountry(), moasession);
+ aquiredAttributes = currentProvider.acquire(currentProviderConfiguredAttributes, container.getRequest(), authData);
+
+ Logger.info(currentProvider.getClass().getSimpleName() + " can handle attribute '" + currentAttribute.getName() + "'");
+ break;
+ } catch (UnsupportedAttributeException e) {
+ // ok, try the next attributeprovider
+ Logger.info(currentProvider.getClass().getSimpleName() + " could not handle attribute '" + currentAttribute.getName() + "'");
+ } catch (MOAIDException e) {
+ // the current plugin had an error. Try the next one.
+ Logger.info(currentProvider.getClass().getSimpleName() + " could not handle attribute '" + currentAttribute.getName() + "' due to an error");
+ }
+ }
+
+ // check if we could fetch the attribute
+ if (null == aquiredAttributes) {
+ // if not
+ Logger.error("We have no suitable plugin for obtaining the attribute '" + currentAttribute.getName() + "'");
+ } else
+ // else, update any existing attributes
+ container.getResponse().setPersonalAttributeList(addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes));
+ }
+ Logger.info("collecting attributes done");
+
+ // ask for consent if necessary
+ new ConsentEvaluator().generateSTORKResponse(response, container);
+
+ return null; // AssertionId
+ // TODO
+
+ } catch (ExternalAttributeRequestRequiredException e) {
+ // the attribute request is ongoing and requires an external service.
+ try {
+ // memorize the container again
+ Logger.debug("prepare putting the container into temporary storage...");
+
+ // - generate new key
+ String newArtifactId = new SecureRandomIdentifierGenerator()
+ .generateIdentifier();
+ // - put container in temporary store.
+ AssertionStorage.getInstance().put(newArtifactId, container);
+
+ Logger.debug("...successful");
+
+ Logger.info(e.getAp().getClass().getSimpleName() + " is going to ask an external service provider for the requested attributes");
+
+ // add container-key to redirect embedded within the return URL
+ e.getAp().performRedirect(AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix() + "/stork2/ResumeAuthentication?" + ARTIFACT_ID + "=" + newArtifactId, request, response, oaParam);
+
+ } catch (Exception e1) {
+ // TODO should we return the response as is to the PEPS?
+ Logger.error("Error putting incomplete Stork response into temporary storage", e1);
+ e1.printStackTrace();
+ throw new MOAIDException("stork.11", null);
+ }
+
+ //TODO: in case of Single LogOut -> SLO information has to be stored
+ return null; // TODO what to do here?
+ }
+ }
+
+ /**
+ * Adds or updates all {@link PersonalAttribute} objects given in {@code source} to/in {@code target}.
+ *
+ * @param target the target
+ * @param source the source
+ * @return
+ * @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 (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()))) {
+ Logger.error("Attribute Value does not match the value from first authentication!");
+ throw new MOAIDException("stork.16", new Object[] {existing.getName()});
+ }
+
+ updatedList.get(current.getName()).setStatus(current.getStatus());
+ updatedList.get(current.getName()).setValue(current.getValue());
+ updatedList.get(current.getName()).setComplexValue(current.getComplexValue());
+ } else
+ updatedList.add(current);
+
+ Logger.debug("...successfully treated " + current.getName());
+ }
+
+ return updatedList;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) {
+ // this action does not need any authentication. The authentication is already done by the preceding AuthenticationRequest-Action.
+ return false;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName()
+ */
+ public String getDefaultActionName() {
+ return STORKProtocol.ATTRIBUTE_COLLECTOR;
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java
new file mode 100644
index 000000000..aadbbd959
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java
@@ -0,0 +1,101 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import at.gv.egovernment.moa.id.commons.MOAIDConstants;
+import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin;
+import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider;
+import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.EHvdAttributeProviderPlugin;
+import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.MandateAttributeRequestProvider;
+import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.PVPAuthenticationProvider;
+import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.SignedDocAttributeRequestProvider;
+import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.StorkAttributeRequestProvider;
+import at.gv.egovernment.moa.logging.Logger;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.PriorityQueue;
+
+/**
+ * A factory for creating AttributeProvider objects.
+ */
+public class AttributeProviderFactory {
+
+ /**
+ * Gets the available plugins.
+ *
+ * @return the available plugins
+ */
+ public static List<String> getAvailablePlugins() {
+ return MOAIDConstants.ALLOWED_STORKATTRIBUTEPROVIDERS;
+ }
+
+ /**
+ * Creates an AttributeProvider object for the given shortname. Returns
+ * {@code null} if there is no such provider available.
+ *
+ * @param shortname the simpleName for the providers class
+ * @return the attribute provider
+ */
+ public static AttributeProvider create(String shortname, String url, String attributes) {
+ if (shortname.equals("StorkAttributeRequestProvider")) {
+ return new StorkAttributeRequestProvider(url, attributes);
+ } else if (shortname.equals("EHvdAttributeProvider")) {
+ return new EHvdAttributeProviderPlugin(url, attributes);
+ } else if (shortname.equals("SignedDocAttributeRequestProvider")) {
+ return new SignedDocAttributeRequestProvider(url, attributes);
+ } else if (shortname.equals("MandateAttributeRequestProvider")) {
+ try {
+ return new MandateAttributeRequestProvider(url, attributes);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ return null;
+ }
+ } else if (shortname.equals("PVPAuthenticationProvider")) {
+ return new PVPAuthenticationProvider(url, attributes);
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Gets fresh instances of the configured plugins.
+ *
+ * @param collection the configured a ps
+ * @return the configured plugins
+ */
+ public static Iterator<AttributeProvider> getConfiguredPlugins(
+ Collection<StorkAttributeProviderPlugin> collection) {
+
+ PriorityQueue<AttributeProvider> result = new PriorityQueue<AttributeProvider>();
+ for (StorkAttributeProviderPlugin current : collection) {
+
+ result.add(create(current.getName(), current.getUrl(), current.getAttributes()));
+ Logger.debug("Adding configured attribute provider: " + current.getClass().getName() + current.getName() + " at " + current.getUrl());
+ }
+
+ return result.iterator();
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java
new file mode 100644
index 000000000..f16f7c9a8
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java
@@ -0,0 +1,531 @@
+/*******************************************************************************
+ * 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.stork2;
+
+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.ex.MOADatabaseException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+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.MISMandate;
+import at.gv.egovernment.moa.id.data.SLOInformationImpl;
+import at.gv.egovernment.moa.id.data.SLOInformationInterface;
+import at.gv.egovernment.moa.id.moduls.IAction;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.id.storage.AssertionStorage;
+import at.gv.egovernment.moa.id.util.VelocityProvider;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.MiscUtil;
+import eu.stork.peps.auth.commons.*;
+import eu.stork.peps.auth.engine.STORKSAMLEngine;
+import eu.stork.peps.exceptions.STORKSAMLEngineException;
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+import org.apache.velocity.runtime.RuntimeConstants;
+import org.w3c.dom.Element;
+import org.w3c.dom.NamedNodeMap;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+
+/**
+ * Second request step - after authentication of the user is done and moasession obtained,
+ * process request and forward the user further to PEPS and/or other entities
+ *
+ * @author bsuzic
+ */
+
+public class AuthenticationRequest implements IAction {
+
+
+ private VelocityEngine velocityEngine;
+ private MOASTORKRequest moaStorkRequest = null;
+
+
+ public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException {
+
+ if ((req instanceof MOASTORKRequest)) { // && ( ((MOASTORKRequest) req).getCitizenCountryCode() == null || ((MOASTORKRequest) req).getCitizenCountryCode().equals("AT") )) {
+
+ this.moaStorkRequest = (MOASTORKRequest) req;
+
+ Logger.debug("Entering MOASTORKRequest");
+ httpResp.reset();
+
+ //TODO: CHECK: req.getOAURL() should return the unique OA identifier
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(req.getOAURL());
+ if (oaParam == null)
+ throw new AuthenticationException("stork.12", new Object[]{req.getOAURL()});
+
+ MOASTORKResponse moaStorkResponse = new MOASTORKResponse(httpReq);
+
+ // check if it is attribute query
+ if (moaStorkRequest.isAttrRequest()) {
+ Logger.debug("Starting AttrQueryRequest");
+
+ moaStorkResponse.setSTORKAttrResponse(new STORKAttrQueryResponse());
+ }
+ // check if we have authentication request
+ else if (moaStorkRequest.isAuthnRequest()) {
+ Logger.debug("Starting AuthenticationRequest");
+ moaStorkResponse.setSTORKAuthnResponse(new STORKAuthnResponse());
+
+ //STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
+
+ // Logger.debug("Starting generation of SAML response");
+ // try {
+ // moaStorkResponse.setSTORKAuthnResponse(engine.generateSTORKAuthnResponse(moaStorkRequest.getStorkAuthnRequest(), moaStorkResponse.getStorkAuthnResponse(), httpReq.getRemoteAddr(), false));
+ // } catch (STORKSAMLEngineException ex) {
+ // Logger.error("Failed to generate STORK SAML Response", ex);
+ // throw new MOAIDException("stork.05", null); // TODO
+ // }
+
+ // Get personal attributtes from MOA/IdentityLink
+
+ //build STORK attributes from local authentication information
+ if (authData != null) {
+ int reqQaa = -1;
+ int authQaa = -1;
+ try {
+ reqQaa = moaStorkRequest.getStorkAuthnRequest().getQaa();
+ authQaa = Integer.valueOf(
+ authData.getQAALevel().substring(PVPConstants.STORK_QAA_PREFIX.length()));
+
+ if (reqQaa > authQaa) {
+ Logger.warn("Requested QAA level does not match to authenticated QAA level");
+ throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa});
+
+ }
+
+ } catch (MOAIDException e) {
+ throw e;
+
+ } catch (Exception e) {
+ if (Logger.isDebugEnabled())
+ Logger.warn("STORK QAA Level evaluation error", e);
+
+ else
+ Logger.warn("STORK QAA Level evaluation error (ErrorMessage="
+ + e.getMessage() + ")");
+
+ throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa});
+
+ }
+
+ moaStorkResponse.setPersonalAttributeList(populateAttributes(authData, oaParam));
+
+ }
+ }
+
+ //moaStorkResponse.setCountry(moaStorkRequest.getSpCountry());
+
+ // Prepare extended attributes
+ Logger.debug("Preparing data container");
+
+ // create fresh container
+ DataContainer container = new DataContainer();
+
+ // - fill in the request we extracted above
+ container.setRequest(moaStorkRequest);
+
+ // - fill in the partial response created above
+ container.setResponse(moaStorkResponse);
+
+ container.setRemoteAddress(httpReq.getRemoteAddr());
+
+ Logger.debug("Data container prepared");
+
+ 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) {
+// return handleMOAStorkRequest("VIDP", (MOASTORKRequest) req, httpReq.getRemoteAddr(), httpResp);
+// }
+
+ // Check if we got the response from PEPS
+ // If so then process it and forward to SP
+ else if ((req instanceof MOASTORKResponse)) {
+ return handleMOAStorkResponse("VIDP", (MOASTORKResponse) req, httpReq.getRemoteAddr(), httpResp);
+ } else {
+ Logger.error("Could not recognize request.");
+ throw new MOAIDException("stork.15", null);
+ }
+ }
+
+ /*
+ Handles STORKAuthnRequeste received for citizens of other countries
+ */
+ private SLOInformationInterface handleMOAStorkRequest(String instanceName, MOASTORKRequest moastorkRequest, String remoteAddr, HttpServletResponse httpResp) throws MOAIDException {
+
+ STORKAuthnRequest spAuthnRequest = moastorkRequest.getStorkAuthnRequest();
+ STORKAuthnRequest storkAuthnRequest = null;
+
+ String citizenCountryCode = spAuthnRequest.getCitizenCountryCode();
+ Logger.info("Got authentication request for citizen of " + citizenCountryCode);
+
+ try {
+ storkAuthnRequest = (STORKAuthnRequest) spAuthnRequest.clone();
+ } catch (CloneNotSupportedException e) {
+ Logger.error("Could not clone AuthnRequest ", e);
+ throw new MOAIDException("stork.05", null); // TODO
+ }
+
+ //TODO: in case of Single LogOut -> SLO information has to be stored
+ // check if citizen country is configured in the system
+ if (!(AuthConfigurationProviderFactory.getInstance().getStorkConfig().getCpepsMap().containsKey(citizenCountryCode))) {
+ Logger.error("Citizen country PEPS not configured in MOA instance: " + citizenCountryCode);
+ throw new MOAIDException("stork.05", null); // TODO
+ }
+
+ // extracting basic settings and adjusting assertion consumer
+ String issuer = null;
+ String assertionConsumerURL = null;
+ String publicURLPrefix = null;
+ String destinationURL = null;
+
+ try {
+ issuer = new URL(moaStorkRequest.getAuthURL()).toString();
+ destinationURL = AuthConfigurationProviderFactory.getInstance().getStorkConfig().getCPEPS(citizenCountryCode).getPepsURL().toString();
+ publicURLPrefix = moaStorkRequest.getAuthURL();
+ assertionConsumerURL = publicURLPrefix + "/stork2/SendPEPSAuthnRequest";
+ } catch (MalformedURLException ex) {
+ Logger.error("Wrong PublicURLPrefix setting of MOA instance: " + AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(), ex);
+ throw new MOAIDException("stork.05", null); // TODO
+ } catch (Exception ex) {
+ Logger.error("Problem with PEPS configuration of MOA instance.", ex);
+ throw new MOAIDException("stork.05", null); // TODO
+ }
+
+
+ // drop if we do not have publicprefix url configured on the instance
+ if (publicURLPrefix == null)
+ throw new AuthenticationException("stork.12", new String[]{"PublicURLPrefix"});
+
+ // adjusting request
+ storkAuthnRequest.setEIDCrossBorderShare(spAuthnRequest.isEIDCrossBorderShare());
+ storkAuthnRequest.setEIDSectorShare(spAuthnRequest.isEIDSectorShare());
+ storkAuthnRequest.setEIDCrossSectorShare(spAuthnRequest.isEIDCrossSectorShare());
+ storkAuthnRequest.setCitizenCountryCode(spAuthnRequest.getCitizenCountryCode());
+ storkAuthnRequest.setIssuer(issuer);
+ storkAuthnRequest.setAssertionConsumerServiceURL(assertionConsumerURL);
+ storkAuthnRequest.setDestination(destinationURL);
+
+ // regenerate request
+ try {
+ //Get SAMLEngine instance
+ STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
+ Logger.debug("Starting generation of SAML request");
+ storkAuthnRequest = engine.generateSTORKAuthnRequest(storkAuthnRequest);
+
+ //generateSAML Token
+ Logger.info("SAML response succesfully generated!");
+ } catch (STORKSAMLEngineException e) {
+ Logger.error("Failed to generate STORK SAML Response", e);
+ throw new MOAIDException("stork.05", null);
+ }
+
+ // store original request from SP in order to be able to extract it in later iteration/response
+ DataContainer spRequestContainer = new DataContainer();
+ spRequestContainer.setRequest(moastorkRequest);
+
+ try {
+ AssertionStorage.getInstance().put(storkAuthnRequest.getSamlId(), spRequestContainer);
+ Logger.info("Storing artifactId " + storkAuthnRequest.getSamlId() + " of SP authentication request with id " + spAuthnRequest.getSamlId());
+ } catch (MOADatabaseException e) {
+ e.printStackTrace();
+ }
+
+ // preparing redirection for the client
+ performRedirection("SAMLRequest", destinationURL, storkAuthnRequest.getTokenSaml(), httpResp);
+
+ SLOInformationImpl sloInfo = new SLOInformationImpl();
+ sloInfo.setProtocolType(moastorkRequest.requestedModule());
+ return sloInfo;
+ }
+
+ /*
+ Handles STORKAuthnResponse received from PEPS (return to SP)
+ */
+ private SLOInformationInterface handleMOAStorkResponse(String instanceName, MOASTORKResponse moastorkResponse, String remoteAddr, HttpServletResponse httpResp) throws MOAIDException {
+
+ STORKAuthnResponse authnResponse = null;
+
+ //Get SAMLEngine instance
+ STORKSAMLEngine engine = STORKSAMLEngine.getInstance(instanceName);
+
+ try {
+ authnResponse = engine.validateSTORKAuthnResponse(moastorkResponse.getSTORKAuthnResponseToken(), remoteAddr);
+ } catch (STORKSAMLEngineException ex) {
+ Logger.error("Unable to validate Stork AuthenticationResponse: " + ex.getMessage());
+ throw new MOAIDException("stork.15", null); // TODO
+ }
+
+ Logger.debug("Requesting artifactId " + authnResponse.getInResponseTo() + " from store.");
+
+ DataContainer dataContainer = null;
+ try {
+ dataContainer = AssertionStorage.getInstance().get(authnResponse.getInResponseTo(), DataContainer.class);
+ } catch (MOADatabaseException e) {
+ Logger.error("Unable to retrieve datacontainer with reference authentication request. Database exception.");
+ throw new MOAIDException("stork.15", null); // TODO
+ }
+
+ // setting new reference request and return url
+ authnResponse.setInResponseTo(dataContainer.getRequest().getStorkAuthnRequest().getSamlId());
+ authnResponse.setAudienceRestriction(dataContainer.getRequest().getAssertionConsumerServiceURL());
+ //AudienceRestrictionBuilder audienceRestrictionBuilder = new AudienceRestrictionBuilder();
+ //AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject(dataContainer.getRequest().getAssertionConsumerServiceURL(), "localname", "nameprefix");
+
+ //authnResponse.getAssertions().get(0).getConditions().getAudienceRestrictions().add(audienceRestriction);
+
+ Logger.debug("Starting generation of SAML response");
+ try {
+ authnResponse = engine.generateSTORKAuthnResponse(dataContainer.getRequest().getStorkAuthnRequest(), authnResponse, remoteAddr, false);
+ } catch (STORKSAMLEngineException e) {
+ Logger.error("Failed to generate STORK SAML Response", e);
+ throw new MOAIDException("stork.05", null); // TODO check
+ }
+
+ Logger.info("SAML response succesfully generated.");
+
+ // preparing redirection for the client
+ performRedirection("SAMLResponse", dataContainer.getRequest().getAssertionConsumerServiceURL(), authnResponse.getTokenSaml(), httpResp);
+
+ return null;
+ }
+
+ /*
+ Perform redirection of the client based on post binding
+ */
+ private void performRedirection(String actionType, String assertionConsumerURL, byte[] tokenSaml, HttpServletResponse httpResp) throws MOAIDException {
+ Logger.info("Performing redirection, using action type: " + actionType);
+
+ try {
+ VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
+ Template template = velocityEngine.getTemplate("/resources/templates/stork2_postbinding_template.html");
+ VelocityContext context = new VelocityContext();
+
+ context.put(actionType, PEPSUtil.encodeSAMLToken(tokenSaml));
+ Logger.debug("Encoded " + actionType + " original: " + new String(tokenSaml));
+
+ Logger.debug("Using assertion consumer url as action: " + assertionConsumerURL);
+ context.put("action", assertionConsumerURL);
+
+ Logger.debug("Starting template merge");
+ StringWriter writer = new StringWriter();
+
+ Logger.debug("Doing template merge");
+ template.merge(context, writer);
+ Logger.debug("Template merge done");
+
+ Logger.debug("Sending html content: " + writer.getBuffer().toString());
+ Logger.debug("Sending html content2 : " + new String(writer.getBuffer()));
+
+ httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8"));
+
+ } catch (IOException e) {
+ Logger.error("Velocity IO error: " + e.getMessage());
+ throw new MOAIDException("stork.15", null); // TODO
+ } catch (Exception e) {
+ Logger.error("Velocity general error: " + e.getMessage());
+ throw new MOAIDException("stork.15", null); // TODO
+ }
+
+ }
+
+ public void generatePEPSRedirect(HttpServletResponse httpResp, DataContainer container) throws MOAIDException {
+ MOASTORKRequest request = container.getRequest();
+ MOASTORKResponse response = container.getResponse();
+
+ Logger.info("generating stork response...");
+
+ try {
+ //Get SAMLEngine instance
+ STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
+ Logger.debug("Starting generation of SAML response");
+ if (response.isAuthnResponse())
+ response.setSTORKAuthnResponse(engine.generateSTORKAuthnResponse(request.getStorkAuthnRequest(), response.getStorkAuthnResponse(), container.getRemoteAddress(), false));
+ else
+ response.setSTORKAttrResponse(engine.generateSTORKAttrQueryResponse(request.getStorkAttrQueryRequest(), response.getStorkAttrQueryResponse(), container.getRemoteAddress(), "", false));
+
+
+ //generateSAML Token
+ Logger.info("SAML response succesfully generated!");
+ } catch (STORKSAMLEngineException e) {
+ Logger.error("Failed to generate STORK SAML Response", e);
+ throw new MOAIDException("stork.05", null);
+ }
+
+ // preparing redirection for the client
+ try {
+ VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
+ Template template = velocityEngine.getTemplate("/resources/templates/stork2_postbinding_template.html");
+ VelocityContext context = new VelocityContext();
+
+ byte[] blob;
+ if (request.isAttrRequest())
+ blob = response.getStorkAttrQueryResponse().getTokenSaml();
+ else
+ blob = response.getStorkAuthnResponse().getTokenSaml();
+
+ context.put("SAMLResponse", PEPSUtil.encodeSAMLToken(blob));
+ Logger.debug("SAMLResponse original: " + new String(blob));
+
+ Logger.debug("Putting assertion consumer url as action: " + request.getAssertionConsumerServiceURL());
+ context.put("action", request.getAssertionConsumerServiceURL());
+ Logger.trace("Starting template merge");
+ StringWriter writer = new StringWriter();
+
+ Logger.trace("Doing template merge");
+ template.merge(context, writer);
+ Logger.trace("Template merge done");
+
+ Logger.trace("Sending html content: " + writer.getBuffer().toString());
+ Logger.trace("Sending html content2 : " + new String(writer.getBuffer()));
+
+ httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8"));
+
+ } catch (Exception e) {
+ Logger.error("Velocity error: " + e.getMessage());
+ }
+ }
+
+
+ public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) {
+
+ //redirect to national PVP IDP infrastructure if special attributes are requested
+ if (MiscUtil.isEmpty(req.getRequestedIDP()) && req instanceof MOASTORKRequest)
+ return !STORKPVPUtilits.performAuthenticationOnNationalIDP((MOASTORKRequest) req);
+
+// // authentication is not needed if we have authentication request from SP for citizen of configured PEPS country
+// if (req instanceof MOASTORKRequest) {
+// MOASTORKRequest moastorkRequest = (MOASTORKRequest) req;
+// if (moastorkRequest.getStorkAuthnRequest() != null) {
+// String citizenCountryCode = moastorkRequest.getStorkAuthnRequest().getCitizenCountryCode();
+// // check if citizen country is configured in the system
+// try {
+// if (AuthConfigurationProvider.getInstance().getStorkConfig().getCpepsMap().containsKey(citizenCountryCode)) {
+// return false;
+// }
+// } catch (MOAIDException e) {
+// Logger.error("Could not initialize AuthConfigurationProvider");
+// }
+// }
+// // authentication is not required if received authentication response
+// } else if (req instanceof MOASTORKResponse) {
+// return false;
+// }
+
+ return true;
+ }
+
+
+ private void iterate(NamedNodeMap attributesList) {
+ for (int j = 0; j < attributesList.getLength(); j++) {
+ Logger.debug("--Attribute: "
+ + attributesList.item(j).getNodeName() + " = "
+ + attributesList.item(j).getNodeValue());
+ }
+ }
+
+
+ // does nothing
+ public void mandate(IAuthData authData) {
+
+ if (authData.isUseMandate()) {
+ try {
+ MISMandate mandate = authData.getMISMandate();
+ String owbpk = mandate.getOWbPK();
+ byte[] mand = mandate.getMandate();
+ String profprep = mandate.getProfRep();
+ //String textdesc = mandate.getTextualDescriptionOfOID();
+ Element mndt = authData.getMandate();
+
+ iterate(mndt.getAttributes());
+ Logger.debug("mandate encoded: " + new String(org.bouncycastle.util.encoders.Base64.encode(mand)));
+ } catch (Exception x) {
+ Logger.debug("There is no mandate used in transaction");
+ }
+ }
+
+
+ }
+
+ public PersonalAttributeList populateAttributes(IAuthData authData, IOAAuthParameters oaParam) {
+
+ IPersonalAttributeList attrLst = moaStorkRequest.getStorkAuthnRequest().getPersonalAttributeList();
+ Logger.info("Found " + attrLst.size() + " personal attributes in the request.");
+
+ // Define attribute list to be populated
+ PersonalAttributeList attributeList = new PersonalAttributeList();
+ MOAAttributeProvider moaAttributeProvider = new MOAAttributeProvider(authData, moaStorkRequest);
+
+ try {
+ for (PersonalAttribute personalAttribute : attrLst) {
+ try {
+ 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(), e);
+ }
+ }
+ } catch (Exception e) {
+ Logger.error("Exception, attributes: " + e.getMessage(), e);
+ }
+
+ Logger.trace("AUTHBLOCK " + authData.getAuthBlock());
+ Logger.debug("SESSION IDENTIFIER " + authData.getCcc() + " " + oaParam.getIdentityLinkDomainIdentifier());
+
+ return attributeList;
+ }
+
+ public String getDefaultActionName() {
+ return STORKProtocol.AUTHENTICATIONREQUEST;
+ }
+
+
+ private void initVelocityEngine() throws Exception {
+ velocityEngine = new VelocityEngine();
+ velocityEngine.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8");
+ velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8");
+ velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
+ velocityEngine.setProperty("classpath.resource.loader.class",
+ "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
+
+ velocityEngine.init();
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java
new file mode 100644
index 000000000..947accf8e
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java
@@ -0,0 +1,249 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import java.io.StringWriter;
+
+import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+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.AuthConfigurationProviderFactory;
+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;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.storage.AssertionStorage;
+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.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.opensaml.common.impl.SecureRandomIdentifierGenerator;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+/**
+ * The ConsentEvaluator assists with fetching user consent on the list of attributes to be sent to the asking S-PEPS.
+ */
+public class ConsentEvaluator implements IAction {
+
+ /**
+ * The Constant ARTIFACT_ID.
+ */
+ private static final String ARTIFACT_ID = "artifactId";
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.auth.data.AuthenticationSession)
+ */
+ public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException {
+
+ // - fetch the container
+ String artifactId = (String) httpReq.getParameter(ARTIFACT_ID);
+ 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.getRequest().getPersonalAttributeList()) {
+ if(null == httpReq.getParameter(current.getName())) {
+ current.setStatus(AttributeStatusType.WITHHELD.value());
+ current.setValue(new ArrayList<String>());
+ current.setComplexValue(new HashMap<String, String>());
+ }
+ }
+
+ //TODO: CHECK: req.getOAURL() should return the unique OA identifier
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.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
+ }
+
+ /**
+ * 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, 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 {
+
+ // memorize the container again
+ Logger.debug("prepare putting the container into temporary storage...");
+
+ // - generate new key
+ newArtifactId = new SecureRandomIdentifierGenerator().generateIdentifier();
+
+ // - put container in temporary store.
+ AssertionStorage.getInstance().put(newArtifactId, container);
+
+ Logger.debug("...successful");
+
+ } catch (Exception e1) {
+ // TODO should we return the response as is to the PEPS?
+ e1.printStackTrace();
+ Logger.error("Error putting incomplete Stork response into temporary storage", e1);
+ throw new MOAIDException("stork.17", null);
+ }
+
+ // ask for consent
+ try {
+ VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
+ Template template = velocityEngine.getTemplate("/resources/templates/stork2_consent.html");
+ VelocityContext context = new VelocityContext();
+
+ context.put("action", AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix() + "/stork2/GetConsent?" + ARTIFACT_ID + "=" + newArtifactId);
+
+ // assemble table
+ String table = "";
+ for (PersonalAttribute current : container.getRequest().getPersonalAttributeList())
+ table += "<tr><td><input type=\"checkbox\" checked=\"yes\" name=\"" + current.getName() + "\"></td><td>" + current.getName() + (current.isRequired() ? "" : " (optional)") + "</td></tr>\n";
+
+ context.put("tablecontent", table);
+ for(Entry<String, String> current : oaParam.getFormCustomizaten().entrySet())
+ context.put(current.getKey().replace("#", ""), current.getValue());
+
+ StringWriter writer = new StringWriter();
+ template.merge(context, writer);
+ httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8"));
+
+ } catch (Exception e) {
+ Logger.error("Velocity error: " + e.getMessage());
+ throw new MOAIDException("stork.17", null);
+ }
+
+ return "12345"; // AssertionId
+ }
+
+ /**
+ * generates binary response from given response class and fill the given HttpResponse with a SAML Post Binding template.
+ *
+ * @param httpResp the http resp
+ * @param container the container
+ * @throws MOAIDException the mOAID exception
+ */
+ public void generateSTORKResponse(HttpServletResponse httpResp, DataContainer container) throws MOAIDException {
+ MOASTORKRequest request = container.getRequest();
+ MOASTORKResponse response = container.getResponse();
+
+ Logger.info("generating stork response...");
+
+ try {
+ //Get SAMLEngine instance
+ STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
+ Logger.debug("Starting generation of SAML response");
+ if(response.isAuthnResponse())
+ response.setSTORKAuthnResponse(engine.generateSTORKAuthnResponse(request.getStorkAuthnRequest(), response.getStorkAuthnResponse(), container.getRemoteAddress(), false));
+ else
+ response.setSTORKAttrResponse(engine.generateSTORKAttrQueryResponse(request.getStorkAttrQueryRequest(), response.getStorkAttrQueryResponse(), container.getRemoteAddress(), "", false));
+
+
+ //generateSAML Token
+ Logger.info("SAML response succesfully generated!");
+ } catch (STORKSAMLEngineException e) {
+ Logger.error("Failed to generate STORK SAML Response", e);
+ throw new MOAIDException("stork.05", null);
+ }
+
+ // preparing redirection for the client
+ try {
+ VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
+ Template template = velocityEngine.getTemplate("/resources/templates/stork2_postbinding_template.html");
+ VelocityContext context = new VelocityContext();
+
+ byte[] blob;
+ if(request.isAttrRequest())
+ blob = response.getStorkAttrQueryResponse().getTokenSaml();
+ else
+ blob = response.getStorkAuthnResponse().getTokenSaml();
+
+ context.put("SAMLResponse", PEPSUtil.encodeSAMLToken(blob));
+ Logger.debug("SAMLResponse original: " + new String(blob));
+
+ Logger.debug("Putting assertion consumer url as action: " + request.getAssertionConsumerServiceURL());
+ context.put("action", request.getAssertionConsumerServiceURL());
+ Logger.trace("Starting template merge");
+ StringWriter writer = new StringWriter();
+
+ Logger.trace("Doing template merge");
+ template.merge(context, writer);
+ Logger.trace("Template merge done");
+
+ Logger.trace("Sending html content: " + writer.getBuffer().toString());
+ Logger.trace("Sending html content2 : " + new String(writer.getBuffer()));
+
+ httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8"));
+
+ } catch (Exception e) {
+ Logger.error("Velocity error: " + e.getMessage());
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
+ */
+ public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) {
+ // this action does not need any authentication. The authentication is already done by the preceding AuthenticationRequest-Action.
+ return false;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName()
+ */
+ public String getDefaultActionName() {
+ return STORKProtocol.CONSENT_EVALUATOR;
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java
new file mode 100644
index 000000000..acbf1678a
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java
@@ -0,0 +1,115 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.logging.Logger;
+import org.xml.sax.InputSource;
+
+import javax.xml.xpath.XPathExpressionException;
+import java.io.StringReader;
+/**
+ * Physical person representing corporate body
+ *
+ * @author bsuzic
+ * Date: 4/29/14, Time: 3:40 PM
+ */
+public class CorporateBodyMandateContainer extends MandateContainer {
+
+ protected String corpMandatorIdentificationValue = null;
+ protected String corpMandatorIdentificationType = null;
+ protected String corpMandatorFullName = null;
+
+
+ String localMethods[] = new String[]{"getCorpMandatorIdentificationValue", "getCorpMandatorIdentificationType", "getCorpMandatorFullName",
+ "getMandateIssuePlace", "getMandateIssueDate", "getMandateIssueTime", "getSimpleMandateContent", "getMandateValidFrom",
+ "getMandateValidTo", "getPhysicalRepresentativeIdentificationValue", "getPhysicalRepresentativeIdentificationType", "getAnnotation",
+ "getPhysicalRepresentativeGivenName", "getPhysicalRepresentativeFamilyName", "getPhysicalRepresentativeBirthDate"
+ };
+
+ public CorporateBodyMandateContainer(String mandate) throws XPathExpressionException, MOAIDException {
+ super(mandate);
+ Logger.debug("Initializing corporate body mandate container.");
+
+ setAnnotation(xPath.evaluate(S2Constants.MANDATE_ANNOTATION_QUERY, new InputSource(new StringReader(mandate))));
+ setCorpMandatorFullName(xPath.evaluate(S2Constants.MANDATE_MANDATOR_CORPBODY_FULLNAME_QUERY, new InputSource(new StringReader(mandate))));
+ setCorpMandatorIdentificationType(xPath.evaluate(S2Constants.MANDATE_MANDATOR_CORPBODY_IDTYPE_QUERY, new InputSource(new StringReader(mandate))));
+ setCorpMandatorIdentificationValue(xPath.evaluate(S2Constants.MANDATE_MANDATOR_CORPBODY_IDVALUE_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateIssueDate(xPath.evaluate(S2Constants.MANDATE_ISSUEDDATE_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateIssuePlace(xPath.evaluate(S2Constants.MANDATE_ISSUEDPLACE_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateIssueTime(xPath.evaluate(S2Constants.MANDATE_ISSUEDTIME_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateValidFrom(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_VALIDFROM_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateValidTo(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_VALIDTO_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeBirthDate(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_DATEOFBIRTH_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeFamilyName(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_FAMILYNAME_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeGivenName(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_GIVENNAME_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeIdentificationType(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_IDTYPE_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeIdentificationValue(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_IDVALUE_QUERY, new InputSource(new StringReader(mandate))));
+ setSimpleMandateContent(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_TXTDESC_QUERY, new InputSource(new StringReader(mandate))));
+
+ // check if all necessary fields are present
+ Logger.debug("Starting mandate structure validation");
+ try {
+ validateMandateStructure(localMethods); // TODO
+ } catch (Exception e) {
+
+ if (e instanceof MOAIDException) {
+ Logger.error("Could not validate mandate structure.");
+ throw new MOAIDException("stork.16", new Object[] {e.getMessage()}); // TODO
+ } else {
+ Logger.error("Error during mandate structure validation.");
+ throw new MOAIDException("stork.16", new Object[] {e.getMessage()}); // TODO
+ }
+
+ }
+
+ }
+
+ public String getCorpMandatorIdentificationValue() {
+ return corpMandatorIdentificationValue;
+ }
+
+ public void setCorpMandatorIdentificationValue(String corpMandatorIdentificationValue) {
+ Logger.debug("Setting corpMandatorIdentificationValue to AT/" + corpMandatorIdentificationValue);
+ this.corpMandatorIdentificationValue = "AT/" + corpMandatorIdentificationValue;
+ }
+
+ public String getCorpMandatorIdentificationType() {
+ return corpMandatorIdentificationType;
+ }
+
+ public void setCorpMandatorIdentificationType(String corpMandatorIdentificationType) {
+ this.corpMandatorIdentificationType = corpMandatorIdentificationType;
+ }
+
+ public String getCorpMandatorFullName() {
+ return corpMandatorFullName;
+ }
+
+ public void setCorpMandatorFullName(String corpMandatorFullName) {
+ this.corpMandatorFullName = corpMandatorFullName;
+ }
+
+
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java
new file mode 100644
index 000000000..e01a7526a
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java
@@ -0,0 +1,100 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import java.io.Serializable;
+
+/**
+ * Holds info about an ongoing but yet incomplete stork authnrequest process.
+ */
+public class DataContainer implements Serializable {
+
+ /** The Constant serialVersionUID. */
+ private static final long serialVersionUID = -8765997480582363012L;
+
+ /** The incoming request. */
+ private MOASTORKRequest request;
+
+ /** The yet incomplete response. */
+ private MOASTORKResponse response;
+
+ /** The target. */
+ private String target;
+
+ /** The remote address. */
+ private String remoteAddress;
+
+ /**
+ * Gets the request.
+ *
+ * @return the request
+ */
+ public MOASTORKRequest getRequest() {
+ return request;
+ }
+
+ /**
+ * Sets the request.
+ *
+ * @param moaStorkRequest the new request
+ */
+ public void setRequest(MOASTORKRequest moaStorkRequest) {
+ this.request = moaStorkRequest;
+ }
+
+ /**
+ * Gets the response.
+ *
+ * @return the response
+ */
+ public MOASTORKResponse getResponse() {
+ return response;
+ }
+
+ /**
+ * Sets the response.
+ *
+ * @param moaStorkResponse the new response
+ */
+ public void setResponse(MOASTORKResponse moaStorkResponse) {
+ this.response = moaStorkResponse;
+ }
+
+ /**
+ * Gets the remote address.
+ *
+ * @return the remote address
+ */
+ public String getRemoteAddress() {
+ return remoteAddress;
+ }
+
+ /**
+ * Sets the remote address.
+ *
+ * @param remoteAddress the new remote address
+ */
+ public void setRemoteAddress(String remoteAddress) {
+ this.remoteAddress = remoteAddress;
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java
new file mode 100644
index 000000000..096f223d7
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java
@@ -0,0 +1,53 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider;
+
+public class ExternalAttributeRequestRequiredException extends Exception {
+
+ /** The Constant serialVersionUID. */
+ private static final long serialVersionUID = 5207631348933518908L;
+
+ /** The ap. */
+ private AttributeProvider ap;
+
+ /**
+ * Instantiates a new external attribute request required exception.
+ *
+ * @param provider the provider
+ */
+ public ExternalAttributeRequestRequiredException(AttributeProvider provider) {
+ ap = provider;
+ }
+
+ /**
+ * Gets the ap that caused the exception.
+ *
+ * @return the ap
+ */
+ public AttributeProvider getAp() {
+ return ap;
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java
new file mode 100644
index 000000000..2c7e5b539
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java
@@ -0,0 +1,248 @@
+/*******************************************************************************
+ * 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.stork2;
+
+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.*;
+
+/**
+ * @author bsuzic
+ * Date: 2/19/14, Time: 4:42 PM
+ *
+ * @author tlenz
+ * Date: 23.10.14
+ */
+public class MOAAttributeProvider {
+ private final IAuthData authData;
+ private static final Map<String, String> storkAttributeSimpleMapping;
+ private static final Map<String, String> storkAttributeFunctionMapping;
+ private final MOASTORKRequest moastorkRequest;
+
+ // mappings for attribute population methods
+ // based on mapping of moa authndata and executing functions to extract attributes
+ static {
+ Map<String, String> tempSimpleMap = new HashMap<String, String>();
+ tempSimpleMap.put("givenName", "getGivenName");
+ tempSimpleMap.put("surname", "getFamilyName");
+ tempSimpleMap.put("MSOrganization", "getPvpAttribute_OU");
+ storkAttributeSimpleMapping = Collections.unmodifiableMap(tempSimpleMap);
+
+ Map<String, String> tempFunctionMap = new HashMap<String, String>();
+ tempFunctionMap.put("eIdentifier", "geteIdentifier");
+ 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);
+
+ }
+
+ public MOAAttributeProvider(IAuthData authData, MOASTORKRequest moastorkRequest) {
+ this.authData = authData;
+ this.moastorkRequest = moastorkRequest;
+
+ }
+
+ 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 {
+ 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);
+ 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);
+ } catch (NoSuchMethodException e) {
+ Logger.error("Could not found MOA extraction method while getting attribute: " + storkAttribute);
+ 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), PersonalAttribute.class);
+ populateAttributeWithMethod(method, this, attributeList, storkAttribute, requestedAttribute);
+ } catch (NoSuchMethodException e) {
+ Logger.error("Could not found MOA extraction method while getting attribute: " + storkAttribute);
+ }
+ } else {
+ Logger.debug("MOA method for extraction of attribute " + storkAttribute + " not defined.");
+ }
+ }
+
+ 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());
+ } catch (BuildException be) {
+ Logger.error("Stork eid could not be constructed; " + be.getMessage());
+ return null; // TODO error
+ }
+ }
+
+ private List<String> getECApplicationRole(PersonalAttribute personalAttribute) {
+ List<String> storkRoles = null;
+
+ if (authData.getAuthenticationRoles() != null
+ && authData.getAuthenticationRoles().size() > 0) {
+
+ storkRoles = new ArrayList<String>();
+ PVPtoSTORKMapper mapper = PVPtoSTORKMapper.getInstance();
+ for (AuthenticationRole el : authData.getAuthenticationRoles()) {
+ String storkRole = mapper.map(el);
+ if (MiscUtil.isNotEmpty(storkRole))
+ storkRoles.add(storkRole);
+ }
+ }
+ return storkRoles;
+ }
+
+ 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, PersonalAttribute requestedAttribute) {
+ try {
+ 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(requestedAttribute.isRequired());
+
+ if (attributeValue != null) {
+ newAttribute.setStatus(AttributeStatusType.AVAILABLE.value());
+ Logger.info("Got attribute value: " + attributeValue);
+
+ if (attributeValue instanceof String)
+ newAttribute.setValue(new ArrayList<String>(Collections.singletonList((String)attributeValue)));
+
+ else if (attributeValue instanceof List<?>) {
+ List<?> attributeValueList = (List<?>) attributeValue;
+ if (attributeValueList.size() > 0 && attributeValueList.get(0) instanceof String) {
+ newAttribute.setValue((List<String>) attributeValueList);
+
+ } else {
+ Logger.info("Attribute " + storkAttribute + " is not available.");
+ newAttribute.setStatus(AttributeStatusType.NOT_AVAILABLE.value());
+
+ }
+
+ } else {
+ Logger.error("Receive an unsupported type for attribute " + storkAttribute);
+
+ }
+ attributeList.add(newAttribute);
+
+ } else {
+ Logger.info("Attribute " + storkAttribute + " is not available.");
+ newAttribute.setStatus(AttributeStatusType.NOT_AVAILABLE.value());
+ }
+
+ } catch (InvocationTargetException e) {
+ Logger.error("Invocation target exception while getting attribute: " + storkAttribute);
+ Logger.debug(e);
+ } catch (IllegalAccessException e) {
+ Logger.error("Illegal access exception while getting attribute: " + storkAttribute);
+ Logger.debug(e);
+ } catch (NullPointerException e) {
+ Logger.error("Could not find method: " + storkAttribute);
+ Logger.debug(e);
+ }
+ }
+
+
+}
+
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java
new file mode 100644
index 000000000..4e666c21c
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java
@@ -0,0 +1,265 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.opensaml.saml2.core.Attribute;
+
+import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder;
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.config.auth.data.DynamicOAAuthParameters;
+import at.gv.egovernment.moa.id.moduls.RequestImpl;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder;
+import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Constants;
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
+import eu.stork.peps.auth.commons.STORKAttrQueryRequest;
+import eu.stork.peps.auth.commons.STORKAuthnRequest;
+import eu.stork.peps.auth.commons.STORKAuthnResponse;
+
+/**
+ * Implements MOA request and stores StorkAuthn/Attr-Request related data.
+ *
+ * @author bsuzic
+ */
+public class MOASTORKRequest extends RequestImpl {
+
+ /**
+ * @param req
+ * @throws ConfigurationException
+ */
+ public MOASTORKRequest(HttpServletRequest req)
+ throws ConfigurationException {
+ super(req);
+ }
+
+ public static final List<String> DEFAULTREQUESTEDATTRFORINTERFEDERATION = Arrays.asList(
+ new String[] {
+ PVPConstants.BPK_NAME,
+ PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME,
+ PVPConstants.GIVEN_NAME_NAME,
+ PVPConstants.PRINCIPAL_NAME_NAME,
+ PVPConstants.BIRTHDATE_NAME,
+ PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME,
+ });
+
+ /** The Constant serialVersionUID. */
+ private static final long serialVersionUID = 4581953368724501376L;
+
+ /** The request id. */
+ private String requestID;
+
+ /** The stork authn request. */
+ private STORKAuthnRequest storkAuthnRequest;
+
+ /** The stork attr query request. */
+ private STORKAttrQueryRequest storkAttrQueryRequest;
+
+
+ /**
+ * Sets the sTORK authn request.
+ *
+ * @param request the new sTORK authn request
+ */
+ public void setSTORKAuthnRequest(STORKAuthnRequest request) {
+ this.storkAuthnRequest = request;
+ }
+
+ /**
+ * Sets the sTORK attr request.
+ *
+ * @param request the new sTORK attr request
+ */
+ public void setSTORKAttrRequest(STORKAttrQueryRequest request) {
+ this.storkAttrQueryRequest = request;
+ }
+
+ /**
+ * Checks if the container holds an AttrQueryRequest
+ *
+ * @return true, if is attr request
+ */
+ public boolean isAttrRequest() {
+ return null != storkAttrQueryRequest;
+ }
+
+ /**
+ * Checks if the container holds an AuthnRequest
+ *
+ * @return true, if is authn request
+ */
+ public boolean isAuthnRequest() {
+ return null != storkAuthnRequest;
+ }
+
+ /**
+ * Gets the stork authn request.
+ *
+ * @return the stork authn request
+ */
+ public STORKAuthnRequest getStorkAuthnRequest() {
+ return this.storkAuthnRequest;
+ }
+
+ /**
+ * Gets the stork attr query request.
+ *
+ * @return the stork attr query request
+ */
+ public STORKAttrQueryRequest getStorkAttrQueryRequest() {
+ return this.storkAttrQueryRequest;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#getOAURL()
+ */
+ public String getOAURL() {
+ if (isAuthnRequest())
+ return storkAuthnRequest.getAssertionConsumerServiceURL();
+ else if (isAttrRequest())
+ return storkAttrQueryRequest.getAssertionConsumerServiceURL();
+ else {
+ Logger.error("There is no authentication or attribute request contained in MOASTORKRequest.");
+ return null;
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#isPassiv()
+ */
+ public boolean isPassiv() {
+ return false;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#forceAuth()
+ */
+ public boolean forceAuth() {
+ return false;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#isSSOSupported()
+ */
+ public boolean isSSOSupported() {
+ return false;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#setRequestID(java.lang.String)
+ */
+ public void setRequestID(String id) {
+ this.requestID = id;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#getRequestID()
+ */
+ public String getRequestID() {
+ return this.requestID;
+ }
+
+ /**
+ * Gets the personal attribute list.
+ *
+ * @return the personal attribute list
+ */
+ public IPersonalAttributeList getPersonalAttributeList() {
+ if(isAttrRequest())
+ return this.storkAttrQueryRequest.getPersonalAttributeList();
+ else
+ return this.storkAuthnRequest.getPersonalAttributeList();
+ }
+
+ /**
+ * Gets the sp country.
+ *
+ * @return the sp country
+ */
+ public String getSpCountry() {
+ if(isAttrRequest())
+ return this.storkAttrQueryRequest.getSpCountry();
+ else
+ return this.storkAuthnRequest.getSpCountry();
+ }
+
+ /**
+ * Gets the assertion consumer service url.
+ *
+ * @return the assertion consumer service url
+ */
+ public String getAssertionConsumerServiceURL() {
+ if(isAttrRequest())
+ return this.storkAttrQueryRequest.getAssertionConsumerServiceURL();
+ else
+ return this.storkAuthnRequest.getAssertionConsumerServiceURL();
+ }
+
+ /**
+ * Gets the citizen country code.
+ *
+ * @return the citizen country code
+ */
+ public String getCitizenCountryCode() {
+ if(isAttrRequest())
+ return this.storkAttrQueryRequest.getCitizenCountryCode();
+ else
+ return this.storkAuthnRequest.getCitizenCountryCode();
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes()
+ */
+ @Override
+ public List<Attribute> getRequestedAttributes() {
+ //TODO: only for testing with MOA-ID as PVP Stammportal
+ IOAAuthParameters oa;
+ try {
+ oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(getOAURL());
+ oa = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oa, this);
+
+ DynamicOAAuthParameters tmp = (DynamicOAAuthParameters) oa;
+ tmp.setBusinessTarget(Constants.URN_PREFIX_CDID + "+BF");
+
+ return AttributQueryBuilder.buildSAML2AttributeList(tmp, DEFAULTREQUESTEDATTRFORINTERFEDERATION.iterator());
+
+ } catch (ConfigurationException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ return null;
+ }
+
+ //return new ArrayList<Attribute>();
+
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java
new file mode 100644
index 000000000..a233835bf
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java
@@ -0,0 +1,308 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import at.gv.egovernment.moa.id.config.ConfigurationException;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.RequestImpl;
+import at.gv.egovernment.moa.logging.Logger;
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
+import eu.stork.peps.auth.commons.PersonalAttributeList;
+import eu.stork.peps.auth.commons.STORKAttrQueryResponse;
+import eu.stork.peps.auth.commons.STORKAuthnResponse;
+
+import java.io.Serializable;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.opensaml.saml2.core.Attribute;
+
+/**
+ * Implements MOA request and stores StorkAuthn/Attr-Request related data.
+ *
+ * @author bsuzic
+ */
+public class MOASTORKResponse extends RequestImpl {
+
+ /**
+ * @param req
+ * @throws ConfigurationException
+ */
+ public MOASTORKResponse(HttpServletRequest req)
+ throws ConfigurationException {
+ super(req);
+ }
+
+ /**
+ * The Constant serialVersionUID.
+ */
+ private static final long serialVersionUID = -5798803155055518747L;
+
+ /**
+ * The stork authn request.
+ */
+ private STORKAuthnResponse storkAuthnResponse;
+
+ /**
+ * The stork attr query request.
+ */
+ private STORKAttrQueryResponse storkAttrQueryResponse;
+
+ /**
+ * The action.
+ */
+ String action = null;
+
+ /**
+ * The token
+ */
+ private byte[] storkAuthnResponseToken = null;
+
+ /**
+ * The request id.
+ */
+ private String requestID;
+
+
+ /**
+ * The module.
+ */
+ String module = null;
+
+ /**
+ * The target.
+ */
+ private String target = null;
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#requestedModule()
+ */
+ public String requestedModule() {
+ return this.module;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#requestedAction()
+ */
+ public String requestedAction() {
+ return action;
+ }
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#getRequestID()
+ */
+ public String getRequestID() {
+ return this.requestID;
+ }
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#getTarget()
+ */
+ public String getTarget() {
+ return this.target;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#isSSOSupported()
+ */
+ public boolean isSSOSupported() {
+ return false;
+ }
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#forceAuth()
+ */
+ public boolean forceAuth() {
+ return false;
+ }
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#setModule(java.lang.String)
+ */
+ public void setModule(String module) {
+ this.module = module;
+ }
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#setRequestID(java.lang.String)
+ */
+ public void setRequestID(String id) {
+ this.requestID = id;
+ }
+
+ /**
+ * Sets the sTORK authn response.
+ *
+ * @param request the new sTORK authn response
+ */
+ public void setSTORKAuthnResponse(STORKAuthnResponse request) {
+ this.storkAuthnResponse = request;
+ }
+
+ /**
+ * Sets the sTORK authn response token
+ *
+ * @param request the new sTORK authn response token
+ */
+ public void setSTORKAuthnResponseToken(byte[] token) {
+ this.storkAuthnResponseToken = token;
+ }
+
+ /**
+ * Gets the sTORK authn response token .
+ *
+ * @param request the new sTORK authn response
+ */
+ public byte[] getSTORKAuthnResponseToken() {
+ return this.storkAuthnResponseToken;
+ }
+ /**
+ * Sets the sTORK attr response.
+ *
+ * @param request the new sTORK attr response
+ */
+ public void setSTORKAttrResponse(STORKAttrQueryResponse request) {
+ this.storkAttrQueryResponse = request;
+ }
+
+ /**
+ * Checks if the container holds an AttrQuery
+ *
+ * @return true, if is attr response
+ */
+ public boolean isAttrResponse() {
+ return null != storkAttrQueryResponse;
+ }
+
+ /**
+ * Checks if the container holds an AuthnRequest
+ *
+ * @return true, if is authn response
+ */
+ public boolean isAuthnResponse() {
+ return null != storkAuthnResponse;
+ }
+
+
+ /**
+ * Gets the AuthnResponse.
+ *
+ * @return the stork authn response
+ */
+ public STORKAuthnResponse getStorkAuthnResponse() {
+ return this.storkAuthnResponse;
+ }
+
+ /**
+ * Gets the AttrQueryResponse.
+ *
+ * @return the stork attr query response
+ */
+ public STORKAttrQueryResponse getStorkAttrQueryResponse() {
+ return this.storkAttrQueryResponse;
+ }
+
+ /**
+ * Gets the personal attribute list.
+ *
+ * @return the personal attribute list
+ */
+ public IPersonalAttributeList getPersonalAttributeList() {
+ if (isAttrResponse())
+ return this.storkAttrQueryResponse.getPersonalAttributeList();
+ else
+ return this.storkAuthnResponse.getPersonalAttributeList();
+ }
+
+ /**
+ * Sets the personal attribute list.
+ *
+ * @param populateAttributes the new personal attribute list
+ */
+ public void setPersonalAttributeList(PersonalAttributeList populateAttributes) {
+ if (isAttrResponse())
+ this.storkAttrQueryResponse.setPersonalAttributeList(populateAttributes);
+ else
+ this.storkAuthnResponse.setPersonalAttributeList(populateAttributes);
+ }
+
+ /**
+ * Sets the country.
+ *
+ * @param spCountry the new country
+ */
+ public void setCountry(String spCountry) {
+ if (isAttrResponse())
+ this.storkAttrQueryResponse.setCountry(spCountry);
+ else
+ this.storkAuthnResponse.setCountry(spCountry);
+ }
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#getOAURL()
+ */
+ public String getOAURL() {
+ if (isAuthnResponse())
+ return storkAuthnResponse.getAudienceRestriction();
+ else if (isAttrResponse())
+ return storkAttrQueryResponse.getAudienceRestriction();
+ else {
+ Logger.error("There is no authentication or attribute request contained in MOASTORKRequest.");
+ return null;
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#isPassiv()
+ */
+ public boolean isPassiv() {
+ return false;
+ }
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.IRequest#setAction(java.lang.String)
+ */
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes()
+ */
+ @Override
+ public List<Attribute> getRequestedAttributes() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java
new file mode 100644
index 000000000..a3fac0f6e
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java
@@ -0,0 +1,182 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.logging.Logger;
+
+import javax.xml.xpath.XPath;
+import javax.xml.xpath.XPathExpressionException;
+import javax.xml.xpath.XPathFactory;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+
+/**
+ * @author bsuzic
+ * Date: 5/5/14, Time: 2:35 PM
+ */
+public abstract class MandateContainer {
+ protected String mandateIssuePlace = null;
+ protected String mandateIssueDate = null;
+ protected String mandateIssueTime = null;
+ protected String simpleMandateContent = null;
+ protected String mandateValidFrom = null;
+ protected String mandateValidTo = null;
+ protected String annotation = null;
+ protected String physicalRepresentativeIdentificationValue = null;
+ protected String physicalRepresentativeIdentificationType = null;
+ protected String physicalRepresentativeGivenName = null;
+ protected String physicalRepresentativeFamilyName = null;
+ protected String physicalRepresentativeBirthDate = null;
+ protected XPath xPath = null;
+
+
+ public MandateContainer(String mandate) throws XPathExpressionException, MOAIDException {
+ Logger.debug("Received mandate content for processing: " + mandate);
+
+ xPath = XPathFactory.newInstance().newXPath();
+ HashMap<String, String> prefMap = new HashMap<String, String>() {{
+ put(S2Constants.MANDATE_PREFIX, S2Constants.MANDATE_NS);
+ put(S2Constants.PERSONDATA_PREFIX, S2Constants.PERSONDATA_NS);
+ put(S2Constants.XMLDSIG_PREFIX, S2Constants.XMLDSIG_NS);
+ }};
+
+ SimpleNamespaceContext namespace = new SimpleNamespaceContext(prefMap);
+ xPath.setNamespaceContext(namespace);
+ }
+
+
+ public void validateMandateStructure(String localMethods[]) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, MOAIDException {
+ for (String localMethod : localMethods) {
+ Method method = this.getClass().getMethod(localMethod);
+ Object x = method.invoke(this);
+ if ((x == null) || x.toString().length() == 0) {
+ throw new MOAIDException("stork.16", new Object[] {localMethod}); // TODO
+ }
+ }
+ Logger.debug("Mandate structure validated");
+ }
+
+
+ public String getMandateIssuePlace() {
+ return mandateIssuePlace;
+ }
+
+ public void setMandateIssuePlace(String mandateIssuePlace) {
+ this.mandateIssuePlace = mandateIssuePlace;
+ }
+
+ public String getMandateIssueDate() {
+ return mandateIssueDate;
+ }
+
+ public void setMandateIssueDate(String mandateIssueDate) {
+ this.mandateIssueDate = mandateIssueDate;
+ }
+
+ public String getMandateIssueTime() {
+ return mandateIssueTime;
+ }
+
+ public void setMandateIssueTime(String mandateIssueTime) {
+ this.mandateIssueTime = mandateIssueTime;
+ }
+
+ public String getSimpleMandateContent() {
+ return simpleMandateContent;
+ }
+
+ public void setSimpleMandateContent(String simpleMandateContent) {
+ this.simpleMandateContent = simpleMandateContent;
+ }
+
+ public String getMandateValidFrom() {
+ return mandateValidFrom;
+ }
+
+ public void setMandateValidFrom(String mandateValidFrom) {
+ this.mandateValidFrom = mandateValidFrom;
+ }
+
+ public String getMandateValidTo() {
+ return mandateValidTo;
+ }
+
+ public void setMandateValidTo(String mandateValidTo) {
+ this.mandateValidTo = mandateValidTo;
+ }
+
+ public String getPhysicalRepresentativeIdentificationValue() {
+ return physicalRepresentativeIdentificationValue;
+ }
+
+ public void setPhysicalRepresentativeIdentificationValue(String physicalRepresentativeIdentificationValue) {
+ this.physicalRepresentativeIdentificationValue = physicalRepresentativeIdentificationValue;
+ }
+
+ public String getPhysicalRepresentativeIdentificationType() {
+ return physicalRepresentativeIdentificationType;
+ }
+
+ public void setPhysicalRepresentativeIdentificationType(String physicalRepresentativeIdentificationType) {
+ this.physicalRepresentativeIdentificationType = physicalRepresentativeIdentificationType;
+ }
+
+ public String getPhysicalRepresentativeGivenName() {
+ return physicalRepresentativeGivenName;
+ }
+
+ public void setPhysicalRepresentativeGivenName(String physicalRepresentativeGivenName) {
+ this.physicalRepresentativeGivenName = physicalRepresentativeGivenName;
+ }
+
+ public String getPhysicalRepresentativeFamilyName() {
+ return physicalRepresentativeFamilyName;
+ }
+
+ public void setPhysicalRepresentativeFamilyName(String physicalRepresentativeFamilyName) {
+ this.physicalRepresentativeFamilyName = physicalRepresentativeFamilyName;
+ }
+
+ public String getPhysicalRepresentativeBirthDate() {
+ return physicalRepresentativeBirthDate;
+ }
+
+ public void setPhysicalRepresentativeBirthDate(String physicalRepresentativeBirthDate) {
+ // making it conform to STORK dateOfBirth specifications, removing dash
+ this.physicalRepresentativeBirthDate = physicalRepresentativeBirthDate.replaceAll("-","");
+ }
+
+ public String getAnnotation() {
+ return annotation;
+ }
+
+ public void setAnnotation(String annotation) {
+ this.annotation = annotation;
+ }
+
+
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java
new file mode 100644
index 000000000..2351450e4
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java
@@ -0,0 +1,602 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import at.gv.egovernment.moa.id.auth.builder.BPKBuilder;
+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.BuildException;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+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;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Constants;
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
+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.StringUtils;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBElement;
+import javax.xml.bind.Marshaller;
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.XMLGregorianCalendar;
+import javax.xml.namespace.QName;
+import java.io.StringWriter;
+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 {
+
+ private IAuthData authData;
+ private MOASTORKRequest moaStorkRequest;
+ private IdentityLink representingIdentityLink;
+ private Integer QAALevel;
+ private byte[] originalContent;
+
+ public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException {
+ Logger.debug("Entering AttributeRequest for MandateProvider");
+ httpResp.reset();
+ this.representingIdentityLink = authData.getIdentityLink();
+ this.QAALevel = translateQAALevel(authData.getQAALevel());
+
+ // preparing original content and removing sensitive data from it
+ 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("<pd:Value>.*?==</pd:Value><pd:Type>urn:publicid:gv.at:baseid</pd:Type>","<pd:Value></pd:Value><pd:Type></pd:Type>");;
+ Logger.debug("Removing personal identification value and type from original mandate ");
+ originalContent = StringUtils.getBytesUtf8(originalMandate);
+
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(req.getOAURL());
+ if (oaParam == null)
+ throw new AuthenticationException("stork.12", new Object[]{req.getOAURL()});
+
+ MOASTORKResponse moaStorkResponse = new MOASTORKResponse(httpReq);
+ STORKAttrQueryResponse attrResponse = new STORKAttrQueryResponse();
+
+ this.authData = authData;
+
+ if ((req instanceof MOASTORKRequest)) {
+ this.moaStorkRequest = (MOASTORKRequest) req;
+ } else {
+ Logger.error("Internal error - did not receive MOASTORKRequest as expected");
+ 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.27", new Object[]{});
+ }
+
+ MandateContainer mandateContainer = null;
+
+ try {
+ mandateContainer = new CorporateBodyMandateContainer(new String(authData.getMISMandate().getMandate(), "UTF-8"));
+ } catch (Exception ex) {
+ try {
+ 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.27", new Object[]{});
+ }
+ }
+
+ IPersonalAttributeList sourceAttributeList = moaStorkRequest.getStorkAttrQueryRequest().getPersonalAttributeList();
+
+ IPersonalAttributeList attributeList = new PersonalAttributeList();
+
+ // according to new mapping, only mandate attribute is directly relevant
+ for (PersonalAttribute currentAttribute : sourceAttributeList) {
+ 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")) { // deprecated
+ RepresentationPersonType representative = getRepresentative(mandateContainer, currentAttribute);
+ attributeList.add(marshallComplexAttribute(currentAttribute, representative));
+ } else if (currentAttribute.getName().equals("represented")) {
+ RepresentationPersonType represented = getRepresented(mandateContainer, currentAttribute);
+ attributeList.add(marshallComplexAttribute(currentAttribute, represented));
+ } else if (currentAttribute.getName().equals("mandate")) {
+ 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) {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(legalName), AttributeStatusType.AVAILABLE.value()));
+ } else {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(legalName), AttributeStatusType.NOT_AVAILABLE.value()));
+ }
+ } else if (currentAttribute.getName().equals("eLPIdentifier")) {
+ String eLPIdentifier = geteLPIdentifier(mandateContainer, currentAttribute);
+ if (eLPIdentifier.length() > 0) {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(eLPIdentifier), AttributeStatusType.AVAILABLE.value()));
+ } else {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(eLPIdentifier), AttributeStatusType.NOT_AVAILABLE.value()));
+ }
+ } else if (currentAttribute.getName().equals("type")) {
+ String type = getCompanyType(mandateContainer, currentAttribute);
+ if (type.length() > 0) {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(type), AttributeStatusType.AVAILABLE.value()));
+ } else {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(type), AttributeStatusType.NOT_AVAILABLE.value()));
+ }
+ } else if (currentAttribute.getName().equals("status")) {
+ String status = getCompanyStatus(mandateContainer, currentAttribute);
+ if (status.length() > 0) {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(status), AttributeStatusType.AVAILABLE.value()));
+ } else {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(status), AttributeStatusType.NOT_AVAILABLE.value()));
+ }
+ } else if (currentAttribute.getName().equals("translatableType")) {
+ String translatableType = getCompanyTranslatableType(mandateContainer, currentAttribute);
+ if (translatableType.length() > 0) {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(translatableType), AttributeStatusType.AVAILABLE.value()));
+ } else {
+ attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(translatableType), AttributeStatusType.NOT_AVAILABLE.value()));
+ }
+ }
+
+ 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());
+ }
+
+ }
+
+
+// if (attrResponse.getPersonalAttributeList().size() == 0) {
+// Logger.error("AttributeList empty - could not retrieve attributes");
+// throw new MOAIDException("stork.16", new Object[]{}); // TODO MESSAGE
+// }
+
+ attrResponse.setPersonalAttributeList(attributeList);
+ moaStorkResponse.setSTORKAttrResponse(attrResponse);
+
+ Logger.debug("Attributes retrieved: " + moaStorkResponse.getStorkAttrQueryResponse().getPersonalAttributeList().size() + " for SP country " + attrResponse.getCountry());
+
+ // Prepare extended attributes
+ Logger.debug("Preparing data container");
+
+ // create fresh container
+ DataContainer container = new DataContainer();
+
+ // - fill in the request we extracted above
+ container.setRequest(moaStorkRequest);
+
+ // - fill in the partial response created above
+ container.setResponse(moaStorkResponse);
+
+ container.setRemoteAddress(httpReq.getRemoteAddr());
+
+ Logger.debug("Data container prepared");
+
+ // ask for consent if necessary
+ if (oaParam.isRequireConsentForStorkAttributes())
+ new ConsentEvaluator().requestConsent(container, httpReq, httpResp, authData, oaParam);
+ else
+ new ConsentEvaluator().generateSTORKResponse(httpResp, container);
+
+ return null;
+ }
+
+ private Integer translateQAALevel(String qaaLevel) throws MOAIDException {
+ if (qaaLevel.equals(PVPConstants.STORK_QAA_1_1))
+ return 1;
+ if (qaaLevel.equals(PVPConstants.STORK_QAA_1_2))
+ return 2;
+ if (qaaLevel.equals(PVPConstants.STORK_QAA_1_3))
+ return 3;
+ if (qaaLevel.equals(PVPConstants.STORK_QAA_1_4))
+ return 4;
+ Logger.error("Wrong QAA Number format");
+ throw new MOAIDException("stork.28", new Object[]{});
+ }
+
+ private String geteLPIdentifier(MandateContainer mandateContainer, PersonalAttribute currentAttribute) throws MOAIDException {
+ RepresentationPersonType represented = getRepresented(mandateContainer, currentAttribute);
+ if (mandateContainer instanceof CorporateBodyMandateContainer) {
+ return represented.getELPIdentifier();
+ } else if (currentAttribute.isRequired()) {
+ Logger.error("Cannot provide eLPIdentifier for natural person.");
+ 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();
+ try {
+ if (obj instanceof MandateContentType) {
+ final Marshaller marshaller = JAXBContext.newInstance(MandateContentType.class).createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
+ marshaller.marshal(new JAXBElement<MandateContentType>(new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()), MandateContentType.class, null, (MandateContentType) obj), stringWriter);
+ } else if (obj instanceof MandateType) {
+ final Marshaller marshaller = JAXBContext.newInstance(MandateType.class).createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
+ marshaller.marshal(new JAXBElement<MandateType>(new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()), MandateType.class, null, (MandateType) obj), stringWriter);
+ } else if (obj instanceof RepresentationPersonType) {
+ final Marshaller marshaller = JAXBContext.newInstance(RepresentationPersonType.class).createMarshaller();
+ marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
+ marshaller.marshal(new JAXBElement<RepresentationPersonType>(new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()), RepresentationPersonType.class, null, (RepresentationPersonType) obj), stringWriter);
+ }
+
+ } catch (Exception ex) {
+ Logger.error("Could not marshall atrribute: " + currentAttribute.getName() + ", " + ex.getMessage());
+ return new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), new ArrayList<String>(), AttributeStatusType.NOT_AVAILABLE.value());
+ }
+ ArrayList<String> value = new ArrayList<String>();
+ value.add(stringWriter.toString());
+
+ PersonalAttribute personalAttribute = new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), value, AttributeStatusType.AVAILABLE.value());
+ return personalAttribute;
+ }
+
+
+ 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")) {
+ return "0"; // General Powers
+ } else if (mandateContainer.getAnnotation().equals("ZVRMitPostvollmacht")) {
+ return "0"; // General Powers
+ } else if (mandateContainer.getAnnotation().equals("EVB")) {
+ return "0"; // General Powers
+ } else if (mandateContainer.getAnnotation().equals("Einzelvertretungsbefugnis")) {
+ return "0"; // General Powers
+ } else if (mandateContainer.getAnnotation().equals("Prokura")) {
+ return "0"; // General Powers
+ } else if (mandateContainer.getAnnotation().equals("Notar")) {
+ return "0"; // General Powers
+ } else if (mandateContainer.getAnnotation().equals("Organwalter")) {
+ return "0"; // General Powers
+ } else if (mandateContainer.getAnnotation().equals("Rechtsanwalt")) {
+ return "0"; // General Powers
+ } else if (mandateContainer.getAnnotation().equals("Ziviltechniker")) {
+ return "0"; // General Powers
+ }
+ Logger.debug("Returning other type of mandate");
+ return "9";
+ }
+
+ private MandateType getMandateType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ MandateType mandateType = new MandateType();
+ RepresentationPersonType representative = getRepresentative(mandateContainer, sourceAttribute);
+ RepresentationPersonType represented = getRepresented(mandateContainer, sourceAttribute);
+ MandateContentType mandateContent = getMandateContent(mandateContainer, sourceAttribute);
+ mandateType.setRepresentative(representative);
+ mandateType.setRepresented(represented);
+ mandateType.getMandateContent().add(mandateContent);
+ Logger.debug("Complex attribute extracted: " + sourceAttribute.getName());
+ return mandateType;
+ }
+
+ private String getLegalName(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ RepresentationPersonType represented = getRepresented(mandateContainer, sourceAttribute);
+ if (mandateContainer instanceof CorporateBodyMandateContainer) {
+ represented.getLegalName();
+ //return represented.getName();
+ } else if (sourceAttribute.isRequired()) {
+ Logger.error("Cannot provide legalName for natural person.");
+ throw new MOAIDException("stork.19", new Object[]{sourceAttribute.getName()});
+ }
+ return "";
+ }
+
+
+ private String getLegalIdentificationType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ if (mandateContainer instanceof CorporateBodyMandateContainer) {
+ return ((CorporateBodyMandateContainer) mandateContainer).getCorpMandatorIdentificationType();
+ } else if (sourceAttribute.isRequired()) {
+ Logger.error("Cannot provide type for natural person.");
+ throw new MOAIDException("stork.19", new Object[]{sourceAttribute.getName()}); // TODO
+ }
+ return "";
+ }
+
+ private String getCompanyStatus(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ String legalName = getLegalName(mandateContainer, sourceAttribute);
+ if (legalName.contains("in Liquidation") || legalName.contains("in Liqu.")) {
+ return "L"; // liqudation
+ }
+ return "R";
+ }
+
+ private String getCompanyType(String legalName, String legalIdentificationType, PersonalAttribute sourceAttrivbute) throws MOAIDException {
+ // compile patterns for different organisation types
+ // sources: USP, WKO, LexAndTax
+
+ // gmbh patterns
+ ArrayList<Pattern> gmbhPatterns = new ArrayList<Pattern>();
+ gmbhPatterns.add(Pattern.compile(".+ GmbH(( in Liquidation)|( in Liqu.)){0,1}$"));
+ gmbhPatterns.add(Pattern.compile(".+ GesmbH$"));
+ gmbhPatterns.add(Pattern.compile(".+ Gesellschaft mit beschränkter Haftung$"));
+ gmbhPatterns.add(Pattern.compile(".+ Ges\\.m\\.b\\.H\\.$"));
+ gmbhPatterns.add(Pattern.compile(".+ G\\.m\\.b\\.H\\.$"));
+ gmbhPatterns.add(Pattern.compile(".+ Handelsges\\.m\\.b\\.H\\.$"));
+ gmbhPatterns.add(Pattern.compile(".+ Gesellschaft m\\.b\\.H\\.$"));
+
+ // ag patterns
+ ArrayList<Pattern> agPatterns = new ArrayList<Pattern>();
+ agPatterns.add(Pattern.compile(".+ AG$"));
+ agPatterns.add(Pattern.compile(".+ Aktiengesellschaft$"));
+
+ // og patterns
+ ArrayList<Pattern> ogPatterns = new ArrayList<Pattern>();
+ ogPatterns.add(Pattern.compile(".+ OG$"));
+ ogPatterns.add(Pattern.compile(".+ OHG$"));
+ ogPatterns.add(Pattern.compile(".+ offene Gesellschaft$"));
+
+ // kg patterns
+ ArrayList<Pattern> kgPatterns = new ArrayList<Pattern>();
+ kgPatterns.add(Pattern.compile(".+ KG$"));
+ kgPatterns.add(Pattern.compile(".+ Kommanditgesellschaft$"));
+
+ // eu patterns
+ ArrayList<Pattern> euPatterns = new ArrayList<Pattern>();
+ euPatterns.add(Pattern.compile(".+ eingetragene Unternehmerin$"));
+ euPatterns.add(Pattern.compile(".+ eingetragener Unternehmer$"));
+ euPatterns.add(Pattern.compile(".+ e\\.U\\.$"));
+
+
+ // company patterns
+ HashMap<String, ArrayList<Pattern>> companyPatterns = new HashMap<String, ArrayList<Pattern>>();
+ companyPatterns.put("GmbH", gmbhPatterns);
+ companyPatterns.put("AG", agPatterns);
+ companyPatterns.put("OG", ogPatterns);
+ companyPatterns.put("KG", kgPatterns);
+ companyPatterns.put("e.U.", euPatterns);
+
+ // iterate over different types of companies and check if the name ending matches
+ if (S2Constants.IDENTIFICATION_TYPE_COMPANY.equals(legalIdentificationType)) {
+ for (String companyType : companyPatterns.keySet()) {
+ for (Pattern pattern : companyPatterns.get(companyType)) {
+ if (pattern.matcher(legalName).matches()) {
+ return companyType;
+ }
+ }
+ }
+ }
+
+ // check if the subject is association
+ if (S2Constants.IDENTIFICATION_TYPE_ASSOCIATION.equals(legalIdentificationType)) {
+ return "Verein";
+ }
+
+ // check if the subject falls under category of others
+ if (S2Constants.IDENTIFICATION_TYPE_OTHERS.equals(legalIdentificationType)) {
+ return "ERsB";
+ }
+
+ return "";
+ }
+
+ private String getCompanyType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ // retrieve the registered subject name and identification type
+ String legalName = getLegalName(mandateContainer, sourceAttribute);
+ String legalIdentificationType = getLegalIdentificationType(mandateContainer, sourceAttribute);
+ return getCompanyType(legalName, legalIdentificationType, sourceAttribute);
+ }
+
+ private String getCompanyTranslatableType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ // retrieve first the company type
+ String companyType = getCompanyType(mandateContainer, sourceAttribute);
+
+ // translate company type based on the section 5.6 in STORK 2 D4.11
+ if (companyType.length() == 0) {
+ return "";
+ } else if (companyType.equals("GmbH")) {
+ return "G";
+ } else if (companyType.equals("AG")) {
+ return "A";
+ } else if (companyType.equals("OG")) {
+ return "O";
+ } else if (companyType.equals("KG")) {
+ return "K";
+ } else {
+ return "";
+ }
+ }
+
+
+ private String getRepresentedStorkeIdentifier(MandateContainer mandateContainer) throws MOAIDException {
+
+ if (!(mandateContainer instanceof PhyPersonMandateContainer)) {
+ Logger.error("Physical person mandate container missing");
+ throw new MOAIDException("stork.20", new Object[]{}); // TODO
+ }
+
+ PhyPersonMandateContainer phyPersonMandateContainer = (PhyPersonMandateContainer) mandateContainer;
+
+ if (!phyPersonMandateContainer.getPhyPersMandatorIdentificationType().equals(Constants.URN_PREFIX_BASEID)) {
+ Logger.error("Identification type of represented person from MIS is not correct");
+ throw new MOAIDException("stork.20", new Object[]{}); // TODO
+ }
+
+ if (phyPersonMandateContainer.getPhyPersMandatorIdentificationValue().length() != 24) {
+ Logger.error("Identification value of represented person from MIS is not correct");
+ throw new MOAIDException("stork.20", new Object[]{}); // TODO
+ }
+
+ if ((this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry() == null) || (this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry().length() == 0)) {
+ Logger.error("Error accessing SP country code");
+ 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 {
+ if ((this.representingIdentityLink == null)) {
+ Logger.error("Error accessing identityLink while fetching mandate attribute");
+ throw new MOAIDException("stork.20", new Object[]{}); // TODO
+ }
+
+ if ((this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry() == null) || (this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry().length() == 0)) {
+ Logger.error("Error accessing SP country code");
+ throw new MOAIDException("stork.20", new Object[]{}); // TODO
+ }
+
+ if (!this.representingIdentityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) {
+ Logger.error("Incorrect identity link (local): identification type is not correct! Got: " + this.representingIdentityLink.getIdentificationType());
+ throw new MOAIDException("stork.20", new Object[]{}); // TODO
+ }
+
+ if (!mandateContainer.getPhysicalRepresentativeIdentificationType().equals(Constants.URN_PREFIX_BASEID)) {
+ Logger.error("Incorrect identity link (MIS): identification type is not correct! Got: " + this.representingIdentityLink.getIdentificationType() + " (representingIdentityLink) and " + mandateContainer.getPhysicalRepresentativeIdentificationType() + " (mandateContainer.phyRepresentative)");
+ Logger.debug("mandatecontainervalue: " + mandateContainer.getPhysicalRepresentativeIdentificationValue() + ", representingidentitylinkvalue: " + this.representingIdentityLink.getIdentificationValue());
+ throw new MOAIDException("stork.20", new Object[]{}); // TODO
+ }
+
+ if (!mandateContainer.getPhysicalRepresentativeIdentificationValue().equals(this.representingIdentityLink.getIdentificationValue())) {
+ Logger.error("Identification values from MIS and local service are not equal!");
+ throw new MOAIDException("stork.20", new Object[]{}); // TODO
+ }
+
+ BPKBuilder bpkBuilder = new BPKBuilder();
+ try {
+ return bpkBuilder.buildStorkeIdentifier(this.representingIdentityLink, 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
+ }
+
+ }
+
+ private RepresentationPersonType getRepresentative(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ RepresentationPersonType representative = new RepresentationPersonType();
+
+ representative.setEIdentifier(getRepresentingStorkeIdentifier(mandateContainer));
+ representative.setGivenName(mandateContainer.getPhysicalRepresentativeGivenName());
+ representative.setSurname(mandateContainer.getPhysicalRepresentativeFamilyName());
+ representative.setDateOfBirth(mandateContainer.getPhysicalRepresentativeBirthDate());
+
+ Logger.debug("Complex attribute extracted: " + sourceAttribute.getName());
+ return representative;
+ }
+
+ private RepresentationPersonType getRepresented(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ RepresentationPersonType represented = new RepresentationPersonType();
+
+ if (mandateContainer instanceof CorporateBodyMandateContainer) {
+ CorporateBodyMandateContainer corporateBodyMandateContainer = (CorporateBodyMandateContainer) mandateContainer;
+ represented.setELPIdentifier(corporateBodyMandateContainer.getCorpMandatorIdentificationValue());
+ represented.setLegalName(corporateBodyMandateContainer.getCorpMandatorFullName());
+ represented.setTextRegisteredAddress(null);
+ represented.setCanonicalRegisteredAddress(new CanonicalAddressType());
+ represented.setLegalForm(getCompanyType(corporateBodyMandateContainer.corpMandatorFullName, corporateBodyMandateContainer.corpMandatorIdentificationType, sourceAttribute));
+ } else if (mandateContainer instanceof PhyPersonMandateContainer) {
+ PhyPersonMandateContainer phyPersonMandateContainer = (PhyPersonMandateContainer) mandateContainer;
+ represented.setEIdentifier(getRepresentedStorkeIdentifier(mandateContainer));
+ represented.setGivenName(phyPersonMandateContainer.getPhyPersMandatorGivenName());
+ represented.setSurname(phyPersonMandateContainer.getPhyPersMandatorFamilyName());
+ represented.setDateOfBirth(phyPersonMandateContainer.getPhyPersMandatorBirthDate());
+ }
+
+ Logger.debug("Complex attribute extracted: " + sourceAttribute.getName());
+
+ return represented;
+ }
+
+
+ private MandateContentType getMandateContent(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException {
+ MandateContentType mandateContent = new MandateContentType();
+ try {
+ XMLGregorianCalendar validFrom = DatatypeFactory.newInstance().newXMLGregorianCalendar(mandateContainer.getMandateValidFrom());
+ XMLGregorianCalendar validTo = DatatypeFactory.newInstance().newXMLGregorianCalendar(mandateContainer.getMandateValidTo());
+ TimeRestrictionType timeRestriction = new TimeRestrictionType();
+ timeRestriction.setValidFrom(validFrom);
+ timeRestriction.setValidTo(validTo);
+ mandateContent.setTimeRestriction(timeRestriction);
+ } catch (DatatypeConfigurationException dte) {
+ Logger.error("Error converting date from mandate: " + mandateContainer.getMandateValidFrom() + ", " + mandateContainer.getMandateValidTo());
+ throw new MOAIDException("stork.20", new Object[]{});
+ }
+ mandateContent.setAQAA(this.QAALevel);
+ mandateContent.setOriginalMandate(originalContent);
+ mandateContent.setOriginalMandateType("application/xml");
+ TransactionLimitRestrictionType transactionLimit = new TransactionLimitRestrictionType();
+ mandateContent.setTransactionLimit(transactionLimit);
+ mandateContent.setIsJoint("");
+ mandateContent.setIsChained(false);
+ mandateContent.setTypeOfPower(mapPowersType(mandateContainer)); // TODO check
+ Logger.debug("Complex attribute extracted: " + sourceAttribute.getName());
+ return mandateContent;
+ }
+
+ public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) {
+ return true;
+ }
+
+ public String getDefaultActionName() {
+ return STORKProtocol.MANDATERETRIEVALREQUEST;
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java
new file mode 100644
index 000000000..c715b65eb
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java
@@ -0,0 +1,132 @@
+/*******************************************************************************
+ * 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.stork2;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.logging.Logger;
+import org.xml.sax.InputSource;
+
+import javax.xml.xpath.XPathExpressionException;
+import java.io.StringReader;
+
+/**
+ * Physical person representing physical person
+ * @author bsuzic
+ * Date: 4/30/14, Time: 11:29 AM
+ */
+public class PhyPersonMandateContainer extends MandateContainer {
+
+ private String phyPersMandatorIdentificationValue = null;
+ private String phyPersMandatorIdentificationType = null;
+ private String phyPersMandatorGivenName = null;
+ private String phyPersMandatorFamilyName = null;
+ private String phyPersMandatorBirthDate = null;
+
+ String localMethods[] = new String[]{"getPhyPersMandatorGivenName", "getPhyPersMandatorFamilyName", "getPhyPersMandatorBirthDate", "getPhyPersMandatorIdentificationValue",
+ "getPhyPersMandatorIdentificationType", "getMandateIssuePlace", "getMandateIssueDate", "getMandateIssueTime", "getSimpleMandateContent", "getMandateValidFrom",
+ "getMandateValidTo", "getPhysicalRepresentativeIdentificationValue", "getPhysicalRepresentativeIdentificationType", "getAnnotation",
+ "getPhysicalRepresentativeGivenName", "getPhysicalRepresentativeFamilyName", "getPhysicalRepresentativeBirthDate"
+ };
+
+
+ public PhyPersonMandateContainer(String mandate) throws XPathExpressionException, MOAIDException {
+ super(mandate);
+
+ setAnnotation(xPath.evaluate(S2Constants.MANDATE_ANNOTATION_QUERY, new InputSource(new StringReader(mandate))));
+ setPhyPersMandatorIdentificationType(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_IDTYPE_QUERY, new InputSource(new StringReader(mandate))));
+ setPhyPersMandatorIdentificationValue(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_IDVALUE_QUERY, new InputSource(new StringReader(mandate))));
+ setPhyPersMandatorGivenName(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_GIVENNAME_QUERY, new InputSource(new StringReader(mandate))));
+ setPhyPersMandatorFamilyName(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_FAMILYNAME_QUERY, new InputSource(new StringReader(mandate))));
+ setPhyPersMandatorBirthDate(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_DATEOFBIRTH_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateIssueDate(xPath.evaluate(S2Constants.MANDATE_ISSUEDDATE_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateIssuePlace(xPath.evaluate(S2Constants.MANDATE_ISSUEDPLACE_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateIssueTime(xPath.evaluate(S2Constants.MANDATE_ISSUEDTIME_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateValidFrom(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_VALIDFROM_QUERY, new InputSource(new StringReader(mandate))));
+ setMandateValidTo(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_VALIDTO_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeBirthDate(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_DATEOFBIRTH_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeFamilyName(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_FAMILYNAME_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeGivenName(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_GIVENNAME_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeIdentificationType(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_IDTYPE_QUERY, new InputSource(new StringReader(mandate))));
+ setPhysicalRepresentativeIdentificationValue(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_IDVALUE_QUERY, new InputSource(new StringReader(mandate))));
+ setSimpleMandateContent(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_TXTDESC_QUERY, new InputSource(new StringReader(mandate))));
+
+ // check if all necessary fields are present
+ Logger.debug("Starting mandate structure validation");
+ try {
+ validateMandateStructure(localMethods); // TODO
+ } catch (Exception e) {
+ if (e instanceof MOAIDException) {
+ Logger.error("Could not validate mandate structure.");
+ throw new MOAIDException("stork.16", new Object[] {e.getMessage()}); // TODO
+ } else {
+ Logger.error("Error during mandate structure validation.");
+ throw new MOAIDException("stork.16", new Object[] {e.getMessage()}); // TODO
+ }
+
+ }
+ }
+
+
+
+ public String getPhyPersMandatorGivenName() {
+ return phyPersMandatorGivenName;
+ }
+
+ public void setPhyPersMandatorGivenName(String phyPersMandatorGivenName) {
+ this.phyPersMandatorGivenName = phyPersMandatorGivenName;
+ }
+
+ public String getPhyPersMandatorFamilyName() {
+ return phyPersMandatorFamilyName;
+ }
+
+ public void setPhyPersMandatorFamilyName(String phyPersMandatorFamilyName) {
+ this.phyPersMandatorFamilyName = phyPersMandatorFamilyName;
+ }
+
+ public String getPhyPersMandatorBirthDate() {
+ return phyPersMandatorBirthDate;
+ }
+
+ public void setPhyPersMandatorBirthDate(String phyPersMandatorBirthDate) {
+ // making it conform to STORK dateOfBirth specifications, removing dash
+ this.phyPersMandatorBirthDate = phyPersMandatorBirthDate.replaceAll("-","");
+ }
+
+ public String getPhyPersMandatorIdentificationValue() {
+ return phyPersMandatorIdentificationValue;
+ }
+
+ public void setPhyPersMandatorIdentificationValue(String phyPersMandatorIdentificationValue) {
+ this.phyPersMandatorIdentificationValue = phyPersMandatorIdentificationValue;
+ }
+
+ public String getPhyPersMandatorIdentificationType() {
+ return phyPersMandatorIdentificationType;
+ }
+
+ public void setPhyPersMandatorIdentificationType(String phyPersMandatorIdentificationType) {
+ this.phyPersMandatorIdentificationType = phyPersMandatorIdentificationType;
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java
new file mode 100644
index 000000000..a560bdaff
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java
@@ -0,0 +1,66 @@
+/*******************************************************************************
+ * 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.stork2;
+
+/**
+ * @author bsuzic
+ * Date: 4/29/14, Time: 5:34 PM
+ */
+public interface S2Constants {
+ public static final String MANDATE_PREFIX = "mandate";
+ public static final String PERSONDATA_PREFIX = "persondata";
+ public static final String XMLDSIG_PREFIX = "xmldsig";
+
+ public static final String MANDATE_NS = "http://reference.e-government.gv.at/namespace/mandates/20040701#";
+ public static final String PERSONDATA_NS = "http://reference.e-government.gv.at/namespace/persondata/20020228#";
+ public static final String XMLDSIG_NS = "http://www.w3.org/2000/09/xmldsig#";
+
+ public static final String MANDATE_ANNOTATION_QUERY = "/mandate:Mandate/mandate:Annotation/text()";
+ public static final String MANDATE_REPRESENTATIVE_PHYPERS_IDVALUE_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:Identification/persondata:Value/text()";
+ public static final String MANDATE_REPRESENTATIVE_PHYPERS_IDTYPE_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:Identification/persondata:Type/text()";
+ public static final String MANDATE_REPRESENTATIVE_PHYPERS_GIVENNAME_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:Name/persondata:GivenName/text()";
+ public static final String MANDATE_REPRESENTATIVE_PHYPERS_FAMILYNAME_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:Name/persondata:FamilyName/text()";
+ public static final String MANDATE_REPRESENTATIVE_PHYPERS_DATEOFBIRTH_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:DateOfBirth/text()";
+ public static final String MANDATE_MANDATOR_CORPBODY_IDVALUE_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:CorporateBody/persondata:Identification/persondata:Value/text()";
+ public static final String MANDATE_MANDATOR_CORPBODY_IDTYPE_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:CorporateBody/persondata:Identification/persondata:Type/text()";
+ public static final String MANDATE_MANDATOR_CORPBODY_FULLNAME_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:CorporateBody/persondata:FullName/text()";
+ public static final String MANDATE_ISSUEDPLACE_QUERY = "/mandate:Mandate/mandate:Issued/mandate:Place/text()";
+ public static final String MANDATE_ISSUEDDATE_QUERY = "/mandate:Mandate/mandate:Issued/mandate:Date/text()";
+ public static final String MANDATE_ISSUEDTIME_QUERY = "/mandate:Mandate/mandate:Issued/mandate:Time/text()";
+ public static final String MANDATE_SIMPLEMANDATECONTENT_TXTDESC_QUERY = "/mandate:Mandate/mandate:SimpleMandateContent/mandate:TextualDescription/text()";
+ public static final String MANDATE_SIMPLEMANDATECONTENT_VALIDFROM_QUERY = "/mandate:Mandate/mandate:SimpleMandateContent/mandate:TimeConstraint/mandate:ValidFrom/text()";
+ public static final String MANDATE_SIMPLEMANDATECONTENT_VALIDTO_QUERY = "/mandate:Mandate/mandate:SimpleMandateContent/mandate:TimeConstraint/mandate:ValidTo/text()";
+
+ public static final String MANDATE_MANDATOR_PHYPERS_IDVALUE_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:Identification/persondata:Value/text()";
+ public static final String MANDATE_MANDATOR_PHYPERS_IDTYPE_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:Identification/persondata:Type/text()";
+ public static final String MANDATE_MANDATOR_PHYPERS_GIVENNAME_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:Name/persondata:GivenName/text()";
+ public static final String MANDATE_MANDATOR_PHYPERS_FAMILYNAME_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:Name/persondata:FamilyName/text()";
+ public static final String MANDATE_MANDATOR_PHYPERS_DATEOFBIRTH_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:DateOfBirth/text()";
+
+ public static final String IDENTIFICATION_TYPE_COMPANY = "urn:publicid:gv.at:baseid+XFN";
+ public static final String IDENTIFICATION_TYPE_ASSOCIATION = "urn:publicid:gv.at:baseid+XZVR";
+ public static final String IDENTIFICATION_TYPE_OTHERS = "urn:publicid:gv.at:baseid+XERSB";
+
+
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java
new file mode 100644
index 000000000..123d32af4
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java
@@ -0,0 +1,49 @@
+/*
+ * 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.stork2;
+
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * @author tlenz
+ *
+ */
+public class STORKPVPUtilits {
+
+ public static final List<String> attributesRequirePVPAuthentication =
+ Arrays.asList("ECApplicationRole", "MSOrganization");
+
+
+
+ public static boolean performAuthenticationOnNationalIDP(MOASTORKRequest moastorkRequest) {
+ for (String el : attributesRequirePVPAuthentication) {
+ if (moastorkRequest.getPersonalAttributeList().containsKey(el)) {
+ return true;
+
+ }
+ }
+ return false;
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java
new file mode 100644
index 000000000..c4f9658e4
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java
@@ -0,0 +1,233 @@
+/*******************************************************************************
+ * 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.stork2;
+
+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.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.moduls.IAction;
+import at.gv.egovernment.moa.id.moduls.IModulInfo;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.MiscUtil;
+import eu.stork.peps.auth.commons.*;
+import eu.stork.peps.auth.engine.STORKSAMLEngine;
+import eu.stork.peps.exceptions.STORKSAMLEngineException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.HashMap;
+
+/**
+ * Stork 2 Protocol Support
+ *
+ * @author bsuzic
+ */
+public class STORKProtocol extends MOAIDAuthConstants implements IModulInfo {
+
+ public static final String NAME = STORKProtocol.class.getName();
+ public static final String PATH = "id_stork2";
+
+ public static final String AUTHENTICATIONREQUEST = "AuthenticationRequest";
+ public static final String ATTRIBUTE_COLLECTOR = "AttributeCollector";
+ public static final String MANDATERETRIEVALREQUEST = "MandateRetrievalRequest";
+ public static final String CONSENT_EVALUATOR = "ConsentEvaluator";
+
+ private static HashMap<String, IAction> actions = new HashMap<String, IAction>();
+
+ static {
+ actions.put(AUTHENTICATIONREQUEST, new AuthenticationRequest());
+ actions.put(ATTRIBUTE_COLLECTOR, new AttributeCollector());
+ actions.put(CONSENT_EVALUATOR, new ConsentEvaluator());
+ actions.put(MANDATERETRIEVALREQUEST, new MandateRetrievalRequest());
+ }
+
+ public String getName() {
+ return NAME;
+ }
+
+ public String getPath() {
+ return PATH;
+ }
+
+ public IAction getAction(String action) {
+ return actions.get(action);
+ }
+
+ public STORKProtocol() {
+ super();
+ }
+
+ /*
+ First request step - send it to BKU selection for user authentication. After the user credentials
+ and other info are obtained, in the second step the request will be processed and the user redirected
+ */
+ public IRequest preProcess(HttpServletRequest request, HttpServletResponse response, String action,
+ String sessionId, String transactionId) throws MOAIDException {
+ Logger.info("Starting preprocessing for Stork2 protocol");
+ Logger.debug("Request method: " + request.getMethod());
+ Logger.debug("Request content length: " + request.getContentLength());
+ Logger.debug("Initiating action: " + action);
+
+ MOASTORKRequest STORK2Request = new MOASTORKRequest(request);
+ MOASTORKResponse STORK2Response = new MOASTORKResponse(request);
+
+
+ if (AttributeCollector.class.getSimpleName().equals(action) || ConsentEvaluator.class.getSimpleName().equals(action))
+ return STORK2Request;
+
+
+ if (request.getParameter("SAMLResponse") != null) { // TODO check attribute collector
+ //extract STORK Response from HTTP Request
+ byte[] decSamlToken;
+ try {
+ decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
+ } catch (NullPointerException e) {
+ if (request.getRemoteHost().contains("129.27.142")) {
+ Logger.warn("Availability check by " + request.getRemoteHost() + " on URI: " + request.getRequestURI());
+ } else {
+ Logger.error("Unable to retrieve STORK Request for host: " + request.getRemoteHost() + " and URI: " + request.getRequestURI(), e);
+ }
+ throw new MOAIDException("stork.04", null);
+ }
+
+ //Get SAMLEngine instance
+ STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
+
+ STORKAuthnResponse authnResponse = null;
+
+
+ // check if valid authn request is contained
+ try {
+ authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, request.getRemoteAddr());
+ } catch (STORKSAMLEngineException ex) {
+ Logger.error("Unable to validate Stork AuthenticationResponse: " + ex.getMessage());
+ }
+
+ STORK2Response.setSTORKAuthnResponseToken(decSamlToken);
+
+ return STORK2Response;
+
+ } else if (request.getParameter("SAMLRequest") != null) {
+
+ //extract STORK Response from HTTP Request
+ byte[] decSamlToken;
+ try {
+ decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLRequest"));
+ } catch (NullPointerException e) {
+ if (request.getRemoteHost().contains("129.27.142")) {
+ Logger.warn("Availability check by " + request.getRemoteHost() + " on URI: " + request.getRequestURI());
+ } else {
+ Logger.error("Unable to retrieve STORK Request for host: " + request.getRemoteHost() + " and URI: " + request.getRequestURI(), e);
+ }
+ throw new MOAIDException("stork.04", null);
+ }
+
+ //Get SAMLEngine instance
+ STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
+
+ STORKAuthnRequest authnRequest = null;
+ STORKAttrQueryRequest attrRequest = null;
+
+ // check if valid authn request is contained
+ try {
+ authnRequest = engine.validateSTORKAuthnRequest(decSamlToken);
+
+ } catch (STORKSAMLEngineException ex) {
+ Logger.error("Unable to validate Stork AuthenticationRequest: " + ex.getMessage());
+
+ } catch (ClassCastException e) {
+ // we do not have a authnRequest
+ // check if a valid attr request is container
+ try {
+ attrRequest = engine.validateSTORKAttrQueryRequest(decSamlToken);
+
+ } catch (STORKSAMLEngineException ex) {
+ Logger.error("Unable to validate Stork AuthenticationRequest: " + ex.getMessage());
+
+ }
+ }
+
+ // if there is no authn or attr request, raise error
+ if ((authnRequest == null) && (attrRequest == null)) {
+ Logger.error("There is no authentication or attribute request contained.");
+ throw new MOAIDException("stork.14", null);
+ }
+ // list attributes in the request
+ try {
+ for (PersonalAttribute personalAttribute : authnRequest.getPersonalAttributeList()) {
+ Logger.debug("Personal attribute found in request: " + personalAttribute.getName() + " isRequired: " + personalAttribute.isRequired());
+ }
+ } catch (Exception e) {
+ Logger.error("Exception, attributes: " + e.getMessage());
+ }
+
+ STORK2Request.setSTORKAuthnRequest(authnRequest);
+ STORK2Request.setSTORKAttrRequest(attrRequest);
+
+ //check if OA is instance of VIDP or STORKPVPGateway
+ OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(STORK2Request.getOAURL());
+ if (oaParam == null)
+ throw new AuthenticationException("stork.12", new Object[]{STORK2Request.getOAURL()});
+
+ else {
+ STORK2Request.setOnlineApplicationConfiguration(oaParam);
+ if (oaParam.isSTORKPVPGateway()) {
+ if (MiscUtil.isNotEmpty(oaParam.getSTORKPVPForwardEntity())) {
+ Logger.info("Received request for STORK->PVP gateway. " +
+ "Forward to PVP portal with entiyID " + oaParam.getSTORKPVPForwardEntity() +
+ " ..." );
+ STORK2Request.setRequestedIDP(oaParam.getSTORKPVPForwardEntity());
+
+ } else {
+ Logger.error("InterfederatedGateway configuration with ID " + STORK2Request.getOAURL() +
+ " not configure a forward entityID.");
+ throw new MOAIDException("", null);
+
+ }
+ }
+
+ }
+
+ return STORK2Request;
+ } else {
+ throw new MOAIDException("stork.14", null); // TODO Specify message
+ }
+ }
+
+ public IAction canHandleRequest(HttpServletRequest request, HttpServletResponse response) {
+ return null;
+ }
+
+ public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) throws Throwable {
+ return false;
+ }
+
+ public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) {
+ return false;
+ }
+}
+
+
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java
new file mode 100644
index 000000000..2c2df3e54
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java
@@ -0,0 +1,83 @@
+/*
+ * 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.stork2;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import javax.xml.namespace.NamespaceContext;
+
+/**
+ * @author tlenz
+ *
+ */
+public class SimpleNamespaceContext implements NamespaceContext {
+
+ HashMap<String, String> prefMap = null;
+ /**
+ * @param prefMap
+ */
+ SimpleNamespaceContext(HashMap<String, String> prefMap) {
+ this.prefMap = prefMap;
+ }
+
+ /* (non-Javadoc)
+ * @see javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String)
+ */
+ @Override
+ public String getNamespaceURI(String prefix) {
+ if (prefMap.containsKey(prefix))
+ return prefMap.get(prefix);
+ else
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see javax.xml.namespace.NamespaceContext#getPrefix(java.lang.String)
+ */
+ @Override
+ public String getPrefix(String namespaceURI) {
+ if (prefMap.containsValue(namespaceURI)) {
+ Set<Entry<String, String>> set = prefMap.entrySet();
+ for (Entry<String, String> el : set) {
+ if (el.getValue().equals(namespaceURI))
+ return el.getKey();
+
+ }
+ }
+
+ return null;
+ }
+
+ /* (non-Javadoc)
+ * @see javax.xml.namespace.NamespaceContext#getPrefixes(java.lang.String)
+ */
+ @Override
+ public Iterator getPrefixes(String namespaceURI) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/UnsupportedAttributeException.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/UnsupportedAttributeException.java
new file mode 100644
index 000000000..31b9c9c0a
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/UnsupportedAttributeException.java
@@ -0,0 +1,29 @@
+/*******************************************************************************
+ * 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.stork2;
+
+public class UnsupportedAttributeException extends Exception {
+
+ private static final long serialVersionUID = -7720066381435378111L;
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java
new file mode 100644
index 000000000..aaf13a779
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java
@@ -0,0 +1,139 @@
+/*******************************************************************************
+ * 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.stork2.attributeproviders;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException;
+import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest;
+import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException;
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
+import eu.stork.peps.auth.commons.PersonalAttribute;
+
+/**
+ * An {@link AttributeProvider} can fetch a set of stork attributes. It might complete the query within one method call,
+ * but might also need to redirect to another webservice to accomplish its task.
+ */
+public abstract class AttributeProvider implements Comparable<AttributeProvider>{
+
+ protected String attributes;
+
+ public AttributeProvider(String attributes){
+ this.attributes = attributes;
+ }
+
+ /**
+ * Acquire the specified attribute. Returns {@code null} when attribute retrieval is in progress, but requires for
+ * for redirecting the user to an external service. Use {@link AttributeProvider#parse(HttpServletRequest)} to parse
+ * the response.
+ *
+ * @param currentProviderConfiguredAttributes the list of attributes to be acquired
+ * @param moastorkRequest the sp county code
+ * @param authData the moasession
+ * @return the personal attribute
+ * @throws UnsupportedAttributeException the unsupported attribute exception
+ * @throws ExternalAttributeRequestRequiredException an attribute request to an external service has to be done
+ * @throws MOAIDException the mOAID exception
+ */
+ protected abstract IPersonalAttributeList acquire(PersonalAttribute currentProviderConfiguredAttributes, MOASTORKRequest moastorkRequest, IAuthData authData) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException;
+
+ public IPersonalAttributeList acquire(List<PersonalAttribute> attributes, MOASTORKRequest moastorkRequest, IAuthData authData) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException {
+ if (attributes.size() == 1) {
+ return acquire(attributes.get(0), moastorkRequest, authData);
+ } else {
+ throw new MOAIDException("stork.13", new Object[] { }); // TODO message only one attribute supported by this provider
+
+ }
+ }
+
+ /**
+ * Perform redirect.
+ *
+ * @param url the return URL ending with ?artifactId=...
+ * @param req the request we got from the S-PEPS and for which we have to ask our APs
+ * @param resp the response to the preceding request
+ * @param oaParam the oa param
+ * @throws MOAIDException the mOAID exception
+ */
+ public abstract void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException;
+
+ /**
+ * Parses the response we got from the external attribute provider.
+ *
+ * @param httpReq the http req
+ * @return a list of attributes
+ * @throws UnsupportedAttributeException if the provider cannot find anything familiar in the provided httpReq
+ * @throws MOAIDException if something went wrong
+ */
+ public abstract IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException;
+
+ /**
+ * Returns the list of supported attributes
+ *
+ * @return a list of attributes
+ * @throws MOAIDException if something went wrong
+ */
+ public List<String> getSupportedAttributeNames() throws MOAIDException {
+ ArrayList<String> supportedAttributeNames = new ArrayList<String>();
+ for (String attributeName : this.attributes.split(",")) {
+ supportedAttributeNames.add(attributeName);
+ }
+ return supportedAttributeNames;
+ }
+
+
+ /**
+ * Returns the sequence priority of this attribute provider.
+ * Providers with small numbers are requested first.
+ *
+ * @return a sequence priority of this provider
+ */
+ public abstract int getPriority();
+
+ /**
+ * Compare the sequence priority of two attribute providers
+ * @param o attribute provider
+ * @return 0 if priority is equal
+ * @return -1 if priority if this is higher then from o
+ * @return +1 if priority if o is higher then from this
+ */
+ @Override
+ public int compareTo(AttributeProvider o) {
+ if (this.getPriority() == o.getPriority())
+ return 0;
+
+ if (this.getPriority() < o.getPriority())
+ return -1;
+
+ else
+ return +1;
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java
new file mode 100644
index 000000000..bd1576020
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java
@@ -0,0 +1,254 @@
+/*******************************************************************************
+ * 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.stork2.attributeproviders;
+
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+import javax.xml.soap.MessageFactory;
+import javax.xml.soap.SOAPBody;
+import javax.xml.soap.SOAPConnection;
+import javax.xml.soap.SOAPConnectionFactory;
+import javax.xml.soap.SOAPElement;
+import javax.xml.soap.SOAPEnvelope;
+import javax.xml.soap.SOAPMessage;
+import javax.xml.soap.SOAPPart;
+
+import at.gv.egovernment.moa.id.auth.builder.BPKBuilder;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException;
+import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest;
+import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException;
+import at.gv.egovernment.moa.logging.Logger;
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
+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 eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.IsHealthCareProfessionalType;
+import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.ObjectFactory;
+
+/**
+ * Fetches the attribute IsHealthcareProfessional from the BAGDAD SOAP service
+ */
+public class EHvdAttributeProviderPlugin extends AttributeProvider {
+
+ /** The destination. */
+ private Object destination;
+
+ /**
+ * Instantiates a new e hvd attribute provider plugin.
+ *
+ * @param url the service url
+ * @param supportedAttributes
+ */
+ public EHvdAttributeProviderPlugin(String url, String supportedAttributes) {
+ super(supportedAttributes);
+ destination = url;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#acquire(eu.stork.peps.auth.commons.PersonalAttribute)
+ */
+ @Override
+ protected IPersonalAttributeList acquire(PersonalAttribute attribute, MOASTORKRequest moastorkRequest, IAuthData authData)
+ throws UnsupportedAttributeException,
+ ExternalAttributeRequestRequiredException, MOAIDException {
+
+ // break when we cannot handle the requested attribute
+ if(!attributes.contains(attribute.getName()))
+ throw new UnsupportedAttributeException();
+
+ try {
+ Logger.debug("initializing SOAP connections...");
+ // create SOAP connection
+ SOAPConnection soapConnection = SOAPConnectionFactory.newInstance().createConnection();
+
+ // assemble SOAP request
+ MessageFactory messageFactory = MessageFactory.newInstance();
+ SOAPMessage requestMessage = messageFactory.createMessage();
+ SOAPPart requestPart = requestMessage.getSOAPPart();
+
+ // (soap 1.1 relevant part. could not find a solution to use soap 1.2 in time.
+ requestMessage.getMimeHeaders().setHeader("SOAPAction", "http://gesundheit.gv.at/BAGDAD/DataAccessService/IsHealthcareProfessional");
+
+ /*
+ Construct SOAP Request Message:
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <IsHealthcareProfessional xmlns="http://gesundheit.gv.at/BAGDAD/DataAccessService">
+ <bPK>string</bPK>
+ </IsHealthcareProfessional>
+ </soap:Body>
+ </soap:Envelope>
+
+ see https://stork.ehealth.gv.at/GDAService.asmx?op=IsHealthcareProfessional
+ */
+
+ // SOAP Envelope
+ SOAPEnvelope envelope = requestPart.getEnvelope();
+
+ // SOAP Body
+ SOAPBody requestBody = envelope.getBody();
+ SOAPElement requestBodyElem = requestBody.addChildElement("IsHealthcareProfessional");
+ requestBodyElem.addAttribute(envelope.createName("xmlns"), "http://gesundheit.gv.at/BAGDAD/DataAccessService");
+
+ SOAPElement requestBodyElem1 = requestBodyElem.addChildElement("bPK");
+
+ //TODO: CHECK: IdentificationValue containts wbPK if MOA-ID is used as VIDP
+ requestBodyElem1.addTextNode(new BPKBuilder().buildBPK(authData.getIdentificationValue(), "GH"));
+
+ requestMessage.saveChanges();
+
+ // perform SOAP call
+ Logger.debug("call...");
+ SOAPMessage responseMessage = soapConnection.call(requestMessage, destination);
+
+ // parse SOAP response
+
+ /*
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <IsHealthcareProfessionalResponse xmlns="http://gesundheit.gv.at/BAGDAD/DataAccessService">
+ <IsHealthcareProfessionalResult>
+ <RequestOK>boolean</RequestOK>
+ <Message>string</Message>
+ <IsHealthcareProfessional>boolean</IsHealthcareProfessional>
+ <NameOfOrganisation>string</NameOfOrganisation>
+ <Type>string</Type>
+ <Specialization>string</Specialization>
+ </IsHealthcareProfessionalResult>
+ </IsHealthcareProfessionalResponse>
+ </soap:Body>
+ </soap:Envelope>
+
+ see https://stork.ehealth.gv.at/GDAService.asmx?op=IsHealthcareProfessional
+ */
+ Logger.debug("call successful. Parse...");
+ SOAPBody responseBody = responseMessage.getSOAPBody();
+
+ // iterate through tree
+ SOAPElement responseElement = (SOAPElement) responseBody.getChildElements().next();
+ SOAPElement resultElement = (SOAPElement) responseElement.getChildElements().next();
+
+ // collect all info in a map
+ Iterator<?> it = resultElement.getChildElements();
+ Map<String, String> collection = new HashMap<String, String>();
+ while (it.hasNext()) {
+ SOAPElement current = (SOAPElement) it.next();
+
+ collection.put(current.getNodeName(), current.getTextContent());
+ }
+
+ // check if there is anything valid in the map
+ if (collection.isEmpty() || collection.size() != 6) {
+ Logger.warn("eHVD returned an unexpected count of values. Expected 6 got " + collection.size());
+ throw new IndexOutOfBoundsException("response attributes not like specified");
+ }
+
+ // - fetch request validity
+ if (collection.get("RequestOK").equals("false")) {
+ Logger.warn("eHVD reported an invalid request. The error message is: " + collection.get("Message"));
+ throw new Exception("eHVD reported an invalid request");
+ }
+
+ PersonalAttribute acquiredAttribute = null;
+
+ if (collection.get("IsHealthcareProfessional").equals("false") || !collection.get("Type").equals("Medical doctor")) {
+ // the citizen is no HCP
+ acquiredAttribute = new PersonalAttribute("isHealthCareProfessional", false, new ArrayList<String>(), AttributeStatusType.NOT_AVAILABLE.value());
+ } else {
+ // go on and parse the data
+ IsHealthCareProfessionalType result = new IsHealthCareProfessionalType();
+
+ // TODO: we do not have any list of possible values yet. Fix as soon as we get some.
+// if (collection.get("Type").equals("Medical doctor"))
+ result.setTypeOfHCP("physician");
+
+ result.setNameOfOrganisation(collection.get("NameOfOrganisation"));
+ //result.setTypeOfOrganisation("Unknown"); // TODO used in previous version, check what to do with this
+
+ result.setAQAA(4);
+
+ final Marshaller m = JAXBContext.newInstance(IsHealthCareProfessionalType.class).createMarshaller();
+ m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
+
+ StringWriter stringWriter = new StringWriter();
+ m.marshal(new ObjectFactory().createIsHealthCareProfessional(result), stringWriter);
+
+ ArrayList<String> value = new ArrayList<String>();
+ value.add(stringWriter.toString());
+
+ acquiredAttribute = new PersonalAttribute("isHealthCareProfessional", false, value, AttributeStatusType.AVAILABLE.value());
+ }
+
+ // pack and return the result
+ PersonalAttributeList result = new PersonalAttributeList();
+ result.add(acquiredAttribute);
+
+ // add stork id for verification
+ ArrayList<String> value = new ArrayList<String>();
+ value.add(new BPKBuilder().buildStorkeIdentifier(authData.getIdentityLink(), moastorkRequest.getSpCountry()));
+ result.add(new PersonalAttribute("eIdentifier", false, value, AttributeStatusType.AVAILABLE.value()));
+
+ return result;
+ } catch (Exception e) {
+ throw new MOAIDException("stork.13", new Object[] { e });
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#performRedirect(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.config.auth.OAAuthParameter)
+ */
+ public void performRedirect(String url,
+ HttpServletRequest req, HttpServletResponse resp,
+ OAAuthParameter oaParam) throws MOAIDException {
+ // there is no redirect required
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#parse(javax.servlet.http.HttpServletRequest)
+ */
+ public IPersonalAttributeList parse(HttpServletRequest httpReq)
+ throws UnsupportedAttributeException, MOAIDException {
+ // there is no redirect required, so we throw an exception when someone asks us to parse a response
+ throw new UnsupportedAttributeException();
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority()
+ */
+ @Override
+ public int getPriority() {
+ return 99;
+ }
+
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java
new file mode 100644
index 000000000..f671f0807
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java
@@ -0,0 +1,231 @@
+/*******************************************************************************
+ * 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.stork2.attributeproviders;
+
+import java.io.StringWriter;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException;
+import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest;
+import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException;
+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.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.engine.STORKSAMLEngine;
+import eu.stork.peps.exceptions.STORKSAMLEngineException;
+
+/**
+ * Provides mandate attribute from MIS
+ */
+public class MandateAttributeRequestProvider extends AttributeProvider {
+ /**
+ * The destination.
+ */
+ private String destination;
+
+ private String spCountryCode;
+
+ private PersonalAttributeList requestedAttributes;
+
+ public MandateAttributeRequestProvider(String aPurl, String supportedAttributes) throws MOAIDException {
+ super(supportedAttributes);
+ destination = aPurl;
+
+ }
+
+ public String getAttrProviderName() {
+ 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());
+ this.spCountryCode = moastorkRequest.getSpCountry();
+ requestedAttributes = new PersonalAttributeList(1);
+ requestedAttributes.add(attribute);
+
+ // break if we cannot handle the requested attribute
+ if (!attributes.contains(attribute.getName())) {
+ Logger.info("Attribute " + attribute.getName() + " not supported by the provider: " + getAttrProviderName());
+ throw new UnsupportedAttributeException();
+ }
+
+ // 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);
+ }
+
+ @Override
+ public IPersonalAttributeList acquire(List<PersonalAttribute> attributes, MOASTORKRequest moastorkRequest, IAuthData moasession) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException {
+ Logger.info("Acquiring " + attributes.size() + " attributes, by: " + getAttrProviderName());
+ this.spCountryCode = moastorkRequest.getSpCountry();
+ requestedAttributes = new PersonalAttributeList(attributes.size());
+
+ for (PersonalAttribute personalAttribute : attributes) {
+ // break if we cannot handle the requested attribute
+ if (!this.attributes.contains(personalAttribute.getName())) {
+ Logger.info("Attribute " + personalAttribute.getName() + " not supported by the provider: " + getAttrProviderName());
+ throw new UnsupportedAttributeException();
+ }
+ requestedAttributes.add(personalAttribute);
+ }
+
+ // 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());
+ throw new UnsupportedAttributeException();
+ }
+
+
+
+ Logger.info("Thrown external request by: " + getAttrProviderName());
+ throw new ExternalAttributeRequestRequiredException(this);
+ }
+
+
+
+
+ public void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException {
+
+ String spSector = "Business";
+ String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName();
+ String spApplication = spInstitution;
+
+ if ((spCountryCode == null) || (spCountryCode.length()<2)) {
+ spCountryCode = oaParam.getTarget();
+ Logger.info("Setting spcountry target: " + oaParam.getTarget());
+ Logger.info("idlink ident " + oaParam.getIdentityLinkDomainIdentifier());
+ Logger.info("idlink type " + oaParam.getIdentityLinkDomainIdentifierType());
+ Logger.info("Setting spcountry target friendly : " + oaParam.getTargetFriendlyName());
+ Logger.info("Oatype : " + oaParam.getOaType());
+ Logger.info("puburl : " + oaParam.getPublicURLPrefix());
+ if ("STORK".equals(oaParam.getIdentityLinkDomainIdentifierType())) {
+
+ spCountryCode = oaParam.getIdentityLinkDomainIdentifier().substring(oaParam.getIdentityLinkDomainIdentifier().length()-2);
+ Logger.info("Set to " +spCountryCode);
+ }
+
+ }
+
+ // 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();
+ attributeRequest.setDestination(destination);
+ attributeRequest.setAssertionConsumerServiceURL(url);
+ attributeRequest.setIssuer(HTTPUtils.getBaseURL(req));
+ attributeRequest.setQaa(oaParam.getQaaLevel());
+ attributeRequest.setSpInstitution(spInstitution);
+ attributeRequest.setCountry(spCountryCode);
+ attributeRequest.setSpCountry(spCountryCode);
+ attributeRequest.setSpApplication(spApplication);
+ attributeRequest.setSpSector(spSector);
+ attributeRequest.setPersonalAttributeList(requestedAttributes);
+
+ attributeRequest.setCitizenCountryCode("AT");
+ attributeRequest.setQaa(oaParam.getQaaLevel());
+
+ if (attributeRequest.getQaa() == 0 ) {
+ attributeRequest.setQaa(4); // workaround
+ }
+
+
+
+ Logger.info("STORK AttrRequest successfully assembled.");
+
+ STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("VIDP");
+ try {
+
+ attributeRequest = samlEngine.generateSTORKAttrQueryRequest(attributeRequest);
+ } catch (STORKSAMLEngineException e) {
+ Logger.error("Could not sign STORK SAML AttrRequest.", e);
+ throw new MOAIDException("stork.00", null);
+ }
+
+ Logger.info("STORK AttrRequest successfully signed!");
+
+ try {
+ Logger.trace("Initialize VelocityEngine...");
+
+ VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
+ Template template = velocityEngine.getTemplate("/resources/templates/saml2-post-binding-moa.vm");
+ VelocityContext context = new VelocityContext();
+ context.put("SAMLRequest", PEPSUtil.encodeSAMLToken(attributeRequest.getTokenSaml()));
+ context.put("action", destination);
+
+ StringWriter writer = new StringWriter();
+ template.merge(context, writer);
+
+ resp.getOutputStream().write(writer.toString().getBytes("UTF-8"));
+ } catch (Exception e) {
+ Logger.error("Error sending STORK SAML AttrRequest.", e);
+ throw new MOAIDException("stork.11", null);
+ }
+ Logger.info("STORK AttrRequest successfully rendered!");
+
+ }
+
+ public IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException {
+ return null; //
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority()
+ */
+ @Override
+ public int getPriority() {
+ return 99;
+ }
+}
+
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java
new file mode 100644
index 000000000..7f06c604b
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java
@@ -0,0 +1,238 @@
+/*
+ * 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.stork2.attributeproviders;
+
+import java.io.StringWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException;
+import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest;
+import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException;
+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.peps.auth.commons.IPersonalAttributeList;
+import eu.stork.peps.auth.commons.PEPSUtil;
+import eu.stork.peps.auth.commons.PersonalAttribute;
+import eu.stork.peps.auth.commons.STORKAttrQueryRequest;
+import eu.stork.peps.auth.commons.STORKAttrQueryResponse;
+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;
+
+/**
+ * @author tlenz
+ *
+ */
+public class PVPAuthenticationProvider extends AttributeProvider {
+
+ private String destination = null;
+ private MOASTORKRequest moastorkRequest = null;
+
+ /**
+ * @param attributes
+ * @param attributes2
+ */
+ public PVPAuthenticationProvider(String url, String attributes) {
+ super(attributes);
+ this.destination = url;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#acquire(eu.stork.peps.auth.commons.PersonalAttribute, java.lang.String, at.gv.egovernment.moa.id.data.IAuthData)
+ */
+ @Override
+ protected IPersonalAttributeList acquire(PersonalAttribute attribute,
+ MOASTORKRequest moastorkRequest, IAuthData authData)
+ throws UnsupportedAttributeException,
+ ExternalAttributeRequestRequiredException, MOAIDException {
+
+ this.moastorkRequest = moastorkRequest;
+ // break if we cannot handle the requested attribute
+ if (!getSupportedAttributeNames().contains(attribute.getName())) {
+ Logger.info("Attribute " + attribute.getName() + " not supported by the provider: " + getAttrProviderName());
+ throw new UnsupportedAttributeException();
+
+ }
+
+ Logger.info("Thrown external request by: " + getAttrProviderName());
+ throw new ExternalAttributeRequestRequiredException(this);
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#performRedirect(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.config.auth.OAAuthParameter)
+ */
+ @Override
+ public void performRedirect(String url, HttpServletRequest req,
+ HttpServletResponse resp, OAAuthParameter oaParam)
+ throws MOAIDException {
+
+ String spSector = "Business";
+ String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName();
+ String spApplication = spInstitution;
+ String spCountryCode = moastorkRequest.getSpCountry();
+
+ if ((spCountryCode == null) || (spCountryCode.length()<2)) {
+ spCountryCode = oaParam.getTarget();
+ Logger.info("Setting spcountry target: " + oaParam.getTarget());
+ Logger.info("idlink ident " + oaParam.getIdentityLinkDomainIdentifier());
+ Logger.info("idlink type " + oaParam.getIdentityLinkDomainIdentifierType());
+ Logger.info("Setting spcountry target friendly : " + oaParam.getTargetFriendlyName());
+ Logger.info("Oatype : " + oaParam.getOaType());
+ Logger.info("puburl : " + oaParam.getPublicURLPrefix());
+ if ("STORK".equals(oaParam.getIdentityLinkDomainIdentifierType())) {
+
+ spCountryCode = oaParam.getIdentityLinkDomainIdentifier().substring(oaParam.getIdentityLinkDomainIdentifier().length()-2);
+ Logger.info("Set to " +spCountryCode);
+ }
+
+ }
+
+ //generate AttrQueryRequest
+ STORKAuthnRequest authRequest = new STORKAuthnRequest();
+ authRequest.setDestination(destination);
+ authRequest.setAssertionConsumerServiceURL(url);
+ authRequest.setIssuer(HTTPUtils.getBaseURL(req));
+ authRequest.setQaa(oaParam.getQaaLevel());
+ authRequest.setSpInstitution(spInstitution);
+ authRequest.setCountry(spCountryCode);
+ authRequest.setSpCountry(spCountryCode);
+ authRequest.setSpApplication(spApplication);
+ authRequest.setProviderName(spApplication);
+ authRequest.setSpSector(spSector);
+ authRequest.setPersonalAttributeList(moastorkRequest.getPersonalAttributeList());
+
+ authRequest.setCitizenCountryCode("AT");
+ //authRequest.setQaa(oaParam.getQaaLevel());
+ authRequest.setQaa(moastorkRequest.getStorkAuthnRequest().getQaa());
+
+
+
+
+ Logger.info("STORK AttrRequest successfully assembled.");
+
+ STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("VIDP");
+ try {
+
+ authRequest = samlEngine.generateSTORKAuthnRequest(authRequest);
+ } catch (STORKSAMLEngineException e) {
+ Logger.error("Could not sign STORK SAML AttrRequest.", e);
+ throw new MOAIDException("stork.00", null);
+ }
+
+ Logger.info("STORK AttrRequest successfully signed!");
+
+ //validate AuthnRequest
+ try {
+ samlEngine.validateSTORKAuthnRequest(authRequest.getTokenSaml());
+ } catch (STORKSAMLEngineException e) {
+ Logger.error("STORK SAML AuthnRequest not valid.", e);
+ throw new MOAIDException("stork.01", null);
+ }
+
+ Logger.debug("STORK AuthnRequest successfully internally validated.");
+
+ try {
+ Logger.trace("Initialize VelocityEngine...");
+
+ VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
+ Template template = velocityEngine.getTemplate("/resources/templates/saml2-post-binding-moa.vm");
+ VelocityContext context = new VelocityContext();
+ context.put("SAMLRequest", PEPSUtil.encodeSAMLToken(authRequest.getTokenSaml()));
+ context.put("action", destination);
+
+ StringWriter writer = new StringWriter();
+ template.merge(context, writer);
+
+ resp.getOutputStream().write(writer.toString().getBytes("UTF-8"));
+
+ } catch (Exception e) {
+ Logger.error("Error sending STORK SAML AttrRequest.", e);
+ throw new MOAIDException("stork.11", null);
+
+ }
+ Logger.info("STORK AttrRequest successfully rendered!");
+
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#parse(javax.servlet.http.HttpServletRequest)
+ */
+ @Override
+ public IPersonalAttributeList parse(HttpServletRequest httpReq)
+ throws UnsupportedAttributeException, MOAIDException {
+
+ throw new UnsupportedAttributeException();
+
+// 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();
+
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority()
+ */
+ @Override
+ public int getPriority() {
+ return 1;
+ }
+
+ public String getAttrProviderName() {
+ return this.getClass().getName();
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java
new file mode 100644
index 000000000..def89d0d9
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java
@@ -0,0 +1,688 @@
+/*******************************************************************************
+ * 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.stork2.attributeproviders;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.activation.DataSource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.xml.namespace.QName;
+import javax.xml.transform.Source;
+import javax.xml.transform.stream.StreamSource;
+import javax.xml.ws.Service;
+import javax.xml.ws.soap.SOAPBinding;
+import javax.xml.ws.BindingProvider;
+
+import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.AttributeStatusType;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.NotImplementedException;
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
+import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException;
+import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest;
+import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException;
+import at.gv.egovernment.moa.id.util.VelocityProvider;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.Base64Utils;
+import eu.stork.oasisdss.api.ApiUtils;
+import eu.stork.oasisdss.api.LightweightSourceResolver;
+import eu.stork.oasisdss.api.ResultMajor;
+import eu.stork.oasisdss.api.exceptions.ApiUtilsException;
+import eu.stork.oasisdss.profile.AnyType;
+import eu.stork.oasisdss.profile.Base64Data;
+import eu.stork.oasisdss.profile.DocumentType;
+import eu.stork.oasisdss.profile.DocumentWithSignature;
+import eu.stork.oasisdss.profile.IncludeObject;
+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.PersonalAttributeList;
+import eu.stork.peps.auth.commons.STORKAttrQueryRequest;
+import eu.stork.peps.auth.engine.STORKSAMLEngine;
+import eu.stork.peps.exceptions.STORKSAMLEngineException;
+import eu.stork.documentservice.DocumentService;
+/**
+ * Forwards a signedDoc attribute request to the oasis-dss service instance
+ */
+public class SignedDocAttributeRequestProvider extends AttributeProvider {
+
+ private String dtlUrl = null;
+ private PersonalAttribute requestedAttribute;
+
+ /**
+ * The URL of the service listening for the oasis dss webform post request
+ */
+ private String oasisDssWebFormURL;
+
+ /**
+ * Instantiates a new signed doc attribute request provider.
+ *
+ * @param oasisDssWebFormURL
+ * the AP location
+ * @param attributes
+ */
+ public SignedDocAttributeRequestProvider(String oasisDssWebFormURL, String attributes) {
+ super(attributes);
+ this.oasisDssWebFormURL = oasisDssWebFormURL;
+
+ try {
+ AuthConfiguration authConfigurationProvider = AuthConfigurationProviderFactory.getInstance();
+ dtlUrl = authConfigurationProvider.getDocumentServiceUrl();
+ Logger.info ("SignedDocAttributeRequestProvider, using dtlUrl:"+dtlUrl);
+ } catch (Exception e) {
+ dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService";
+ e.printStackTrace();
+ Logger.error("Loading documentservice url failed, using default value:"+dtlUrl);
+ }
+
+// 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();
+// }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#acquire(java
+ * .lang.String)
+ */
+ @Override
+ protected IPersonalAttributeList acquire(PersonalAttribute attribute, MOASTORKRequest moastorkRequest, IAuthData authData) throws UnsupportedAttributeException,
+ ExternalAttributeRequestRequiredException {
+ if(!attributes.contains(attribute.getName())) {
+ throw new UnsupportedAttributeException();
+ }
+
+ requestedAttribute = attribute;
+ try
+ {
+ String tmp = requestedAttribute.getValue().get(0);
+ }catch(Exception e)
+ {
+ Logger.info("SignedDocAttributeProvide failed:"+e.toString());
+ throw new UnsupportedAttributeException();
+ }
+
+ throw new ExternalAttributeRequestRequiredException(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#parse(javax
+ * .servlet.http.HttpServletRequest)
+ */
+ public IPersonalAttributeList parse(HttpServletRequest httpReq) throws MOAIDException, UnsupportedAttributeException {
+ Logger.debug("Beginning to extract OASIS-DSS response out of HTTP Request");
+
+ try {
+ String base64 = httpReq.getParameter("signresponse");
+ Logger.debug("signresponse url: " + httpReq.getRequestURI().toString());
+ Logger.debug("signresponse querystring: " + httpReq.getQueryString());
+ Logger.debug("signresponse method: " + httpReq.getMethod());
+ Logger.debug("signresponse content type: " + httpReq.getContentType());
+ Logger.debug("signresponse parameter:"+base64);
+ String signResponseString = new String(Base64Utils.decode(base64, false), "UTF8");
+ Logger.debug("RECEIVED signresponse:"+signResponseString);
+ //create SignResponse object
+ Source response = new StreamSource(new java.io.StringReader(signResponseString));
+ SignResponse signResponse = ApiUtils.unmarshal(response, SignResponse.class);
+ //Check if Signing was successfully or not
+
+ if(!signResponse.getResult().getResultMajor().equals(ResultMajor.RESULT_MAJOR_SUCCESS))
+ {
+ //Pass unmodifed or unmarshal & marshal??
+ InputStream istr = ApiUtils.marshalToInputStream(signResponse);
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(istr, writer, "UTF-8");
+ signResponseString = writer.toString();
+ Logger.info("SignResponse with error (unmodified):"+signResponseString);
+ istr.close();
+ }
+ else
+ {
+ //extract doc from signresponse
+ DataSource dataSource = LightweightSourceResolver.getDataSource(signResponse);
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ IOUtils.copy(dataSource.getInputStream(), baos);
+ byte[] data = baos.toByteArray();
+ baos.close();
+
+ //update doc in DTL
+ String docId, dssId = "";
+ docId = signResponse.getDocUI();
+ //For reference dssId equals docId
+ dssId = docId;
+ if (dssId != null && data!=null)
+ {
+ boolean success = false;
+ try{
+ success = updateDocumentInDtl(data, docId, signResponseString);
+ }catch(Exception e){//No document service used?
+ Logger.info("No document service used?");
+ e.printStackTrace();
+ success = false;
+ }
+ if(success)
+ {
+ // set the url in the SignResponse
+ DocumentWithSignature documentWithSignature = new DocumentWithSignature();
+ DocumentType value = new DocumentType();
+ if(dtlUrl.endsWith("?wsdl"))
+ {
+ String tmp = dtlUrl.replace("?wsdl", "");
+ Logger.debug("DocumentUrl ends with ? wsdl, using "+tmp+" instead.");
+ value.setDocumentURL(tmp);
+ }
+ else
+ {
+ value.setDocumentURL(dtlUrl);
+ }
+ documentWithSignature.setDocument(value);
+ if(signResponse.getOptionalOutputs()!=null)
+ {
+ //signResponse.getOptionalOutputs().getAny().add(documentWithSignature);
+ for(Object o :signResponse.getOptionalOutputs().getAny())
+ {
+ if(o instanceof DocumentWithSignature)
+ {
+ signResponse.getOptionalOutputs().getAny().remove(o);
+ signResponse.getOptionalOutputs().getAny().add(documentWithSignature);
+ break;
+ }
+ }
+ }
+ else
+ {
+ AnyType anytype = new AnyType();
+ anytype.getAny().add(documentWithSignature);
+ signResponse.setOptionalOutputs(anytype );
+ }
+
+ // System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl);
+ InputStream istr = ApiUtils.marshalToInputStream(signResponse);
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(istr, writer, "UTF-8");
+ signResponseString = writer.toString();
+ Logger.info("SignResponse overwritten:"+signResponseString);
+ istr.close();
+ }
+ else
+ {
+ //No document service used?
+ // do nothing....
+ //TODO temporary fix because document is deleted after fetching => SP can't download Doc
+ //Add doc to Signresponse
+
+ DocumentWithSignature documentWithSignature = new DocumentWithSignature();
+ DocumentType value = new DocumentType();
+ if(signResponse.getProfile().toLowerCase().contains("xades"))
+ {
+ value.setBase64XML(data);
+ }
+ else
+ {
+ Base64Data base64data = new Base64Data();
+ base64data.setValue(data);
+ base64data.setMimeType(dataSource.getContentType());
+ value.setBase64Data(base64data);
+ }
+ documentWithSignature.setDocument(value);
+ if(signResponse.getOptionalOutputs()!=null)
+ {
+ //signResponse.getOptionalOutputs().getAny().add(documentWithSignature);
+ for(Object o :signResponse.getOptionalOutputs().getAny())
+ {
+ if(o instanceof DocumentWithSignature)
+ {
+ signResponse.getOptionalOutputs().getAny().remove(o);
+ signResponse.getOptionalOutputs().getAny().add(documentWithSignature);
+ break;
+ }
+ }
+ }
+ else
+ {
+ AnyType anytype = new AnyType();
+ anytype.getAny().add(documentWithSignature);
+ signResponse.setOptionalOutputs(anytype );
+ }
+
+ // System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl);
+ InputStream istr = ApiUtils.marshalToInputStream(signResponse);
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(istr, writer, "UTF-8");
+ signResponseString = writer.toString();
+ Logger.info("SignResponse overwritten:"+signResponseString);
+ istr.close();
+ }
+ }
+ else
+ throw new Exception("No DSS id found.");
+ }
+
+ //alter signresponse
+ //done
+ List<String> values = new ArrayList<String>();
+ values.add(signResponseString);
+
+ Logger.debug("Assembling signedDoc attribute");
+ PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values,
+ AttributeStatusType.AVAILABLE.value());
+
+ // pack and return the result
+ PersonalAttributeList result = new PersonalAttributeList();
+ result.add(signedDocAttribute);
+ return result;
+ } catch (UnsupportedEncodingException e) {
+ Logger.error("Failed to assemble signedDoc attribute");
+ throw new MOAIDException("stork.05", null);
+ } catch (ApiUtilsException e) {
+ e.printStackTrace();
+ Logger.error("Failed to assemble signedDoc attribute");
+ throw new MOAIDException("stork.05", null);
+ } catch (IOException e) {
+ e.printStackTrace();
+ Logger.error("Failed to assemble signedDoc attribute");
+ throw new MOAIDException("stork.05", null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ Logger.error("Failed to assemble signedDoc attribute");
+ //throw new MOAIDException("stork.05", null);
+ throw new UnsupportedAttributeException();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#performRedirect
+ * (java.lang.String)
+ */
+ public void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam)
+ throws MOAIDException {
+
+ try {
+ Logger.trace("Initialize VelocityEngine...");
+ Logger.info("performRedirect url:"+url);
+ VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
+ Template template = velocityEngine.getTemplate("/resources/templates/oasis_dss_webform_binding.vm");
+ VelocityContext context = new VelocityContext();
+
+ //Parse SignRequest
+ String signRequestString = requestedAttribute.getValue().get(0);
+ Logger.debug("performRedirect, signrequest:"+signRequestString);
+ Source signDoc = new StreamSource(new java.io.StringReader(signRequestString));
+ SignRequest signRequest = ApiUtils.unmarshal(signDoc, SignRequest.class);
+ try{
+ //search for DTL link
+ String dtlURL = getDtlUrlFromRequest(signRequest);
+ String docId = signRequest.getDocUI();
+
+ if(dtlURL!=null)
+ {
+ String docRequest = getDocTransferRequest(docId, dtlURL);//dtlUrl
+
+ byte[] data = getDocumentFromDtl(docRequest, dtlURL);//dtlUrl
+
+ //load doc from DTL
+ Logger.debug("data:"+data+" "+data.length);
+ try{
+ Logger.trace("data:"+new String(data,"UTF-8"));
+ }catch(Exception e)
+ {
+ Logger.trace("data: creating String failed:"+e);
+ }
+ String mime = getDocumentMimeFromDtl(docId, dtlURL);//dtlUrl
+ Logger.debug("mime:"+mime);
+
+ //add doc as base64* to signrequest => post doc to oasis
+ try{
+ List<IncludeObject> includeObjects = ApiUtils.findNamedElement(
+ signRequest.getOptionalInputs(), "IncludeObject",
+ IncludeObject.class);
+ signRequest.getOptionalInputs().getAny().removeAll(includeObjects);
+
+ String documentId = null;
+ Object objDoc = signRequest.getInputDocuments().getDocumentOrTransformedDataOrDocumentHash().get(0);
+ if (objDoc != null && objDoc instanceof DocumentType)
+ {
+ DocumentType document = (DocumentType)objDoc;
+ documentId = document.getID();
+ }
+ DocumentType document = new DocumentType();
+ if(documentId != null)
+ document.setID(documentId);
+ if(signRequest.getProfile().toLowerCase().contains("xades"))
+ {
+ document.setBase64XML(data);
+ }
+ else
+ {
+ Base64Data b64data = new Base64Data();
+ b64data.setValue(data);
+ b64data.setMimeType(mime);
+ document.setBase64Data(b64data);
+ }
+
+ signRequest.setInputDocuments(ApiUtils.createInputDocuments(document));
+ //override old signRequestString
+
+ InputStream istr = ApiUtils.marshalToInputStream(signRequest);
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(istr, writer, "UTF-8");
+ 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);
+ }
+ }
+ else//Do not modify signRequest, document is already included
+ {
+
+ }
+ }catch(Exception e)
+ {
+ Logger.info("No documentservice used?");
+ e.printStackTrace();
+ }
+
+ context.put("signrequest", Base64Utils.encode(signRequestString.getBytes("UTF8")));
+ context.put("clienturl", url);
+ context.put("action", oasisDssWebFormURL);
+
+ StringWriter writer = new StringWriter();
+ template.merge(context, writer);
+
+ resp.getOutputStream().write(writer.toString().getBytes("UTF-8"));
+ } catch (Exception e) {
+ Logger.error("Error sending DSS signrequest.", e);
+ throw new MOAIDException("stork.11", null);
+ }
+ }
+
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#getSupportedAttributeNames()
+ */
+ @Override
+ public List<String> getSupportedAttributeNames() throws MOAIDException {
+ ArrayList<String> supportedAttributeNames = new ArrayList<String>();
+ for (String attributeName : this.attributes.split(",")) {
+ supportedAttributeNames.add(attributeName);
+ }
+ return supportedAttributeNames;
+ }
+
+
+ //From DTLPEPSUTIL
+
+ /**
+ * Get DTL uril from the oasis sign request
+ * @param signRequest The signature request
+ * @return The URL of DTL service
+ * @throws SimpleException
+ */
+ private String getDtlUrlFromRequest(SignRequest signRequest) throws Exception
+ {
+ if (signRequest == null)
+ throw new Exception("Signature request is empty");
+ else
+ {
+ try
+ {
+ Object objDoc = signRequest.getInputDocuments().getDocumentOrTransformedDataOrDocumentHash().get(0);
+ if (objDoc instanceof DocumentType)
+ {
+ DocumentType document = (DocumentType)objDoc;
+ if (document.getDocumentURL() != null)
+ return document.getDocumentURL();
+ else
+ return null;//throw new Exception("No document url found");
+ }
+ else
+ throw new Exception("No input document found");
+ }
+ catch (Exception ex)
+ {
+ throw new Exception("Unable to parse xml.", ex);
+ }
+ }
+ }
+
+ /**
+ * Get document from DTL
+ * @param transferRequest The transfer request (attribute query)
+ * @param eDtlUrl The DTL url of external DTL
+ * @return the document data
+ * @throws SimpleException
+ */
+ private byte[] getDocumentFromDtl(String transferRequest, String eDtlUrl) throws Exception
+ {
+ URL url = null;
+ try
+ {
+ Logger.debug("getDocumentFromDtl:"+dtlUrl);
+ 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);
+ }
+ }
+
+ /**
+ * Get mime type of document from DTL
+ * @param docId The document id
+ * @param dtlUrl The url of dtl
+ * @return The mime type
+ */
+ private String getDocumentMimeFromDtl(String docId, 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.getDocumentMime(docId, "");
+ else
+ return docservice.getDocumentMime(docId, eDtlUrl);
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ throw new Exception("Error in getDocumentFromDtl", e);
+ }
+ }
+
+ /**
+ * Add document to DTL service
+ * @param docData the document data
+ * @param mime the mime type of data
+ * @param signRequest the sign request
+ * @return the document id
+ * @throws SimpleException
+ */
+ private String addDocumentToDtl(byte[] docData, String mime, String signRequest, String destCountry, String spId) throws Exception
+ {
+ throw new NotImplementedException();
+// URL url = null;
+// String docID = 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);
+//
+// docID = docservice.addDocument(docData, signRequest, destCountry, spId, mime, "");
+// }
+// catch (Exception e)
+// {
+// e.printStackTrace();
+// throw new Exception("Error in addDocumentToDtl", e);
+// }
+//
+// return docID;
+ }
+
+ /**
+ * Update document in DTL
+ * @param docData The docment data
+ * @param docId The document ID
+ * @param signResponse The signature response
+ * @return True if successful
+ * @throws SimpleException
+ */
+ private boolean updateDocumentInDtl(byte[] docData, String docId, String signResponse) throws Exception
+ {
+ boolean success = false;
+ 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);
+
+ success = docservice.updateDocument(docId, signResponse, docData);
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ throw new Exception("Error in updateDocumentInDtl", e);
+ }
+
+ return success;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority()
+ */
+ @Override
+ public int getPriority() {
+ return 99;
+ }
+}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java
new file mode 100644
index 000000000..5ee0e380e
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java
@@ -0,0 +1,193 @@
+/*******************************************************************************
+ * 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.stork2.attributeproviders;
+
+import java.io.StringWriter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
+import at.gv.egovernment.moa.id.data.IAuthData;
+import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException;
+import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest;
+import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException;
+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.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.STORKAttrQueryResponse;
+import eu.stork.peps.auth.engine.STORKSAMLEngine;
+import eu.stork.peps.exceptions.STORKSAMLEngineException;
+
+/**
+ * creates a STORK attribute request for a configurable set of attributes
+ */
+public class StorkAttributeRequestProvider extends AttributeProvider {
+
+ private PersonalAttributeList requestedAttributes;
+
+ /** The destination. */
+ private String destination;
+
+ /** The sp country code. */
+ private String spCountryCode;
+
+ /**
+ * Instantiates a new stork attribute request provider.
+ *
+ * @param apUrl the AP location
+ * @param supportedAttributes the supported attributes as csv
+ */
+ public StorkAttributeRequestProvider(String apUrl, String supportedAttributes) {
+ super(supportedAttributes);
+ destination = apUrl;
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#acquire(java.lang.String)
+ */
+ @Override
+ protected IPersonalAttributeList acquire(PersonalAttribute attribute, MOASTORKRequest moastorkRequest, IAuthData authData)
+ throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException {
+
+ if (!attributes.contains(attribute.getName()))
+ throw new UnsupportedAttributeException();
+
+ this.spCountryCode = moastorkRequest.getSpCountry();
+
+ requestedAttributes = new PersonalAttributeList(1);
+ requestedAttributes.add(attribute);
+ throw new ExternalAttributeRequestRequiredException(this);
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#parse(javax.servlet.http.HttpServletRequest)
+ */
+ public IPersonalAttributeList parse(HttpServletRequest httpReq) throws MOAIDException, UnsupportedAttributeException {
+
+ 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");
+
+ STORKAttrQueryResponse attrResponse = null;
+ try {
+ //validate SAML Token
+ Logger.debug("Starting validation of SAML response");
+ attrResponse = engine.validateSTORKAttrQueryResponse(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 attrResponse.getPersonalAttributeList();
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#performRedirect(java.lang.String)
+ */
+ public void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException {
+
+ String spSector = "Business";
+ String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName();
+ String spApplication = spInstitution;
+
+ //generate AuthnRquest
+ STORKAttrQueryRequest attributeRequest = new STORKAttrQueryRequest();
+ attributeRequest.setDestination(destination);
+ attributeRequest.setAssertionConsumerServiceURL(url);
+ attributeRequest.setIssuer(HTTPUtils.getBaseURL(req));
+ attributeRequest.setQaa(oaParam.getQaaLevel());
+ attributeRequest.setSpInstitution(spInstitution);
+ attributeRequest.setCountry(spCountryCode);
+ attributeRequest.setSpCountry(spCountryCode);
+ attributeRequest.setSpApplication(spApplication);
+ attributeRequest.setSpSector(spSector);
+ attributeRequest.setPersonalAttributeList(requestedAttributes);
+
+ attributeRequest.setCitizenCountryCode("AT");
+
+
+ Logger.debug("STORK AttrRequest successfully assembled.");
+
+ STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("VIDP");
+ try {
+ attributeRequest = samlEngine.generateSTORKAttrQueryRequest(attributeRequest);
+ } catch (STORKSAMLEngineException e) {
+ Logger.error("Could not sign STORK SAML AttrRequest.", e);
+ throw new MOAIDException("stork.00", null);
+ }
+ Logger.info("Using citizen country code: " + attributeRequest.getCitizenCountryCode());
+ Logger.info("STORK AttrRequest successfully signed!");
+
+ try {
+ Logger.trace("Initialize VelocityEngine...");
+
+ VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
+ Template template = velocityEngine.getTemplate("/resources/templates/saml2-post-binding-moa.vm");
+ VelocityContext context = new VelocityContext();
+ context.put("SAMLRequest", PEPSUtil.encodeSAMLToken(attributeRequest.getTokenSaml()));
+ context.put("action", destination);
+
+ StringWriter writer = new StringWriter();
+ template.merge(context, writer);
+
+ resp.getOutputStream().write(writer.toString().getBytes("UTF-8"));
+ } catch (Exception e) {
+ Logger.error("Error sending STORK SAML AttrRequest.", e);
+ throw new MOAIDException("stork.11", null);
+ }
+ Logger.info("STORK AttrRequest successfully rendered!");
+ }
+
+ /* (non-Javadoc)
+ * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority()
+ */
+ @Override
+ public int getPriority() {
+ return 99;
+ }
+
+}
+
diff --git a/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo b/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo
new file mode 100644
index 000000000..5d7af87d5
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo
@@ -0,0 +1 @@
+at.gv.egovernment.moa.id.protocols.stork2.STORKProtocol \ No newline at end of file
diff --git a/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder b/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder
new file mode 100644
index 000000000..540802dce
--- /dev/null
+++ b/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder
@@ -0,0 +1,14 @@
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKAdoptedFamilyNameAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKAgeAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKCanonicalResidenceAddressAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKCountryCodeOfBirthAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKFiscalNumberAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKGenderAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKInhertedFamilyNameAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKIsAgeOverAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKMaritalStatusAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKNationalityCodeAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKPseudonymAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKResidencePermitAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKTextResidenceAddressAttributBuilder
+at.gv.egovernment.moa.id.protocols.builder.attributes.STORKTitleAttributBuilder \ No newline at end of file
diff --git a/id/server/modules/pom.xml b/id/server/modules/pom.xml
index 1ca5b3835..db03326ea 100644
--- a/id/server/modules/pom.xml
+++ b/id/server/modules/pom.xml
@@ -22,10 +22,13 @@
<modules>
<module>module-stork</module>
<module>module-monitoring</module>
+ <module>moa-id-modules-saml1</module>
+ <module>moa-id-module-openID</module>
+ <module>moa-id-modul-citizencard_authentication</module>
</modules>
<dependencies>
- <dependency>
+ <dependency>
<groupId>MOA.id.server</groupId>
<artifactId>moa-id-lib</artifactId>
<exclusions>