diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at')
208 files changed, 1906 insertions, 23997 deletions
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAReversionLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAReversionLogger.java index 77105d77e..8ee32c54e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAReversionLogger.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAReversionLogger.java @@ -33,8 +33,8 @@ import at.gv.egovernment.moa.id.auth.data.IdentityLink; 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.data.MISMandate; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java index 0d9c1ec20..bfed65ae2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java @@ -54,9 +54,9 @@ 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.moduls.IRequest; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java deleted file mode 100644 index 8aa6a15d7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ /dev/null @@ -1,1610 +0,0 @@ - -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.io.UnsupportedEncodingException; -import java.security.Principal; -import java.security.cert.CertificateException; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.UUID; -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.opensaml.xml.util.XMLHelper; -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.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.client.SZRGWClient; -import at.gv.egovernment.moa.id.client.SZRGWClientException; -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.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.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.util.XMLUtil; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; -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; -import at.gv.util.xsd.mis.MandateIdentifiers; -import at.gv.util.xsd.mis.Target; -import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest; -import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest.PEPSData; -import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; -import at.gv.util.xsd.srzgw.MISType; -import at.gv.util.xsd.srzgw.MISType.Filters; - -/** - * 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 MOAIDAuthConstants { - - /** - * single instance - */ - private static AuthenticationServer instance; - - /** - * time out in milliseconds used by {@link cleanup} for session store - */ - private long sessionTimeOutCreated = 15 * 60 * 1000; // default 10 minutes - private long sessionTimeOutUpdated = 10 * 60 * 1000; // default 10 minutes - /** - * time out in milliseconds used by {@link cleanup} for authentication data - * store - */ - private long authDataTimeOut = 2 * 60 * 1000; // default 2 minutes - - /** - * 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><InfoboxReadRequest></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><InfoboxReadRequest></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ä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ü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><InfoboxReadResponse></code> sent by the security layer implementation.<br> - * <ul> - * <li>Validates given <code><InfoboxReadResponse></code></li> - * <li>Parses identity link enclosed in <code><InfoboxReadResponse></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><CreateXMLSignatureRequest></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><InfoboxReadResponse></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()); - - // 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><InfoboxReadResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><InfoboxReadResponse></code></li> - * <li>Parses identity link enclosed in - * <code><InfoboxReadResponse></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><CreateXMLSignatureRequest></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><InfoboxReadResponse></code> - * @return String representation of the - * <code><CreateXMLSignatureRequest></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><CreateXMLSignatureRequest></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><InfoboxReadResponse></code> - * @return String representation of the - * <code><CreateXMLSignatureRequest></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><CreateXMLSignatureRequest></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><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses response enclosed in - * <code><CreateXMLSignatureResponse></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><CreateXMLSignatureResponse></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><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses response enclosed in - * <code><CreateXMLSignatureResponse></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><ReadInfoboxResponse></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><saml:Assertion></code> from - * given session data. - * - * @param session authentication session - * @return <code><saml:Assertion></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("&", "&"); - - } 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("&", "&"); - 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><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses <code><CreateXMLSignatureResponse></code> for error - * codes</li> - * <li>Parses authentication block enclosed in - * <code><CreateXMLSignatureResponse></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><CreateXMLSignatureResponse></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(); - 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><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses <code><CreateXMLSignatureResponse></code> for error - * codes</li> - * <li>Parses authentication block enclosed in - * <code><CreateXMLSignatureResponse></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><CreateXMLSignatureResponse></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); - } - - /** - * Retrieves a session from the session store. - * - * @param id session ID - * @return <code>AuthenticationSession</code> stored with given session ID (never {@code null}). - * @throws AuthenticationException in case the session id does not reflect a valic, active session. - */ - public static AuthenticationSession getSession(String id) - throws AuthenticationException { - AuthenticationSession session; - try { - session = AuthenticationSessionStoreage.getSession(id); - - if (session == null) - throw new AuthenticationException("auth.02", new Object[]{id}); - return session; - - } catch (MOADatabaseException e) { - throw new AuthenticationException("auth.02", new Object[]{id}); - - } catch (Exception e) { - throw new AuthenticationException("parser.04", new Object[]{id}); - } - } - - /** - * Cleans up expired session and authentication data stores. - */ - public void cleanup() { - long now = new Date().getTime(); - - //clean AuthenticationSessionStore - - AuthenticationSessionStoreage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); - - //clean AssertionStore - AssertionStorage assertionstore = AssertionStorage.getInstance(); - assertionstore.clean(now, authDataTimeOut); - - //clean ExeptionStore - DBExceptionStoreImpl exstore = DBExceptionStoreImpl.getStore(); - exstore.clean(now, authDataTimeOut); - - } - - /** - * Sets the sessionTimeOut. - * - * @param seconds Time out of the session in seconds - */ - public void setSecondsSessionTimeOutCreated(long seconds) { - sessionTimeOutCreated = seconds * 1000; - } - - public void setSecondsSessionTimeOutUpdated(long seconds) { - sessionTimeOutUpdated = seconds * 1000; - } - - /** - * Sets the authDataTimeOut. - * - * @param seconds Time out for signing AuthData in seconds - */ - public void setSecondsAuthDataTimeOut(long seconds) { - authDataTimeOut = seconds * 1000; - } - - /** - * 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; - } - - /** - * Does the request to the SZR-GW. - * - * @param signature the signature - * @return the identity link - * @throws SZRGWClientException the sZRGW client exception - * @throws ConfigurationException the configuration exception - */ - public CreateIdentityLinkResponse getIdentityLink(Element signature) throws SZRGWClientException, ConfigurationException { - return getIdentityLink(null, null, null, null, XMLHelper.nodeToString(signature), null); - } - - /** - * Does the request to the SZR-GW. - * - * @param PEPSIdentifier the pEPS identifier - * @param PEPSFirstname the pEPS firstname - * @param PEPSFamilyname the pEPS familyname - * @param PEPSDateOfBirth the pEPS date of birth - * @param signature XMLDSIG signature - * @return Identity link assertion - * @throws SZRGWClientException the sZRGW client exception - * @throws ConfigurationException the configuration exception - */ - public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature, String PEPSFiscalNumber) throws SZRGWClientException { - return getIdentityLink(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null, PEPSFiscalNumber); - } - - /** - * SZR-GW Client interface. - * - * @param eIdentifier the e identifier - * @param givenName the given name - * @param lastName the last name - * @param dateOfBirth the date of birth - * @param citizenSignature the citizen signature - * @param representative the representative - * @param represented the represented - * @param mandate the mandate - * @return the identity link - * @throws SZRGWClientException the sZRGW client exception - */ - public CreateIdentityLinkResponse getIdentityLink(String eIdentifier, - String givenName, String lastName, String dateOfBirth, String gender, - String citizenSignature, String representative, String represented, - String mandate, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { - return getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, gender, - citizenSignature, representative, represented, mandate, null, - null, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); - } - - /** - * Gets the identity link. - * - * @param citizenSignature the citizen signature - * @param representative the representative - * @param represented the represented - * @param mandate the mandate - * @param organizationAddress the organization address - * @param organizationType the organization type - * @return the identity link - * @throws SZRGWClientException - */ - public CreateIdentityLinkResponse getIdentityLink(String citizenSignature, - String representative, String represented, String mandateContent, - String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { - return getIdentityLink(null, null, null, null, null, - citizenSignature, represented, representative, mandateContent, organizationAddress, - organizationType, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); - } - - public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String gender, String citizenSignature, String represented, String representative, String mandateContent, String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { - - try { - AuthConfiguration authConf = AuthConfigurationProviderFactory.getInstance(); - ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); - - String requestID = UUID.randomUUID().toString(); - SZRGWClient client = new SZRGWClient(connectionParameters); - - CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); - request.setSignature(citizenSignature.getBytes("UTF-8")); - request.setReqID(requestID); - if(PEPSDateOfBirth!=null || PEPSFamilyname!=null || PEPSFirstname!=null || PEPSIdentifier!=null || representative!=null || represented!=null || mandateContent!=null || organizationAddress!=null || organizationType!=null) - { - PEPSData data = new PEPSData(); - data.setDateOfBirth(PEPSDateOfBirth); - data.setFamilyname(PEPSFamilyname); - data.setFirstname(PEPSFirstname); - data.setIdentifier(PEPSIdentifier); - - data.setFiscalNumber(PEPSFiscalNumber); - - data.setRepresentative(representative); - data.setRepresented(represented); - data.setMandateContent(mandateContent); - - data.setLegalPersonCanonicalRegisteredAddress(organizationAddress); - data.setLegalPersonTranslatableType(organizationType); - - request.setPEPSData(data); - } - if (null != mandateContent) { - MISType mis = new MISType(); - - Target targetObject = new Target(); - targetObject.setType(targetType); - targetObject.setValue(targetValue); - mis.setTarget(targetObject); - - mis.setOAFriendlyName(oaFriendlyName); - - Filters filterObject = new Filters(); - MandateIdentifiers mandateIds = new MandateIdentifiers(); - for(String current : filters) - mandateIds.getMandateIdentifier().add(current.trim()); - filterObject.setMandateIdentifiers(mandateIds); - mis.setFilters(filterObject); - - request.setMIS(mis); - } - - if (MiscUtil.isEmpty(connectionParameters.getUrl())) { - Logger.warn("SZR-Gateway Service URL is empty"); - throw new SZRGWClientException("service.07"); - } - - Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); - CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request, connectionParameters.getUrl()); - return response; - - } - catch (ConfigurationException e) { - Logger.warn(e); - Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); - } catch (UnsupportedEncodingException e) { - Logger.warn(e); - } - - return null; - - } - - /** - * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java index 104cd8622..1f12675ca 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java @@ -26,7 +26,7 @@ public class AuthenticationSessionCleaner implements Runnable { while (true) { try { Logger.debug("AuthenticationSessionCleaner run"); - AuthenticationServer.getInstance().cleanup(); + BaseAuthenticationServer.cleanup(); } catch (Exception e) { Logger.error(MOAIDMessageProvider.getInstance().getMessage("cleaner.01", null), e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java new file mode 100644 index 000000000..5e3b6653b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java @@ -0,0 +1,100 @@ + +package at.gv.egovernment.moa.id.auth; + +import java.io.UnsupportedEncodingException; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.opensaml.xml.util.XMLHelper; + +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.client.SZRGWClient; +import at.gv.egovernment.moa.id.client.SZRGWClientException; +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.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.storage.AssertionStorage; +import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; +import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import at.gv.util.xsd.mis.MandateIdentifiers; +import at.gv.util.xsd.mis.Target; +import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest; +import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest.PEPSData; +import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; +import at.gv.util.xsd.srzgw.MISType; +import at.gv.util.xsd.srzgw.MISType.Filters; + +/** + * 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 abstract class BaseAuthenticationServer extends MOAIDAuthConstants { + + /** + * Retrieves a session from the session store. + * + * @param id session ID + * @return <code>AuthenticationSession</code> stored with given session ID (never {@code null}). + * @throws AuthenticationException in case the session id does not reflect a valic, active session. + */ + public static AuthenticationSession getSession(String id) + throws AuthenticationException { + AuthenticationSession session; + try { + session = AuthenticationSessionStoreage.getSession(id); + + if (session == null) + throw new AuthenticationException("auth.02", new Object[]{id}); + return session; + + } catch (MOADatabaseException e) { + throw new AuthenticationException("auth.02", new Object[]{id}); + + } catch (Exception e) { + throw new AuthenticationException("parser.04", new Object[]{id}); + } + } + + /** + * Cleans up expired session and authentication data stores. + */ + public static void cleanup() { + long now = new Date().getTime(); + + try { + int sessionTimeOutCreated = AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut() * 1000; + int sessionTimeOutUpdated = AuthConfigurationProviderFactory.getInstance().getSSOUpdatedTimeOut() * 1000; + int authDataTimeOut = AuthConfigurationProviderFactory.getInstance().getTransactionTimeOut() * 1000; + + //clean AuthenticationSessionStore + AuthenticationSessionStoreage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); + + //clean AssertionStore + AssertionStorage assertionstore = AssertionStorage.getInstance(); + assertionstore.clean(now, authDataTimeOut); + + //clean ExeptionStore + DBExceptionStoreImpl exstore = DBExceptionStoreImpl.getStore(); + exstore.clean(now, authDataTimeOut); + + } catch (Exception e) { + Logger.error("Session cleanUp FAILED!" , e); + + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index 49c3578d8..fa30f9ffd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -169,6 +169,11 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String MDC_TRANSACTION_ID = "transactionId"; public static final String MDC_SESSION_ID = "sessionId"; - public static final int TIME_JITTER = 5; //allow 5 minutes time jitter for AuthnRequests - + + //AuthnRequest IssueInstant validation + public static final int TIME_JITTER = 5; //all 5 minutes time jitter + + public static final String PROCESSCONTEXT_INTERFEDERATION_ENTITYID = "interfederationIDPEntityID"; + public static final String PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION = "requireLocalAuthentication"; + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index ed632d8b9..953a478be 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -20,9 +20,6 @@ import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigLoader; 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.PropertyBasedAuthConfigurationProvider; -import at.gv.egovernment.moa.id.iaik.config.LoggerConfigImpl; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.util.AxisSecureSocketFactory; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.SSLUtils; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationAssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationAssertionBuilder.java deleted file mode 100644 index 89f42ab7d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationAssertionBuilder.java +++ /dev/null @@ -1,125 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -package at.gv.egovernment.moa.id.auth.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java deleted file mode 100644 index 760d28d5b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java +++ /dev/null @@ -1,584 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ - - -package at.gv.egovernment.moa.id.auth.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><saml:Assertion></code> - * to be included in a <code><CreateXMLSignatureResponse></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><saml:Assertion></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äftsbereich"; maybe <code>null</code> if the application - * is a business application - * @param identityLinkValue the content of the <code><pr:Value></code> - * child element of the <code><pr:Identification></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><pr:Type></code> - * child element of the <code><pr:Identification></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><saml:Assertion></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><saml:Assertion></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äftsbereich"; maybe <code>null</code> if the application - * is a business application - * @param identityLinkValue the content of the <code><pr:Value></code> - * child element of the <code><pr:Identification></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><pr:Type></code> - * child element of the <code><pr:Identification></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><saml:Assertion></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataAssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataAssertionBuilder.java deleted file mode 100644 index fc04fa9a7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataAssertionBuilder.java +++ /dev/null @@ -1,458 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ - - - -package at.gv.egovernment.moa.id.auth.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><saml:Assertion></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><saml:Assertion></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><saml:Assertion></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><saml:Assertion></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><saml:Assertion></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><saml:Attribute></code> named <code>"isPublicAuthority"</code>, - * to be inserted into the <code><saml:Assertion></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><saml:Assertion></code>. - * - * @param authData the <code>AuthenticationData</code> to build the - * <code><saml:Assertion></code> from - * @param xmlPersonData <code>lt;pr:Person></code> element as a String - * @param xmlAuthBlock authentication block to be included in a - * <code>lt;saml:SubjectConfirmationData></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><saml:Assertion></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><saml:Assertion></code>. - * - * @param authData the <code>AuthenticationData</code> to build the - * <code><saml:Assertion></code> from - * @param xmlPersonData <code>lt;pr:Person></code> element as a String - * @param xmlAuthBlock authentication block to be included in a - * <code>lt;saml:SubjectConfirmationData></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><saml:Assertion></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 573f2e09f..998fa495f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -27,6 +27,7 @@ import iaik.x509.X509Certificate; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; import java.security.PrivateKey; import java.util.ArrayList; import java.util.Arrays; @@ -82,6 +83,7 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.data.AuthenticationRoleFactory; import at.gv.egovernment.moa.id.data.IAuthData; +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.protocols.pvp2x.PVPTargetConfiguration; @@ -94,13 +96,10 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtracto import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData; -import at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; @@ -135,19 +134,29 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { AuthenticationData authdata = null; - if (protocolRequest instanceof SAML1RequestImpl) { - //request is SAML1 - SAML1AuthenticationData saml1authdata = new SAML1AuthenticationData(); - if (session.getExtendedSAMLAttributesOA() == null) - saml1authdata.setExtendedSAMLAttributesOA(new ArrayList<ExtendedSAMLAttribute>()); - else - saml1authdata.setExtendedSAMLAttributesOA(session.getExtendedSAMLAttributesOA()); + try { + Object saml1Requst = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl").newInstance(); + IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); + if (protocolRequest.getClass().isInstance(saml1Requst)) { + //request is SAML1 + if (session.getExtendedSAMLAttributesOA() == null) { + saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, new ArrayList<ExtendedSAMLAttribute>()); + + } else { + saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, session.getExtendedSAMLAttributesOA()); + } + + authdata = (AuthenticationData) saml1authdata; + + } else { + authdata = new AuthenticationData(); + + } - authdata = saml1authdata; - - } else { + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { authdata = new AuthenticationData(); - + } //reuse some parameters if it is a reauthentication @@ -1034,7 +1043,16 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { if (baseIDType.equals(Constants.URN_PREFIX_BASEID)) { // only compute bPK if online application is a public service and we have the Stammzahl String target = null; - if (protocolRequest instanceof SAML1RequestImpl) + Object saml1Requst = null; + try { + saml1Requst = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl").newInstance(); + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | java.lang.SecurityException ex) { + + + } + + if (saml1Requst != null && protocolRequest.getClass().isInstance(saml1Requst)) target = protocolRequest.getTarget(); else target = oaParam.getTarget(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/Builder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/Builder.java deleted file mode 100644 index ca9bf2080..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/Builder.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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[] {"<" + tag.substring(1, tag.length() - 1) + ">"}); - } - } 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CertInfoVerifyXMLSignatureRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CertInfoVerifyXMLSignatureRequestBuilder.java deleted file mode 100644 index a904242e1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CertInfoVerifyXMLSignatureRequestBuilder.java +++ /dev/null @@ -1,130 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><VerifyXMLSignatureRequest></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><dsig:Signature></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><VerifyXMLSignatureRequest></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java deleted file mode 100644 index f4b5cb4c9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java +++ /dev/null @@ -1,172 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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ü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>"&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(""");
- else if (ch == '<')
- out.write("<");
- else if (ch == '>')
- out.write(">");
- else if (ch == 'ä')
- out.write("ä");
- else if (ch == 'ö')
- out.write("ö");
- else if (ch == 'ü')
- out.write("ü");
- else if (ch == 'Ä')
- out.write("Ä");
- else if (ch == 'Ö')
- out.write("Ö");
- else if (ch == 'Ü')
- out.write("Ü");
- else if (ch == 'ß')
- out.write("ß");
- 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DynamicOAAuthParameterBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DynamicOAAuthParameterBuilder.java index bc3645e74..79b09503f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DynamicOAAuthParameterBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DynamicOAAuthParameterBuilder.java @@ -22,6 +22,7 @@ */ package at.gv.egovernment.moa.id.auth.builder; +import java.lang.reflect.InvocationTargetException; import java.util.List; import org.opensaml.saml2.core.Attribute; @@ -35,7 +36,6 @@ 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.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; @@ -121,24 +121,28 @@ public class DynamicOAAuthParameterBuilder { dynOAParams.setApplicationID(oaParam.getPublicURLPrefix()); dynOAParams.setBusinessService(oaParam.getBusinessService()); - if (protocolRequest instanceof MOASTORKRequest) - return buildFromSTORKRequest(dynOAParams, (MOASTORKRequest) protocolRequest); + Object storkRequst = null; + try { + storkRequst = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest").newInstance(); + if (storkRequst != null && + protocolRequest.getClass().isInstance(storkRequst)) { + + dynOAParams.setBusinessTarget(Constants.URN_PREFIX_STORK + "+" + "AT" + "+" + + protocolRequest.getClass().getMethod("getSpCountry", null).invoke(protocolRequest, null)); + dynOAParams.setBusinessService(true); + + } + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { + + + } + +// if (protocolRequest instanceof MOASTORKRequest) +// return buildFromSTORKRequest(dynOAParams, (MOASTORKRequest) protocolRequest); Logger.warn("Dynamic OA generation failed. RequestType is not implemented."); return null; } - /** - * @param oaParam - * @param protocolRequest - * @return - */ - private static IOAAuthParameters buildFromSTORKRequest( - DynamicOAAuthParameters oaParam, MOASTORKRequest protocolRequest) { - - oaParam.setBusinessTarget(Constants.URN_PREFIX_STORK + "+" + "AT" + "+" + protocolRequest.getSpCountry()); - oaParam.setBusinessService(true); - - return oaParam; - } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java deleted file mode 100644 index dc981ba33..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java +++ /dev/null @@ -1,246 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><InfoboxReadRequest></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ü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ü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ü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>"&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("""); - } else if (ch == '<') { - out.write("<"); - } else if (ch == '>') { - out.write(">"); - } else if (ch == 'ä') { - out.write("ä"); - } else if (ch == 'ö') { - out.write("ö"); - } else if (ch == 'ü') { - out.write("ü"); - } else if (ch == 'Ä') { - out.write("Ä"); - } else if (ch == 'Ö') { - out.write("Ö"); - } else if (ch == 'Ãœ') { - out.write("Ü"); - } else if (ch == 'ß') { - out.write("ß"); - } 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetVerifyAuthBlockFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetVerifyAuthBlockFormBuilder.java deleted file mode 100644 index 3f2d96df4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetVerifyAuthBlockFormBuilder.java +++ /dev/null @@ -1,128 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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ü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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java deleted file mode 100644 index 81ef5e408..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java +++ /dev/null @@ -1,195 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><InfoboxReadRequest></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><InfoboxReadRequest></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><InfoboxReadRequest></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><InfoboxReadRequest></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><InfoboxReadRequest></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java deleted file mode 100644 index bb3533664..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilderCertificate.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><InfoboxReadRequest></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><InfoboxReadRequest></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><InfoboxReadRequest></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginConfirmationBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginConfirmationBuilder.java deleted file mode 100644 index 31e4c0578..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginConfirmationBuilder.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -package at.gv.egovernment.moa.id.auth.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ü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ü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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java index dff2daa09..99ba49d26 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java @@ -38,7 +38,6 @@ 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.stork.CPEPS; -import at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol; import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -137,12 +136,12 @@ public class LoginFormBuilder { } if(value != null) { - if(modul == null) { - modul = SAML1Protocol.PATH; - } - if(action == null) { - action = SAML1Protocol.GETARTIFACT; - } +// if(modul == null) { +// modul = SAML1Protocol.PATH; +// } +// if(action == null) { +// action = SAML1Protocol.GETARTIFACT; +// } value = value.replace(MODUL, modul); value = value.replace(ACTION, action); value = value.replace(OANAME, oaParam.getFriendlyName()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java deleted file mode 100644 index 333d8680c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/PersonDataBuilder.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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></code> element to be inserted - * in the authentication data <code>lt;saml:Assertion></code>. - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class PersonDataBuilder { - - /** - * Constructor for PersonDataBuilder. - */ - public PersonDataBuilder() { - super(); - } - /** - * Builds the <code><pr:Person></code> element.<br/> - * Utilizes the parsed <code><prPerson></code> from the identity link - * and the information regarding inclusion of <code>"Stammzahl"</code> in the - * <code><pr:Person></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><pr:Person></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilder.java deleted file mode 100644 index eeca78e60..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLArtifactBuilder.java +++ /dev/null @@ -1,167 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java deleted file mode 100644 index 8b0d906fe..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java +++ /dev/null @@ -1,137 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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></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></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java index 295254eda..d14910319 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java @@ -35,7 +35,6 @@ import org.apache.commons.io.IOUtils; 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.saml1.SAML1Protocol; import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.logging.Logger; @@ -138,12 +137,12 @@ public class SendAssertionFormBuilder { } if(value != null) { - if(modul == null) { - modul = SAML1Protocol.PATH; - } - if(action == null) { - action = SAML1Protocol.GETARTIFACT; - } +// if(modul == null) { +// modul = SAML1Protocol.PATH; +// } +// if(action == null) { +// action = SAML1Protocol.GETARTIFACT; +// } value = value.replace(MODUL, modul); value = value.replace(ACTION, action); value = value.replace(ID, id); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java deleted file mode 100644 index 5c1b12e0d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -package at.gv.egovernment.moa.id.auth.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java deleted file mode 100644 index d2ea53011..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/VerifyXMLSignatureRequestBuilder.java +++ /dev/null @@ -1,408 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><VerifyXMLSignatureRequestBuilder></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><VerifyXMLSignatureRequest></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><VerifyXMLSignatureRequest></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><VerifyXMLSignatureRequest></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><VerifyXMLSignatureRequest></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 76bf93249..59482c4a8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java @@ -43,22 +43,14 @@ import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Date; -import java.util.Iterator; import java.util.List; -import java.util.Vector; -import org.w3c.dom.Element; import eu.stork.peps.auth.commons.IPersonalAttributeList; import eu.stork.peps.auth.commons.STORKAuthnRequest; -import eu.stork.peps.auth.commons.STORKAuthnResponse; -import at.gv.egovernment.moa.id.auth.validator.InfoboxValidator; -import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; -import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; +import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DOMUtils; /** * Session data to be stored between <code>AuthenticationServer</code> API calls. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java deleted file mode 100644 index 72a7d3ba1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java deleted file mode 100644 index 8ae4a9999..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java +++ /dev/null @@ -1,28 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.internal; - -import org.apache.commons.lang3.StringUtils; - -import at.gv.egovernment.moa.id.auth.modules.AuthModule; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; - -/** - * Module descriptor - */ -public class DefaultAuthModuleImpl implements AuthModule { - - @Override - public int getPriority() { - return 0; - } - - @Override - public String selectProcess(ExecutionContext context) { - return StringUtils.isBlank((String) context.get("ccc")) ? "DefaultAuthentication" : null; - } - - @Override - public String[] getProcessDefinitions() { - return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml" }; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java deleted file mode 100644 index 0cfd16262..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java +++ /dev/null @@ -1,103 +0,0 @@ -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.ParamValidatorUtils;
-import at.gv.egovernment.moa.id.util.ServletUtils;
-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());
-
- ServletUtils.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java deleted file mode 100644 index df3d90aab..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java +++ /dev/null @@ -1,138 +0,0 @@ -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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java new file mode 100644 index 000000000..4a6ecd56a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java @@ -0,0 +1,297 @@ +/* + * 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.lang.reflect.InvocationTargetException; +import java.security.NoSuchAlgorithmException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.joda.time.DateTime; +import org.opensaml.common.impl.SecureRandomIdentifierGenerator; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.Issuer; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.xml.security.SecurityException; + +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.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.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.IRequest; +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.protocols.pvp2x.binding.IEncoder; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +public class CreateInterfedeartionRequestTask 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 { + boolean requiredLocalAuthentication = true; + + IRequest pendingReq = RequestStorage.getPendingRequest( + (String) executionContext.get("pendingRequestID")); + + String idpEntityID = + (String) executionContext.get(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID); + + if (MiscUtil.isEmpty(idpEntityID)) { + Logger.info("Interfederation not possible -> not inderfederation IDP EntityID found!"); + throw new TaskExecutionException("Interfederation not possible", new MOAIDException("No inderfederation-IDP EntityID found.", null)); + + } + + //TODO: create MOASession + //TODO: set relayState to MOASession + //TODO: add support for requested attributes (from context and from metadata) + + + try { + OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(idpEntityID); + OAAuthParameter sp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(pendingReq.getOAURL()); + + if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { + Logger.info("Requested interfederation IDP " + pendingReq.getRequestedIDP() + " is not valid for interfederation."); + Logger.debug("isInderfederationIDP:" + String.valueOf(idp.isInderfederationIDP()) + + " isInboundSSOAllowed:" + String.valueOf(idp.isInboundSSOInterfederationAllowed())); + Logger.info("Switch to local authentication on this IDP ... "); + + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, true); + return; + + } + + + + + EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). + getEntityDescriptor(idpEntityID); + + if (idpEntity != null ) { + + //fetch endpoint from IDP metadata + SingleSignOnService redirectEndpoint = null; + for (SingleSignOnService sss : + idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS).getSingleSignOnServices()) { + + // use POST binding as default if it exists + //TODO: maybe use RedirectBinding as default + if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { + redirectEndpoint = sss; + + } else if ( sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) && + redirectEndpoint == null ) + redirectEndpoint = sss; + } + + if (redirectEndpoint != null) { + + AuthnRequest authReq = SAML2Utils + .createSAMLObject(AuthnRequest.class); + SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); + authReq.setID(gen.generateIdentifier()); + + //send passive AuthnRequest + authReq.setIsPassive(idp.isPassivRequestUsedForInterfederation()); + + authReq.setAssertionConsumerServiceIndex(0); + authReq.setIssueInstant(new DateTime()); + Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); + issuer.setValue(pendingReq.getAuthURLWithOutSlash()); + + issuer.setFormat(NameIDType.ENTITY); + authReq.setIssuer(issuer); + NameIDPolicy policy = SAML2Utils + .createSAMLObject(NameIDPolicy.class); + policy.setAllowCreate(true); + policy.setFormat(NameID.TRANSIENT); + authReq.setNameIDPolicy(policy); + + authReq.setDestination(redirectEndpoint.getLocation()); + + RequestedAuthnContext reqAuthContext = + SAML2Utils.createSAMLObject(RequestedAuthnContext.class); + + AuthnContextClassRef authnClassRef = + SAML2Utils.createSAMLObject(AuthnContextClassRef.class); + + //check if STORK protocol module is in ClassPath + Object storkRequst = null; + Integer storkSecClass = null; + try { + storkRequst = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest").newInstance(); + if (storkRequst != null && + pendingReq.getClass().isInstance(storkRequst)) { + Object storkAuthnRequest = pendingReq.getClass().getMethod("getStorkAuthnRequest", null).invoke(pendingReq, null); + storkSecClass = (Integer) storkAuthnRequest.getClass().getMethod("getQaa", null).invoke(storkAuthnRequest, null); + + } + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { + + + } + + + if (sp != null && sp.isSTORKPVPGateway()){ + //use PVP SecClass instead of STORK QAA level + String secClass = null; + if (storkRequst != null && + pendingReq.getClass().isInstance(storkRequst)) { + + try { + secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( + PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); + + } catch (Exception e) { + Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); + + } + } + + if (MiscUtil.isNotEmpty(secClass)) + authnClassRef.setAuthnContextClassRef(secClass); + else + authnClassRef.setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"); + + } else { + if (storkRequst != null && + pendingReq.getClass().isInstance(storkRequst)) { + //use requested QAA level from STORK request + try { + authnClassRef.setAuthnContextClassRef( + PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); + Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef() + + " from STORK request"); + + } catch (Exception e) { + Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); + + } + + } + + if (MiscUtil.isEmpty(authnClassRef.getAuthnContextClassRef())) + authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4"); + + } + + reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); + reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); + authReq.setRequestedAuthnContext(reqAuthContext); + + IEncoder binding = null; + if (redirectEndpoint.getBinding().equals( + SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + binding = new RedirectBinding(); + + } else if (redirectEndpoint.getBinding().equals( + SAMLConstants.SAML2_POST_BINDING_URI)) { + binding = new PostBinding(); + + } + + binding.encodeRequest(request, response, authReq, + redirectEndpoint.getLocation(), pendingReq.getRequestID()); + + //build and send request without an error + requiredLocalAuthentication = false; + + MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_IDP, idpEntity.getEntityID()); + + + } else { + Logger.warn("Requested IDP " + pendingReq.getRequestedIDP() + + " does not support POST or Redirect Binding."); + + } + + } else { + Logger.warn("Requested IDP " + pendingReq.getRequestedIDP() + + " is not found in InterFederation configuration"); + + } + + } catch (MetadataProviderException e) { + Logger.error("IDP metadata error." , e); + + } catch (NoSuchAlgorithmException e) { + Logger.error("Build IDP authentication request FAILED.", e); + + } catch (MessageEncodingException e) { + Logger.error("Build IDP authentication request FAILED.", e); + + } catch (SecurityException e) { + Logger.error("Build IDP authentication request FAILED.", e); + + } catch (PVP2Exception e) { + Logger.error("Build IDP authentication request FAILED.", e); + + } catch (ConfigurationException e1) { + Logger.error("Build IDP authentication request FAILED.", e1); + + } + + //set flag for next step + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, + requiredLocalAuthentication); + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java index 28bed7713..8add03da7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java @@ -97,7 +97,7 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { Logger.info("AuthProcess finished. Redirect to Protocol Dispatcher."); String redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingReq.getRequestID()), newMOASessionID); + ModulUtils.buildAuthURL(pendingReq.requestedModule(), pendingReq.requestedAction(), pendingReq.getRequestID()), newMOASessionID); response.setContentType("text/html"); response.setStatus(302); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java deleted file mode 100644 index 215a7a809..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java +++ /dev/null @@ -1,191 +0,0 @@ -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.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 = AuthenticationServer.getInstance().getIdentityLink(signature);
-
- if (null != response.getErrorResponse()) {
- // TODO fix exception parameter
- throw new SZRGWClientException("service.08", (String) response.getErrorResponse().getErrorCode(),
- (String) response.getErrorResponse().getInfo());
- } else {
- IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream(
- response.getIdentityLink()));
- IdentityLink identitylink = ilParser.parseIdentityLink();
- session.setIdentityLink(identitylink);
-
- // set QAA Level four in case of card authentifcation
- session.setQAALevel(PVPConstants.STORK_QAA_1_4);
-
- AuthenticationServer.getInstance().getForeignAuthenticationData(session);
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session);
-
- Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID);
- Logger.info("Daten angelegt zu MOASession " + newMOASessionID);
-
- 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java deleted file mode 100644 index 4951dcab8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java +++ /dev/null @@ -1,184 +0,0 @@ -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.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.MISMandate;
-import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.DOMUtils;
-
-/**
- * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java deleted file mode 100644 index 4dcd48f57..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java +++ /dev/null @@ -1,101 +0,0 @@ -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.ParamValidatorUtils;
-import at.gv.egovernment.moa.id.util.ServletUtils;
-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);
-
- ServletUtils.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java deleted file mode 100644 index 099bc085c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.auth.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20OANotSupportedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java index 0edeb89bc..f05ff07e9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20OANotSupportedException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java @@ -20,25 +20,34 @@ * 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; +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +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; /** * @author tlenz * */ -public class OAuth20OANotSupportedException extends OAuth20Exception { - - private static final long serialVersionUID = -8713091674236329339L; +public class ReceiveInterfederationResponseTask extends AbstractAuthServletTask { - /** - * @param errorCode - * @param messageId - * @param parameters + /* (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) */ - public OAuth20OANotSupportedException() { - super(OAuth20Constants.ERROR_SERVER_ERROR, "oauth20.06", new Object[] {}); + @Override + public void execute(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + + //TODO: validate SAML2 assertion + //TODO: move attributeQuery from AuthenticationDataBuilder to her + //TODO: add SAML2 interfederation Response to MOASession + //TODO: update AuthenticationDataBuilder to use Response from MOASession if exists + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java deleted file mode 100644 index da464ba68..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java +++ /dev/null @@ -1,160 +0,0 @@ -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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java deleted file mode 100644 index 5e0be0f2c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java +++ /dev/null @@ -1,174 +0,0 @@ -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.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"
- ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate");
-
- }
- else {
-
- String countrycode = CertificateUtils.getIssuerCountry(cert);
- if (countrycode != null) {
- if (countrycode.compareToIgnoreCase("AT") == 0) {
- Logger.error("Certificate issuer country code is \"AT\". Login not support in foreign identities mode.");
- throw new AuthenticationException("auth.22", null);
- }
- }
-
- // Foreign Identities Modus
- 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"
- ServletUtils.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java deleted file mode 100644 index f0a0024e5..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java +++ /dev/null @@ -1,111 +0,0 @@ -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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java deleted file mode 100644 index b39cf9e9b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/CreateXMLSignatureResponseParser.java +++ /dev/null @@ -1,285 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><InfoboxReadResponse></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><CreateXMLSignatureResponse></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><InfoboxReadResponse></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><InfoboxReadResponse></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><CreateXMLSignatureResponse></code> object. - * - * @return a <code><CreateXMLSignatureResponse></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><CreateXMLSignatureResponse></code> object. - * - * @return a <code><CreateXMLSignatureResponse></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/ErrorResponseParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/ErrorResponseParser.java deleted file mode 100644 index a09f0a2a8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/ErrorResponseParser.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><ErrorResponse></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><Unklassifizierter Fehler.></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/ExtendedInfoboxReadResponseParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/ExtendedInfoboxReadResponseParser.java deleted file mode 100644 index 390467bf8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/ExtendedInfoboxReadResponseParser.java +++ /dev/null @@ -1,203 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><PushInfobox></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><XMLContent></code> or - * <code><Base64Content></code> child of the given element to a list of - * infobox token. - * - * @param contentParent The elment including the <code><XMLContent></code> or - * <code><Base64Content></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><XMLContent></code> - * or <code><Base64Content></code> child or the - * <code><XMLContent></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java deleted file mode 100644 index 28ce69e95..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/InfoboxReadResponseParser.java +++ /dev/null @@ -1,274 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><InfoboxReadResponse></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><InfoboxReadResponse></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><InfoboxReadResponse></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><saml:Assertion></code> element from <code><InfoboxReadResponse></code> - * @return <code><saml:Assertion></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><saml:Assertion></code> element from <code><InfoboxReadResponse></code> - * @return <code><saml:Assertion></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><saml:Assertion></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><saml:Assertion></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParser.java deleted file mode 100644 index 0e0b42cde..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/SAMLArtifactParser.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java index 8a536ca77..e659c9447 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java @@ -38,7 +38,7 @@ 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.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.FileUtils; @@ -126,42 +126,51 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ // get target and target friendly name from config String targetConfig = oaParam.getTarget(); String targetFriendlyNameConfig = oaParam.getTargetFriendlyName(); - - if (StringUtils.isEmpty(targetConfig) - || (module.equals(SAML1Protocol.PATH) && - !StringUtils.isEmpty(target)) - ) { - //INFO: ONLY SAML1 legacy mode - // if SAML1 is used and target attribute is given in request - // use requested target - // check target parameter - if (!ParamValidatorUtils.isValidTarget(target)) { - Logger.error("Selected target is invalid. Using target: " + target); - throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12"); - } - if (MiscUtil.isNotEmpty(targetConfig)) - targetFriendlyName = targetFriendlyNameConfig; - - else { - String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(target); - if (MiscUtil.isNotEmpty(sectorName)) - targetFriendlyName = sectorName; + + if (!oaParam.getBusinessService()) { + if (StringUtils.isEmpty(targetConfig) + || (module.equals("id_saml1") && + !StringUtils.isEmpty(target)) + ) { + //INFO: ONLY SAML1 legacy mode + // if SAML1 is used and target attribute is given in request + // use requested target + // check target parameter + if (!ParamValidatorUtils.isValidTarget(target)) { + Logger.error("Selected target is invalid. Using target: " + target); + throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12"); + } + if (MiscUtil.isNotEmpty(targetConfig)) + targetFriendlyName = targetFriendlyNameConfig; else { - //check target contains subSector - int delimiter = target.indexOf("-"); - if (delimiter > 0) { - targetFriendlyName = - TargetToSectorNameMapper.getSectorNameViaTarget(target.substring(0, delimiter)); - - } - } + String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(target); + if (MiscUtil.isNotEmpty(sectorName)) + targetFriendlyName = sectorName; + + else { + //check target contains subSector + int delimiter = target.indexOf("-"); + if (delimiter > 0) { + targetFriendlyName = + TargetToSectorNameMapper.getSectorNameViaTarget(target.substring(0, delimiter)); + + } + } + } + + } else { + // use target from config + target = targetConfig; + targetFriendlyName = targetFriendlyNameConfig; } - + moasession.setTarget(target); + moasession.setTargetFriendlyName(targetFriendlyName); + } else { - // use target from config - target = targetConfig; - targetFriendlyName = targetFriendlyNameConfig; + Logger.debug("Business: " + moasession.getBusinessService() + " stork: " + moasession.getStorkService()); + moasession.setDomainIdentifier(oaParam.getIdentityLinkDomainIdentifier()); + } @@ -205,13 +214,9 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ } moasession.setPublicOAURLPrefix(oaParam.getPublicURLPrefix()); - - moasession.setTarget(target); moasession.setBusinessService(oaParam.getBusinessService()); + //moasession.setStorkService(oaParam.getStorkService()); - Logger.debug("Business: " + moasession.getBusinessService() + " stork: " + moasession.getStorkService()); - moasession.setTargetFriendlyName(targetFriendlyName); - moasession.setDomainIdentifier(oaParam.getIdentityLinkDomainIdentifier()); } //check OnlineApplicationURL @@ -271,7 +276,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ } - public static void parse(HttpServletRequest req, HttpServletResponse resp, + public static void parse(ExecutionContext ec, HttpServletRequest req, AuthenticationSession moasession, IRequest request) throws WrongParametersException, MOAIDException { @@ -280,23 +285,23 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ modul = StringEscapeUtils.escapeHtml(modul); action = StringEscapeUtils.escapeHtml(action); - if(modul == null) { - modul = SAML1Protocol.PATH; - } - - if(action == null) { - action = SAML1Protocol.GETARTIFACT; - } +// if(modul == null) { +// modul = SAML1Protocol.PATH; +// } +// +// if(action == null) { +// action = SAML1Protocol.GETARTIFACT; +// } moasession.setModul(modul); moasession.setAction(action); //get Parameters from request - String target = req.getParameter(PARAM_TARGET); - String oaURL = req.getParameter(PARAM_OA); - String bkuURL = req.getParameter(PARAM_BKU); - String templateURL = req.getParameter(PARAM_TEMPLATE); - String useMandate = req.getParameter(PARAM_USEMANDATE); - String ccc = req.getParameter(PARAM_CCC); + String target = (String) ec.get(PARAM_TARGET); + String oaURL = (String) ec.get(PARAM_OA); + String bkuURL = (String) ec.get(PARAM_BKU); + String templateURL = (String) ec.get(PARAM_TEMPLATE); + String useMandate = (String) ec.get(PARAM_USEMANDATE); + String ccc = (String) ec.get(PARAM_CCC); if (request.getOnlineApplicationConfiguration() != null && request.getOnlineApplicationConfiguration().isOnlyMandateAllowed()) { @@ -305,8 +310,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ useMandate = String.valueOf(request.getOnlineApplicationConfiguration().isOnlyMandateAllowed()); } - - + oaURL = request.getOAURL(); target = request.getTarget(); @@ -324,4 +328,5 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ private static boolean isEmpty(String param) { return param == null || param.length() == 0; } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java deleted file mode 100644 index 7bce406e0..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><VerifyXMLSignatureResponse></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><InfoboxReadResponse></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><InfoboxReadResponse></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><InfoboxReadResponse></code> as Element - */ - public VerifyXMLSignatureResponseParser(Element xmlResponse) - { - verifyXMLSignatureResponse =xmlResponse; - - } - - /** - * Parse identity link from <code><InfoboxReadResponse></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index ef5eaf5b9..2a63968dd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -23,7 +23,9 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; +import java.util.Enumeration; import java.util.List; +import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -47,10 +49,8 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestStorage; -import at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol; import at.gv.egovernment.moa.id.process.ExecutionContextImpl; -import at.gv.egovernment.moa.id.process.ProcessInstance; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; @@ -68,27 +68,13 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { String pendingRequestID = null; try { - String bkuid = req.getParameter(MOAIDAuthConstants.PARAM_BKU); - String useMandate = req.getParameter(MOAIDAuthConstants.PARAM_USEMANDATE); - String ccc = req.getParameter(MOAIDAuthConstants.PARAM_CCC); - String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); - - moasessionid = StringEscapeUtils.escapeHtml(moasessionid); - - AuthenticationSession moasession = null; - - 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[] {}); - } - + String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); + moasessionid = StringEscapeUtils.escapeHtml(moasessionid); + AuthenticationSession moasession = null; try { - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); - + pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); moasession = AuthenticationSessionStoreage.getSession(moasessionid); - -// AuthenticationSessionStoreage.changeSessionID(moasession); - + } catch (MOADatabaseException e) { Logger.info("MOASession with SessionID="+ moasessionid + " is not found in Database"); throw new MOAIDException("init.04", new Object[] { @@ -99,90 +85,36 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { throw new MOAIDException("auth.18", new Object[] {}); } - //load OA Config - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(moasession.getOAURLRequested()); - - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { moasession.getOAURLRequested() }); - - else { - - //get Target from config or from request in case of SAML 1 - String target = null; - 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}); - - } - - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUTYPE_SELECTED, bkuid); - - if (MiscUtil.isNotEmpty(pendingReq.getTarget()) && - pendingReq.requestedModule().equals(SAML1Protocol.PATH)) - target = pendingReq.getTarget(); - else - target = oaParam.getTarget(); - - String bkuURL = oaParam.getBKUURL(bkuid); - if (MiscUtil.isEmpty(bkuURL)) { - Logger.info("No OA specific BKU defined. Use BKU from default configuration"); - 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(), - req, - pendingReq); - } + ExecutionContext ec = new ExecutionContextImpl(); - // set execution context - ec.put("ccc", moasession.getCcc()); - ec.put("useMandate", moasession.getUseMandate()); - ec.put("bkuURL", moasession.getBkuURL()); + // set execution context + Enumeration<String> reqParamNames = req.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (MiscUtil.isNotEmpty(paramName)) + ec.put(paramName, req.getParameter(paramName)); + + } + ec.put("pendingRequestID", pendingRequestID); - + ec.put(MOAIDAuthConstants.PARAM_SESSIONID, moasessionid); + +// String bkuid = req.getParameter(MOAIDAuthConstants.PARAM_BKU); +// String useMandate = req.getParameter(MOAIDAuthConstants.PARAM_USEMANDATE); +// String ccc = req.getParameter(MOAIDAuthConstants.PARAM_CCC); +// ec.put("ccc", moasession.getCcc()); +// ec.put("useMandate", moasession.getUseMandate()); +// ec.put("bkuURL", moasession.getBkuURL()); + // select and create process instance String processDefinitionId = ModuleRegistration.getInstance().selectProcess(ec); - String processInstanceId = getProcessEngine().createProcessInstance(processDefinitionId, ec); - if (processDefinitionId == null) { Logger.warn("No suitable process found for SessionID " + moasession.getSessionID()); throw new MOAIDException("process.02", new Object[] { moasession.getSessionID() }); - } + } + + String processInstanceId = getProcessEngine().createProcessInstance(processDefinitionId, ec); // keep process instance id in moa session moasession.setProcessInstanceId(processInstanceId); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java index ee995e16b..f3e3ae8a4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java @@ -7,20 +7,16 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
-import org.slf4j.MDC;
import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils;
-import at.gv.egovernment.moa.id.auth.AuthenticationServer;
+import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions;
import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
-import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils;
import at.gv.egovernment.moa.id.moduls.IRequest;
import at.gv.egovernment.moa.id.moduls.RequestStorage;
import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
import at.gv.egovernment.moa.logging.Logger;
/**
@@ -81,7 +77,7 @@ public class ProcessEngineSignalServlet extends AuthServlet { }
AuthenticationSessionExtensions extendedSessionInformation = AuthenticationSessionStoreage.getAuthenticationSessionExtensions(sessionID);
- AuthenticationSession session = AuthenticationServer.getSession(sessionID);
+ AuthenticationSession session = BaseAuthenticationServer.getSession(sessionID);
//add transactionID and unique sessionID to Logger
if (extendedSessionInformation != null)
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/UnsupportedAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java index 31b9c9c0a..62ee1ed85 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/UnsupportedAttributeException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * 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. @@ -19,11 +19,22 @@ * 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; + */ +package at.gv.egovernment.moa.id.auth.servlet; -public class UnsupportedAttributeException extends Exception { +/** + * @author tlenz + * + */ + +public class SAML2InterfederationSignalServlet extends + ProcessEngineSignalServlet { - private static final long serialVersionUID = -7720066381435378111L; + private static final long serialVersionUID = 8208970012249149156L; + + //TODO: getMOASessionID from SAML2 relayState + //TODO: add WebService EndPoints for pvp2/sp/post and redirect + //TODO: implement SAML2 preprocessing + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java index 600ef2c76..064431a6b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java @@ -133,8 +133,8 @@ public class SSOSendAssertionServlet extends AuthServlet{ AuthenticationSessionStoreage.setAuthenticated(moaSessionID, true); //log event - String pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); - IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID); + //String pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); + IRequest pendingReq = RequestStorage.getPendingRequest(id); MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_FINISHED); String redirectURL = new DataURLBuilder().buildDataURL(moasession.getAuthURL(), @@ -143,6 +143,7 @@ public class SSOSendAssertionServlet extends AuthServlet{ resp.setContentType("text/html"); resp.setStatus(302); + resp.addHeader("Location", redirectURL); Logger.debug("REDIRECT TO: " + redirectURL); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/AssertionVerifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/AssertionVerifier.java deleted file mode 100644 index ca15cb120..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/AssertionVerifier.java +++ /dev/null @@ -1,78 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * Copyright 2011 by Graz University of Technology, Austria
- * The Austrian STORK Modules have been developed by the E-Government
- * Innovation Center EGIZ, a joint initiative of the Federal Chancellery
- * Austria 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.util.List;
-
-import org.opensaml.saml2.core.Assertion;
-import org.opensaml.saml2.metadata.RequestedAttribute;
-
-/**
- * Interface to be implemented for verifying SAML assertions
- *
- * @author bzwattendorfer
- *
- */
-public interface AssertionVerifier {
-
- /**
- * Verifies a given assertion
- * @param assertion SAML assertion
- * @param reqIPAddress IP address of the client
- * @param authnRequestID ID of the corresponding authentication request for verification
- * @param recipient recipient for verification
- * @param audience audience for verification
- * @param reqAttrList RequestedAttribute list for verification
- * @throws SecurityException
- */
- public void verify(Assertion assertion, String reqIPAddress, String authnRequestID, String recipient, String audience, List<RequestedAttribute> reqAttrList) throws SecurityException;
-
-}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java deleted file mode 100644 index a91e1bc5a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java +++ /dev/null @@ -1,64 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/**
- *
- */
-package at.gv.egovernment.moa.id.auth.stork;
-
-
-/**
- * Exception thrown if error occurs in STORK processing
- * @author bzwattendorfer
- *
- */
-public class STORKException extends Exception{
-
- /**
- *
- */
- private static final long serialVersionUID = 1L;
-
- public STORKException() {
- super();
-
- }
-
- public STORKException(String message, Throwable cause) {
- super(message, cause);
-
- }
-
- public STORKException(String message) {
- super(message);
-
- }
-
- public STORKException(Throwable cause) {
- super(cause);
-
- }
-
-
-
-
-}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java deleted file mode 100644 index 3809ec4bc..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java +++ /dev/null @@ -1,323 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/**
- *
- */
-package at.gv.egovernment.moa.id.auth.stork;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-import java.util.Vector;
-
-import javax.activation.DataSource;
-import javax.xml.transform.Source;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactoryConfigurationError;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.StringEscapeUtils;
-
-import at.gv.egovernment.moa.id.auth.AuthenticationServer;
-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.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 = AuthenticationServer.getInstance().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 = AuthenticationServer.getInstance().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 = AuthenticationServer.getInstance().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 = AuthenticationServer.getInstance().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 = AuthenticationServer.getInstance().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;
-
- }
-
-
- /**
- * 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;
- }
-
- 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java deleted file mode 100644 index d70cd6f50..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java +++ /dev/null @@ -1,671 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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 ' - issuer = issuer.replaceAll("'", "'"); - - 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("'", "'"); - - 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 ' - issuer = issuer.replaceAll("'", "'"); - - 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("'", "'"); - - 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java deleted file mode 100644 index fa6486afe..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java +++ /dev/null @@ -1,209 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/InfoboxValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/InfoboxValidator.java deleted file mode 100644 index e6e2539c9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/InfoboxValidator.java +++ /dev/null @@ -1,128 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java deleted file mode 100644 index ac528c89d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java +++ /dev/null @@ -1,303 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><VerifyXMLSignatureResponse></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/ParepUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/ParepUtils.java deleted file mode 100644 index 0e2251f21..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/ParepUtils.java +++ /dev/null @@ -1,762 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateIdentityLinkResponse.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateIdentityLinkResponse.java deleted file mode 100644 index fca0b2dce..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateIdentityLinkResponse.java +++ /dev/null @@ -1,84 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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 org.w3c.dom.Element;
-
-
-/**
- * This class implements a SZR-gateway GetIdentityLink Response.
- *
- */
-public class CreateIdentityLinkResponse {
-
- private Element assertion;
- private String error;
- private boolean isError;
-
- public Element getAssertion() {
- return assertion;
- }
- public String getError() {
- return error;
- }
-
- public void setAssertion(Element assertion) {
- isError = false;
- this.assertion = assertion;
- }
- public void setError(String error) {
- isError = true;
- this.error = error;
- }
-
- public boolean isError() {
- return isError;
- }
-
-
-}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateMandateResponse.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateMandateResponse.java deleted file mode 100644 index e6b7dee34..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/CreateMandateResponse.java +++ /dev/null @@ -1,181 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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 org.apache.xpath.XPathAPI;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-
-/**
- * This class implements a SZR-gateway CreateMandate Response.
- *
- * @author <a href="mailto:peter.danner@egiz.gv.at">Peter Danner</a>
- */
-public class CreateMandateResponse {
-
- /**
- * Result code of the request.
- */
- private int resultCode;
-
- /**
- * Description of the result.
- */
- private String resultInfo;
-
- /**
- * The returned mandate.
- */
- private Element mandate;
-
- /**
- * @return the resultCode
- */
- public int getResultCode() {
- return resultCode;
- }
-
- /**
- * @param resultCode the resultCode to set
- */
- public void setResultCode(String resultCode) {
- if (resultCode!=null) {
- this.resultCode = Integer.parseInt(resultCode);
- } else {
- this.resultCode = 0;
- }
- }
-
- /**
- * @return the resultInfo
- */
- public String getInfo() {
- return resultInfo;
- }
-
- /**
- * @param resultInfo the resultInfo to set
- */
- public void setInfo(String resultInfo) {
- this.resultInfo = resultInfo;
- }
-
- /**
- * @return the mandate
- */
- public Element getMandate() {
- return mandate;
- }
-
- /**
- * @param mandate the mandate to set
- */
- public void setMandate(Element mandate) {
- this.mandate = mandate;
- }
-
-
- /**
- * Parses the SZR-gateway response.
- *
- * @param response the SZR-gateway response.
- * @throws SZRGWClientException if an error occurs.
- */
- public void parse(Element response) throws SZRGWClientException {
- try {
-
- // first check if response is a soap error
- NodeList list = response.getElementsByTagName("faultstring");
- if (list.getLength() > 0) {
- String faultCode = "";
- String faultString = "";
- Element snameSpaceNode = response.getOwnerDocument().createElement("NameSpaceNode");
- snameSpaceNode.setAttribute("xmlns" + SOAPConstants.SOAP_ENV_POSTFIX, SOAPConstants.SOAP_ENV_NS);
- Node faultCodeNode = XPathAPI.selectSingleNode(response, SOAPConstants.XPATH_SOAP_FAULTCODE, snameSpaceNode);
- Node faultStringNode = XPathAPI.selectSingleNode(response, SOAPConstants.XPATH_SOAP_FAULTSTRING, snameSpaceNode);
- if (faultCodeNode!=null) faultCode = faultCodeNode.getNodeValue();
- if (faultStringNode!=null) faultString = faultStringNode.getNodeValue();
- throw new SZRGWClientException("Fehler bei SZR-Gateway (SOAP-Error " + faultCode + "): " + faultString);
- }
-
- this.mandate = null;
- this.resultCode = 2000;
- this.resultInfo = null;
- // parse single SZR-gateway results
- Element nameSpaceNode = response.getOwnerDocument().createElement("NameSpaceNode");
- nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.SZRGW_POSTFIX, SZRGWConstants.SZRGW_REQUEST_NS);
- nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX, SZRGWConstants.MANDATE_NS);
- Node mandateNode = XPathAPI.selectSingleNode(response, "//" + SZRGWConstants.SZRGW_PREFIX + SZRGWConstants.CREATE_MANDATE_RESPONSE + "/" + SZRGWConstants.MANDATE_PREFIX + SZRGWConstants.MANDATE, nameSpaceNode);
- if (mandateNode!=null) {
- this.mandate = (Element) mandateNode;
- } else {
- String errorResponse = "//" + SZRGWConstants.SZRGW_PREFIX + SZRGWConstants.CREATE_MANDATE_RESPONSE + "/" + SZRGWConstants.SZRGW_PREFIX + SZRGWConstants.ERROR_RESPONSE + "/";
- Node errorCode = XPathAPI.selectSingleNode(response, errorResponse + SZRGWConstants.SZRGW_PREFIX + "ErrorCode/text()", nameSpaceNode);
- if (errorCode!=null) setResultCode(errorCode.getNodeValue());
- Node errorInfo = XPathAPI.selectSingleNode(response, errorResponse + SZRGWConstants.SZRGW_PREFIX + "Info/text()", nameSpaceNode);
- this.setInfo(errorInfo.getNodeValue());
- }
- } catch(Exception e) {
- e.printStackTrace();
- throw new SZRGWClientException(e);
- }
- }
-
- public static void main(String[] args) throws Exception {
-// CreateMandateResponse resp = new CreateMandateResponse();
-// Document doc = ParepUtils.readDocFromIs(new FileInputStream("c:/response2.xml"));
-// Element response = doc.getDocumentElement();
-// resp.parse(response);
-// System.out.println(resp.getResultCode());
-// System.out.println(resp.getInfo());
-// if (resp.getMandate()!=null) ParepUtils.serializeElement(resp.getMandate(), System.out);
- }
-
-}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SOAPConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SOAPConstants.java deleted file mode 100644 index 0313814b1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SOAPConstants.java +++ /dev/null @@ -1,78 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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;
-
-
-/**
- * SOAP Envelope Constants.
- *
- * @author <a href="mailto:arne.tauber@egiz.gv.at">Arne Tauber</a>
- * @version $ $
- **/
-public interface SOAPConstants {
-
- /*
- * Namespaces and namespace prefixes for SOAP message handling
- */
- public static final String SOAP_ENV_NS = "http://schemas.xmlsoap.org/soap/envelope/";
- public static final String SOAP_ENV_ENCODING_STYLE = "http://schemas.xmlsoap.org/soap/encoding/";
- public static final String SOAP_ENV_PREFIX = "soapenv:";
- public static final String SOAP_ENV_POSTFIX = ":soapenv";
-
- public static final String ENVELOPE = "Envelope";
- public static final String BODY = "Body";
- public static final String FAULT = "Fault";
- public static final String ENCODING_STYLE = "encodingStyle";
-
- public static final String XPATH_SOAP_FAULT = "/" + SOAP_ENV_PREFIX + ENVELOPE + "/" + SOAP_ENV_PREFIX + BODY + "/" + SOAP_ENV_PREFIX + FAULT;
- public static final String XPATH_SOAP_FAULTCODE = XPATH_SOAP_FAULT + "/faultcode/text()";
- public static final String XPATH_SOAP_FAULTSTRING = XPATH_SOAP_FAULT + "/faultstring/text()";
-
-
-
-}
-
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java deleted file mode 100644 index 61b26b59a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClient.java +++ /dev/null @@ -1,389 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-
-import javax.net.ssl.SSLSocketFactory;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.protocol.Protocol;
-import org.apache.xpath.XPathAPI;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-
-import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils;
-import at.gv.egovernment.moa.id.commons.utils.HttpClientWithProxySupport;
-import at.gv.egovernment.moa.util.Constants;
-import at.gv.egovernment.moa.util.DOMUtils;
-
-
-
-/**
- * This class implements a client for communication with the SZR-gateway
- * <p>
- * Two types of requests are supported
- * <ol>
- * <li>Basic Request</li>
- * <li>Detailed Request</li>
- * </ol>
- *
- * @author <a href="mailto:peter.danner@egiz.gv.at">Peter Danner</a>
- */
-public class SZRGWClient {
- /**
- * The URL of the SZR-gateway webservice.
- */
- private String address;
-
- /**
- * The SSL socket factory when using a secure connection.
- */
- private SSLSocketFactory sSLSocketFactory;
-
- /**
- * Constructor
- */
- public SZRGWClient() {
- }
-
- /**
- * Constructor
- *
- * @param address the URL of the SZR-gateway webservice.
- */
- public SZRGWClient(String address) {
- this.address = address;
- }
- /**
- * Sets the SSL socket factory.
- *
- * @param factory the SSL socket factory.
- */
- public void setSSLSocketFactory(SSLSocketFactory factory) {
- this.sSLSocketFactory = factory;
- }
-
- /**
- * Sets the SZR webservice URL
- *
- * @param address the URL of the SZR-gateway webservice.
- */
- public void setAddress(String address) {
- this.address = address;
- }
-
- /**
- * Creates a mandate.
- *
- * @param reqElem the request.
- * @return a SZR-gateway response containing the result
- * @throws SZRGWException when an error occurs creating the mandate.
- */
- public CreateMandateResponse createMandateResponse(Element reqElem) throws SZRGWClientException {
- //Logger.info("Connecting to SZR-gateway.");
- try {
- if (address == null) {
- throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null.");
- }
- HttpClient client = HttpClientWithProxySupport.getHttpClient();
- PostMethod method = new PostMethod(address);
- method.setRequestHeader("SOAPAction", "");
-
-
- // ssl settings
- if (sSLSocketFactory != null) {
- SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory);
- Protocol.registerProtocol("https", new Protocol("https", fac, 443));
- }
-
- // create soap body
- Element soapBody = getSOAPBody();
- Document doc = soapBody.getOwnerDocument();
- soapBody.appendChild(doc.importNode(reqElem, true));
- Element requestElement = soapBody.getOwnerDocument().getDocumentElement();
-
- //ParepUtils.saveElementToFile(requestElement, new File("c:/temp/szrRequest.xml"));
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ParepUtils.serializeElementAsDocument(requestElement, bos);
-
- method.setRequestBody(new ByteArrayInputStream(bos.toByteArray()));
- client.executeMethod(method);
- CreateMandateResponse response = new CreateMandateResponse();
-
- bos = new ByteArrayOutputStream();
- doc = ParepUtils.readDocFromIs(method.getResponseBodyAsStream());
-
- //ParepUtils.saveElementToFile(doc.getDocumentElement(), new File("c:/temp/szrResponse.xml"));
- response.parse(doc.getDocumentElement());
-
-
- return response;
- } catch(Exception e) {
- //e.printStackTrace();
- throw new SZRGWClientException(e);
- }
- }
-
- /**
- * Gets a identity link.
- *
- * @param reqElem the request.
- * @return a SZR-gateway response containing the result
- * @throws SZRGWException when an error occurs creating the mandate.
- */
- public CreateIdentityLinkResponse createIdentityLinkResponse(Element reqElem) throws SZRGWClientException {
-
- try {
- if (address == null) {
- throw new NullPointerException("Address (SZR-gateway ServiceURL) must not be null.");
- }
- HttpClient client = new HttpClient();
- PostMethod method = new PostMethod(address);
- method.setRequestHeader("SOAPAction", "");
-
-
- // ssl settings
- if (sSLSocketFactory != null) {
- SZRGWSecureSocketFactory fac = new SZRGWSecureSocketFactory(sSLSocketFactory);
- Protocol.registerProtocol("https", new Protocol("https", fac, 443));
- }
-
- // create soap body
- Element soapBody = getSOAPBody();
- Document doc = soapBody.getOwnerDocument();
- soapBody.appendChild(doc.importNode(reqElem, true));
- Element requestElement = soapBody.getOwnerDocument().getDocumentElement();
-
- //ParepUtils.saveElementToFile(requestElement, new File("c:/temp/szrRequest.xml"));
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ParepUtils.serializeElementAsDocument(requestElement, bos);
-
- method.setRequestBody(new ByteArrayInputStream(bos.toByteArray()));
- client.executeMethod(method);
- CreateIdentityLinkResponse response = new CreateIdentityLinkResponse();
-
- bos = new ByteArrayOutputStream();
- doc = ParepUtils.readDocFromIs(method.getResponseBodyAsStream());
- //ParepUtils.saveElementToFile(doc.getDocumentElement(), new File("c:/temp/szrResponse.xml"));
-
- NodeList list = doc.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "ErrorResponse");
- if (list.getLength() > 0) {
- // set error response
- list = doc.getElementsByTagNameNS(SZRGWConstants.SZRGW_REQUEST_NS, "Info");
- String error = DOMUtils.getText(list.item(0));
-
- response.setError(error);
- }
- else {
- // set assertion
- DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
- Document newdoc = builder.newDocument();
-
- Element nameSpaceNode = newdoc.createElement("NameSpaceNode");
- nameSpaceNode.setAttribute("xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI);
- nameSpaceNode.setAttribute("xmlns:" + Constants.SAML_PREFIX, Constants.SAML_NS_URI);
-
- Element samlAssertion = (Element)XPathAPI.selectSingleNode(doc, "//saml:Assertion[1]", nameSpaceNode);
-
- if (samlAssertion == null)
- throw new SZRGWClientException("Could not found a saml:Assertion element in response.");
- else
- response.setAssertion(samlAssertion);
- }
-
- return response;
-
- } catch(Exception e) {
- throw new SZRGWClientException(e);
- }
- }
-
-
- /*
- * builds an XML soap envelope
- */
- private Element getSOAPBody() throws SZRGWClientException {
- Document doc_;
- try {
- doc_ = ParepUtils.createEmptyDocument();
- Element root = doc_.createElementNS(SOAPConstants.SOAP_ENV_NS, SOAPConstants.SOAP_ENV_PREFIX + SOAPConstants.ENVELOPE);
- doc_.appendChild(root);
-
- root.setAttribute("xmlns" + SOAPConstants.SOAP_ENV_POSTFIX, SOAPConstants.SOAP_ENV_NS);
- //root.setAttribute(SOAPConstants.SOAP_ENV_PREFIX + SOAPConstants.ENCODING_STYLE, SOAPConstants.SOAP_ENV_ENCODING_STYLE);
- root.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
- root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
-
- Element body = doc_.createElementNS(SOAPConstants.SOAP_ENV_NS, SOAPConstants.SOAP_ENV_PREFIX + SOAPConstants.BODY);
- root.appendChild(body);
-
- return body;
- } catch (SZRGWClientException e) {
- throw new SZRGWClientException(e);
- }
-
- }
-
- public Document buildGetIdentityLinkRequest(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature, String representative, String represented, String mandateContent) throws SZRGWClientException { - - String SZRGW_NS = "http://reference.e-government.gv.at/namespace/szrgw/20070807#";
- try {
- DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document doc = builder.newDocument();
-
- Element getIdentityLink = doc.createElementNS(SZRGW_NS, "szrgw:GetIdentityLinkRequest");
- getIdentityLink.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:szrgw", SZRGW_NS);
- doc.appendChild(getIdentityLink);
-
- if ( (PEPSIdentifier != null) || (PEPSFirstname != null) || (PEPSFamilyname != null) || (PEPSDateOfBirth != null) ) {
-
- Element pepsDataElem = doc.createElementNS(SZRGW_NS, "szrgw:PEPSData");
- getIdentityLink.appendChild(pepsDataElem);
-
- if (PEPSIdentifier != null) {
- Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Identifier");
- pepsDataElem.appendChild(elem);
- Text text= doc.createTextNode(PEPSIdentifier);
- elem.appendChild(text);
- }
- if (PEPSFirstname != null) {
- Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Firstname");
- pepsDataElem.appendChild(elem);
- Text text= doc.createTextNode(PEPSFirstname);
- elem.appendChild(text);
- }
-
- if (PEPSFamilyname != null) {
- Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Familyname");
- pepsDataElem.appendChild(elem);
- Text text= doc.createTextNode(PEPSFamilyname);
- elem.appendChild(text);
- }
-
- if (PEPSDateOfBirth != null) {
- Element elem = doc.createElementNS(SZRGW_NS, "szrgw:DateOfBirth");
- pepsDataElem.appendChild(elem);
- Text text= doc.createTextNode(PEPSDateOfBirth);
- elem.appendChild(text);
- }
-
- if (representative != null) { - Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Representative"); - pepsDataElem.appendChild(elem);
- Text text= doc.createTextNode(representative); - elem.appendChild(text);
- } -
- if (represented != null) { - Element elem = doc.createElementNS(SZRGW_NS, "szrgw:Represented"); - pepsDataElem.appendChild(elem);
- Text text= doc.createTextNode(represented); - elem.appendChild(text);
- }
-
- if (mandateContent != null) { - Element elem = doc.createElementNS(SZRGW_NS, "szrgw:MandateContent"); - pepsDataElem.appendChild(elem);
- Text text= doc.createTextNode(mandateContent); - elem.appendChild(text);
- }
- }
-
- if (signature == null)
- throw new SZRGWClientException("Signature element must not be null!");
- else {
- Element sig = doc.createElementNS(SZRGW_NS, "szrgw:Signature");
- Element base64content = doc.createElementNS(SZRGW_NS, "szrgw:Base64Content");
- sig.appendChild(base64content);
- getIdentityLink.appendChild(sig);
- Text text= doc.createTextNode(signature);
- base64content.appendChild(text);
- }
- - if(representative != null && represented != null && mandateContent != null) { - Element mis = doc.createElementNS(SZRGW_NS, "szrgw:MIS"); - Element filters = doc.createElementNS(SZRGW_NS, "szrgw:Filters"); - mis.appendChild(filters); - Element target = doc.createElementNS(SZRGW_NS, "szrgw:Target"); - mis.appendChild(target); - Element friendlyName = doc.createElementNS(SZRGW_NS, "szrgw:OAFriendlyName"); - mis.appendChild(friendlyName); - getIdentityLink.appendChild(mis); - -// TODO fetch data from oa params -// String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); -// moasessionid = StringEscapeUtils.escapeHtml(moasessionid); -// AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moasessionid); -// OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); -// if (oaParam == null) -// throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() }); -// Text text = doc.createTextNode(oaParam.getFriendlyName()); - } - - return doc;
- } catch (ParserConfigurationException e) {
- throw new SZRGWClientException(e);
- } /*catch (CertificateEncodingException e) {
- throw new SZRGWClientException(e);
- }*/
-
-
- }
-
-}
-
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClientException.java deleted file mode 100644 index 8e1f887f6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWClientException.java +++ /dev/null @@ -1,88 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWSecureSocketFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWSecureSocketFactory.java deleted file mode 100644 index fd16c1586..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/parep/client/szrgw/SZRGWSecureSocketFactory.java +++ /dev/null @@ -1,170 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/utils/SZRGWClientUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/utils/SZRGWClientUtils.java new file mode 100644 index 000000000..b0b2029ec --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/utils/SZRGWClientUtils.java @@ -0,0 +1,198 @@ +/* + * 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.client.utils; + +import java.io.UnsupportedEncodingException; +import java.util.List; +import java.util.UUID; + +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.client.SZRGWClient; +import at.gv.egovernment.moa.id.client.SZRGWClientException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +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.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import at.gv.util.xsd.mis.MandateIdentifiers; +import at.gv.util.xsd.mis.Target; +import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest; +import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; +import at.gv.util.xsd.srzgw.MISType; +import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest.PEPSData; +import at.gv.util.xsd.srzgw.MISType.Filters; + +/** + * @author tlenz + * + */ +public class SZRGWClientUtils { + + /** + * Does the request to the SZR-GW. + * + * @param signature the signature + * @return the identity link + * @throws SZRGWClientException the sZRGW client exception + * @throws ConfigurationException the configuration exception + */ + public static CreateIdentityLinkResponse getIdentityLink(Element signature) throws SZRGWClientException, ConfigurationException { + return getIdentityLink(null, null, null, null, XMLHelper.nodeToString(signature), null); + } + + /** + * Does the request to the SZR-GW. + * + * @param PEPSIdentifier the pEPS identifier + * @param PEPSFirstname the pEPS firstname + * @param PEPSFamilyname the pEPS familyname + * @param PEPSDateOfBirth the pEPS date of birth + * @param signature XMLDSIG signature + * @return Identity link assertion + * @throws SZRGWClientException the sZRGW client exception + * @throws ConfigurationException the configuration exception + */ + public static CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature, String PEPSFiscalNumber) throws SZRGWClientException { + return getIdentityLink(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null, PEPSFiscalNumber); + } + + /** + * SZR-GW Client interface. + * + * @param eIdentifier the e identifier + * @param givenName the given name + * @param lastName the last name + * @param dateOfBirth the date of birth + * @param citizenSignature the citizen signature + * @param representative the representative + * @param represented the represented + * @param mandate the mandate + * @return the identity link + * @throws SZRGWClientException the sZRGW client exception + */ + public static CreateIdentityLinkResponse getIdentityLink(String eIdentifier, + String givenName, String lastName, String dateOfBirth, String gender, + String citizenSignature, String representative, String represented, + String mandate, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { + return getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, gender, + citizenSignature, representative, represented, mandate, null, + null, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); + } + + /** + * Gets the identity link. + * + * @param citizenSignature the citizen signature + * @param representative the representative + * @param represented the represented + * @param mandate the mandate + * @param organizationAddress the organization address + * @param organizationType the organization type + * @return the identity link + * @throws SZRGWClientException + */ + public static CreateIdentityLinkResponse getIdentityLink(String citizenSignature, + String representative, String represented, String mandateContent, + String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { + return getIdentityLink(null, null, null, null, null, + citizenSignature, represented, representative, mandateContent, organizationAddress, + organizationType, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); + } + + public static CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String gender, String citizenSignature, String represented, String representative, String mandateContent, String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { + + try { + AuthConfiguration authConf = AuthConfigurationProviderFactory.getInstance(); + ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); + + String requestID = UUID.randomUUID().toString(); + SZRGWClient client = new SZRGWClient(connectionParameters); + + CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); + request.setSignature(citizenSignature.getBytes("UTF-8")); + request.setReqID(requestID); + if(PEPSDateOfBirth!=null || PEPSFamilyname!=null || PEPSFirstname!=null || PEPSIdentifier!=null || representative!=null || represented!=null || mandateContent!=null || organizationAddress!=null || organizationType!=null) + { + PEPSData data = new PEPSData(); + data.setDateOfBirth(PEPSDateOfBirth); + data.setFamilyname(PEPSFamilyname); + data.setFirstname(PEPSFirstname); + data.setIdentifier(PEPSIdentifier); + + data.setFiscalNumber(PEPSFiscalNumber); + + data.setRepresentative(representative); + data.setRepresented(represented); + data.setMandateContent(mandateContent); + + data.setLegalPersonCanonicalRegisteredAddress(organizationAddress); + data.setLegalPersonTranslatableType(organizationType); + + request.setPEPSData(data); + } + if (null != mandateContent) { + MISType mis = new MISType(); + + Target targetObject = new Target(); + targetObject.setType(targetType); + targetObject.setValue(targetValue); + mis.setTarget(targetObject); + + mis.setOAFriendlyName(oaFriendlyName); + + Filters filterObject = new Filters(); + MandateIdentifiers mandateIds = new MandateIdentifiers(); + for(String current : filters) + mandateIds.getMandateIdentifier().add(current.trim()); + filterObject.setMandateIdentifiers(mandateIds); + mis.setFilters(filterObject); + + request.setMIS(mis); + } + + if (MiscUtil.isEmpty(connectionParameters.getUrl())) { + Logger.warn("SZR-Gateway Service URL is empty"); + throw new SZRGWClientException("service.07"); + } + + Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); + CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request, connectionParameters.getUrl()); + return response; + + } + catch (ConfigurationException e) { + Logger.warn(e); + Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); + } catch (UnsupportedEncodingException e) { + Logger.warn(e); + } + + return null; + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java index 4da066e5b..47abf78db 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java @@ -35,7 +35,7 @@ public interface AuthConfiguration extends ConfigurationProvider{ public OAAuthParameter getOnlineApplicationParameter(String oaURL); - public String getMoaSpAuthBlockTrustProfileID() throws ConfigurationException; + public String getMoaSpAuthBlockTrustProfileID(boolean useTestTrustStore) throws ConfigurationException; public List<String> getMoaSpAuthBlockVerifyTransformsInfoIDs() throws ConfigurationException; @@ -44,8 +44,8 @@ public interface AuthConfiguration extends ConfigurationProvider{ public ConnectionParameter getForeignIDConnectionParameter() throws ConfigurationException; public ConnectionParameter getOnlineMandatesConnectionParameter() throws ConfigurationException; - - public String getMoaSpIdentityLinkTrustProfileID() throws ConfigurationException; + + public String getMoaSpIdentityLinkTrustProfileID(boolean useTestTrustStore) throws ConfigurationException; public List<String> getTransformsInfos() throws ConfigurationException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/ConfigurationToJSONConverter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/ConfigurationToJSONConverter.java deleted file mode 100644 index e1c1ac49e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/ConfigurationToJSONConverter.java +++ /dev/null @@ -1,155 +0,0 @@ -//package at.gv.egovernment.moa.id.config.auth; -// -//import java.beans.IntrospectionException; -//import java.beans.Introspector; -//import java.beans.PropertyDescriptor; -//import java.lang.reflect.InvocationTargetException; -//import java.lang.reflect.Method; -//import java.util.Arrays; -//import java.util.List; -// -//import org.springframework.beans.factory.annotation.Autowired; -//import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -//import org.springframework.context.ApplicationContext; -//import org.springframework.context.support.ClassPathXmlApplicationContext; -// -//import at.gv.egovernment.moa.id.commons.config.persistence.MOAIDConfiguration; -//import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; -//import at.gv.egovernment.moa.id.config.ConfigurationException; -//import at.gv.egovernment.moa.id.config.ConfigurationProvider; -// -//import com.fasterxml.jackson.annotation.JsonIgnore; -//import com.fasterxml.jackson.annotation.JsonProperty; -// -//public class ConfigurationToJSONConverter { -// -// @Autowired -// NewAuthConfigurationProvider configProvider; -// -// @Autowired -// MOAIDConfiguration configDataBase; -// -// public static void main(String[] args) { -// -// try { -// ConfigurationToJSONConverter converter = new ConfigurationToJSONConverter(args[0]); -// converter.writeConfigToJSONDB(); -// System.out.println("====================================="); -// System.out.println("====================================="); -// converter.readConfigFromDB(); -// System.out.println("====================================="); -// System.out.println("====================================="); -// -// // otherwise the database connection is not initialized -// JaxBAuthConfigurationProvider.getInstance(); -// List<String> methodNames = Arrays.asList("getAllOnlineApplications", "getAllUsers", "getMOAIDConfiguration"); -// converter.extractDataViaConfigurationDBRead(methodNames); -// converter.readExtractedConfigurationDBReadData(methodNames); -// -// } catch (ConfigurationException e) { -// e.printStackTrace(); -// System.out.println("Problems reading the configuration file in: " + System.getProperty(ConfigurationProvider.CONFIG_PROPERTY_NAME)); -// System.exit(1); -// } -// -// } -// -// public ConfigurationToJSONConverter(String pathToDBConfigPropertiesFile) throws ConfigurationException { -// -// System.getProperties().setProperty("location", "file:" + pathToDBConfigPropertiesFile); -// ApplicationContext context = new ClassPathXmlApplicationContext("configuration.beans.xml"); -// AutowireCapableBeanFactory acbFactory = context.getAutowireCapableBeanFactory(); -// acbFactory.autowireBean(this); -// -// } -// -// public void extractDataViaConfigurationDBRead(List<String> methodNames) { -// System.out.println("Start extracting"); -// // read objects from db and write to key-value -// for (String name : methodNames) { -// try { -// Method method = ConfigurationDBRead.class.getMethod(name); -// Object tmp = method.invoke(null, new Object[] {}); -// JsonProperty annotation = method.getAnnotation(JsonProperty.class); -// if (annotation != null) { -// configDataBase.set(annotation.value(), tmp); -// } else { -// System.out.println("Annotate Method with name: " + name); -// } -// } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException -// | InvocationTargetException e) { -// System.out.println("Problems while extracting ConfigurationDBRead data."); -// } -// } -// } -// -// public void readExtractedConfigurationDBReadData(List<String> methodNames) { -// for (String name : methodNames) { -// Object tmp = configDataBase.get(name); -// System.out.println(">>> OBJECT: " + tmp); -// } -// } -// -// public void writeConfigToJSONDB() { -// -// try { -// // find all getter methods -// for (PropertyDescriptor pd : Introspector.getBeanInfo(NewAuthConfigurationProvider.class).getPropertyDescriptors()) { -// // check if correct methods, and not annotated with @JsonIgnore -// if ((pd.getReadMethod() != null) -// && (!"class".equals(pd.getName())) -// && (pd.getReadMethod().getAnnotation(JsonIgnore.class) == null)) { -// -// JsonProperty name = pd.getReadMethod().getAnnotation(JsonProperty.class); -// // get result of get method -// Object tmp; -// try { -// tmp = pd.getReadMethod().invoke(configProvider); -// // convert result to JSON -// if (name != null) { -// configDataBase.set(name.value(), tmp); -// } else { -// System.out.println("CHECK if '" + pd.getDisplayName() + "' is NOT ANNOTATED"); -// } -// } catch (IllegalAccessException | InvocationTargetException e) { -// System.out.println("Problems while writing the configuration to the database."); -// } -// } -// } -// -// // no static method handling needed -// -// } catch (IllegalArgumentException e) { -// System.out.println("Problems while using reflection to get all getter methods."); -// } catch (IntrospectionException e) { -// System.out.println("Problems while using reflection to get all getter methods."); -// } -// -// } -// -// public void readConfigFromDB() { -// try { -// // find all getter methods -// for (PropertyDescriptor pd : Introspector.getBeanInfo(NewAuthConfigurationProvider.class) -// .getPropertyDescriptors()) { -// // check if correct methods, and not annotated with @JsonIgnore -// if ((pd.getReadMethod() != null) -// && (!"class".equals(pd.getName())) -// && (pd.getReadMethod().getAnnotation(JsonIgnore.class) == null)) { -// JsonProperty name = pd.getReadMethod().getAnnotation(JsonProperty.class); -// // get result of get method -// if (name != null) { -// System.out.println(">>> OBJECT: " + configDataBase.get(name.value())); -// } else { -// System.out.println("CHECK if '" + pd.getDisplayName() + "' is NOT ANNOTATED"); -// } -// } -// } -// } catch (IllegalArgumentException e) { -// System.out.println("Problems while using reflection to get all getter methods."); -// } catch (IntrospectionException e) { -// System.out.println("Problems while using reflection to get all getter methods."); -// } -// } -// -//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java index 92d0856ba..b68f42086 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java @@ -188,6 +188,9 @@ public interface IOAAuthParameters { List<String> getTestCredentialOIDs(); + boolean isUseIDLTestTrustStore(); + boolean isUseAuthBlockTestTestStore(); + PrivateKey getBPKDecBpkDecryptionKey(); /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java index 8f3091e42..fdd125156 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java @@ -888,4 +888,30 @@ public List<Integer> getReversionsLoggingEventCodes() { return null; } + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isUseIDLTestTrustStore() + */ +@Override +public boolean isUseIDLTestTrustStore() { + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_USETESTIDLTRUSTSTORE); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); + else + return false; +} + + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isUseAuthBlockTestTestStore() + */ +@Override +public boolean isUseAuthBlockTestTestStore() { + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_USETESTAUTHBLOCKTRUSTSTORE); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); + else + return false; +} + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java index d99e92b22..d3c26cdbe 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java @@ -35,7 +35,6 @@ import at.gv.egovernment.moa.id.config.ConnectionParameterMandate; import at.gv.egovernment.moa.id.config.auth.data.ProtocolAllowed; import at.gv.egovernment.moa.id.config.stork.STORKConfig; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; -import at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -302,7 +301,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide List<String> legacy = new ArrayList<String>(); try { if (configuration.getBooleanValue(MOAIDConfigurationConstants.GENERAL_PROTOCOLS_SAML1_LEGACY, false)) - legacy.add(SAML1Protocol.PATH); + legacy.add("id_saml1"); if (configuration.getBooleanValue(MOAIDConfigurationConstants.GENERAL_PROTOCOLS_PVP2X_LEGACY, false)) legacy.add(PVP2XProtocol.PATH); @@ -322,8 +321,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide */ public OAAuthParameter getOnlineApplicationParameter(String oaURL) { Map<String, String> oa = getActiveOnlineApplication(oaURL); - if (oa == null) { - Logger.warn("Online application with identifier " + oaURL + " is not found."); + if (oa == null) { return null; } @@ -336,7 +334,14 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return a string with a url-reference to the VerifyAuthBlock trust profile ID. * @throws ConfigurationException is thrown in case of missing {@link AuthComponentGeneral} or in case of missing {@link MOASP}. */ - public String getMoaSpAuthBlockTrustProfileID() throws ConfigurationException { + public String getMoaSpAuthBlockTrustProfileID(boolean useTestTrustStore) throws ConfigurationException { + if (useTestTrustStore) + return getMoaSpAuthBlockTestTrustProfileID(); + else + return getMoaSpAuthBlockTrustProfileID(); + } + + private String getMoaSpAuthBlockTrustProfileID() throws ConfigurationException { try { return configuration.getStringValue( MOAIDConfigurationConstants.GENERAL_AUTH_MOASP_TRUSTPROFILE_AUTHBLOCK_PROD); @@ -346,7 +351,39 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide return null; } } + + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getMoaSpAuthBlockTestTrustProfileID() + */ + private String getMoaSpAuthBlockTestTrustProfileID() + throws ConfigurationException { + try { + return configuration.getStringValue( + MOAIDConfigurationConstants.GENERAL_AUTH_MOASP_TRUSTPROFILE_AUTHBLOCK_TEST); + + } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { + Logger.warn("Test-AuthBlock validation trustprofile can not be read from configuration.", e); + return null; + } + } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getMoaSpIdentityLinkTestTrustProfileID() + */ + private String getMoaSpIdentityLinkTestTrustProfileID() + throws ConfigurationException { + try { + return configuration.getStringValue( + MOAIDConfigurationConstants.GENERAL_AUTH_MOASP_TRUSTPROFILE_IDL_TEST); + + } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { + Logger.warn("Test-IdentityLink validation trustprofile can not be read from configuration.", e); + return null; + } + } + + /** * Returns a list of strings with references to all verify transform info IDs within the moa-sp part of the authentication component. * @@ -448,7 +485,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return String with a url-reference to the VerifyIdentityLink trust profile ID * @throws ConfigurationException is thrown in case of missing {@link AuthComponentGeneral} or in case of missing {@link VerifyIdentityLink}. */ - public String getMoaSpIdentityLinkTrustProfileID() throws ConfigurationException { + private String getMoaSpIdentityLinkTrustProfileID() throws ConfigurationException { try { return configuration.getStringValue( MOAIDConfigurationConstants.GENERAL_AUTH_MOASP_TRUSTPROFILE_IDL_PROD); @@ -972,15 +1009,27 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return the requested online application or {@code null} */ public Map<String, String> getActiveOnlineApplication(String id) { - Logger.trace("Get active OnlineApplication with ID " + id + " from database."); + Logger.trace("Get active OnlineApplication with ID " + id + " from database."); + Map<String, String> oaConfig = null; try { - Map<String, String> oaConfig = configuration.getOnlineApplication(id); + //OracleDB does not allow the selection of a lob in SQL where expression + String dbDriver = properties.getProperty("configuration.hibernate.connection.driver_class"); + if (MiscUtil.isNotEmpty(dbDriver) && dbDriver.startsWith("oracle.jdbc.")) + oaConfig = configuration.getOnlineApplicationBackupVersion(id); + + else + oaConfig = configuration.getOnlineApplication(id); + if (oaConfig != null) { String isActiveString = oaConfig.get(MOAIDConfigurationConstants.SERVICE_ISACTIVE); if (isActiveString != null && Boolean.valueOf(isActiveString)) return oaConfig; - } + else + Logger.info("Online application with identifier " + id + " is found, but NOT active."); + + } else + Logger.warn("Online application with identifier " + id + " is not found."); } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { @@ -1089,4 +1138,15 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide return null; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getMoaSpIdentityLinkTrustProfileID(boolean) + */ + @Override + public String getMoaSpIdentityLinkTrustProfileID(boolean useTestTrustStore) + throws ConfigurationException { + if (useTestTrustStore) + return getMoaSpIdentityLinkTestTrustProfileID(); + else + return getMoaSpIdentityLinkTrustProfileID(); + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/DynamicOAAuthParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/DynamicOAAuthParameters.java index e59ac827b..386e04f45 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/DynamicOAAuthParameters.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/DynamicOAAuthParameters.java @@ -468,4 +468,22 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ // TODO Auto-generated method stub return null; } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isUseIDLTestTrustStore() + */ + @Override + public boolean isUseIDLTestTrustStore() { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isUseAuthBlockTestTestStore() + */ + @Override + public boolean isUseAuthBlockTestTestStore() { + // TODO Auto-generated method stub + return false; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java index 05b008515..e2892e70a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java @@ -27,7 +27,6 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import java.util.List; @@ -37,7 +36,6 @@ import eu.stork.peps.auth.commons.IPersonalAttributeList; import eu.stork.peps.auth.commons.STORKAuthnRequest; import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.DateTimeUtils; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java index ccc90a031..09b0d7971 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java @@ -31,7 +31,6 @@ import eu.stork.peps.auth.commons.IPersonalAttributeList; import eu.stork.peps.auth.commons.STORKAuthnRequest; import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; /** * @author tlenz diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISMandate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java index 8e42f0df7..12fe3c948 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISMandate.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java @@ -1,161 +1,161 @@ -/*******************************************************************************
- * 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.Serializable;
-
-import org.w3c.dom.Element;
-
-import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate;
-import at.gv.egovernment.moa.id.util.MandateBuilder;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.DOMUtils;
-import at.gv.egovernment.moa.util.MiscUtil;
-
-public class MISMandate implements Serializable{
-
- private static final long serialVersionUID = 1L;
-
- final static private String OID_NOTAR = "1.2.40.0.10.3.1";
- final static private String TEXT_NOTAR = "berufsmäßige(r) Parteienvertreter(in) mit Notariatseigenschaft";
-
- final static private String OID_RECHTSANWALT = "1.2.40.0.10.3.2";
- final static private String TEXT_RECHTSANWALT = "berufsmäßige(r) Parteienvertreter(in) mit Rechtsanwaltseigenschaft";
-
- final static private String OID_ZIVILTECHNIKER = "1.2.40.0.10.3.3";
- final static private String TEXT_ZIVILTECHNIKER = "berufsmäßige(r) Parteienvertreter(in) mit Ziviltechnikerinneneigenschaft";
-
- final static public String OID_ORGANWALTER = "1.2.40.0.10.3.4";
- final static private String TEXT_ORGANWALTER = "Organwalter";
-
- final static public String OID_ELGA_OMBUTSSTELLE = "1.2.40.0.34.3.1.3";
- final static public String OID_ELGA_OMBUTSSTELLE_TEST = "1.2.40.0.34.3.1.2.99.9";
- final static private String TEXT_ELGA_OMBUTSSTELLE = "ELGA-Ombudsstelle";
-
- private String oid = null;
- private byte[] mandate = null;
- private String owBPK = null;
- private boolean isFullMandateIncluded = false;
-
- public String getProfRep() {
- return oid;
- }
- public void setProfRep(String oid) {
- this.oid = oid;
- }
- public void setOWbPK(String oWbPK) {
- this.owBPK = oWbPK;
- }
-
- public String getOWbPK() {
- return owBPK;
- }
- public byte[] getMandate() {
- return mandate;
- }
-
- public Element getMandateDOM() {
- try {
- byte[] byteMandate = mandate;
- String stringMandate = new String(byteMandate);
- return DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement();
-
- }
- catch (Throwable e) {
- Logger.warn("Mandate content could not be generated from MISMandate.");
- return null;
- }
- }
-
- public Mandate getMandateJaxB() {
- Element domMandate = getMandateDOM();
- if (domMandate != null)
- return MandateBuilder.buildMandate(domMandate);
-
- return null;
- }
-
- public void setMandate(byte[] mandate) {
- this.mandate = mandate;
- }
-
- public String getTextualDescriptionOfOID() {
- if (MiscUtil.isNotEmpty(this.oid)) {
- if (this.oid.equalsIgnoreCase(OID_NOTAR))
- return TEXT_NOTAR;
- if (this.oid.equalsIgnoreCase(OID_RECHTSANWALT))
- return TEXT_RECHTSANWALT;
- if (this.oid.equalsIgnoreCase(OID_ZIVILTECHNIKER))
- return TEXT_ZIVILTECHNIKER;
- if (this.oid.equalsIgnoreCase(OID_ORGANWALTER))
- return TEXT_ORGANWALTER;
- if (this.oid.equalsIgnoreCase(OID_ELGA_OMBUTSSTELLE)
- || this.oid.equalsIgnoreCase(OID_ELGA_OMBUTSSTELLE_TEST))
- return TEXT_ELGA_OMBUTSSTELLE;
-
- return "Keine textuelle Beschreibung für OID " + oid;
-
- } else {
- return null;
- }
-
- }
- /**
- * @return the isFullMandateIncluded
- */
- public boolean isFullMandateIncluded() {
- return isFullMandateIncluded;
- }
- /**
- * @param isFullMandateIncluded the isFullMandateIncluded to set
- */
- public void setFullMandateIncluded(boolean isFullMandateIncluded) {
- this.isFullMandateIncluded = isFullMandateIncluded;
- }
-
-
-}
+/******************************************************************************* + * 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.data; + +import java.io.Serializable; + +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.egovernment.moa.util.MiscUtil; + +public class MISMandate implements Serializable{ + + private static final long serialVersionUID = 1L; + + final static private String OID_NOTAR = "1.2.40.0.10.3.1"; + final static private String TEXT_NOTAR = "berufsmäßige(r) Parteienvertreter(in) mit Notariatseigenschaft"; + + final static private String OID_RECHTSANWALT = "1.2.40.0.10.3.2"; + final static private String TEXT_RECHTSANWALT = "berufsmäßige(r) Parteienvertreter(in) mit Rechtsanwaltseigenschaft"; + + final static private String OID_ZIVILTECHNIKER = "1.2.40.0.10.3.3"; + final static private String TEXT_ZIVILTECHNIKER = "berufsmäßige(r) Parteienvertreter(in) mit Ziviltechnikerinneneigenschaft"; + + final static public String OID_ORGANWALTER = "1.2.40.0.10.3.4"; + final static private String TEXT_ORGANWALTER = "Organwalter"; + + final static public String OID_ELGA_OMBUTSSTELLE = "1.2.40.0.34.3.1.3"; + final static public String OID_ELGA_OMBUTSSTELLE_TEST = "1.2.40.0.34.3.1.2.99.9"; + final static private String TEXT_ELGA_OMBUTSSTELLE = "ELGA-Ombudsstelle"; + + private String oid = null; + private byte[] mandate = null; + private String owBPK = null; + private boolean isFullMandateIncluded = false; + + public String getProfRep() { + return oid; + } + public void setProfRep(String oid) { + this.oid = oid; + } + public void setOWbPK(String oWbPK) { + this.owBPK = oWbPK; + } + + public String getOWbPK() { + return owBPK; + } + public byte[] getMandate() { + return mandate; + } + + public Element getMandateDOM() { + try { + byte[] byteMandate = mandate; + String stringMandate = new String(byteMandate); + return DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement(); + + } + catch (Throwable e) { + Logger.warn("Mandate content could not be generated from MISMandate."); + return null; + } + } + + public Mandate getMandateJaxB() { + Element domMandate = getMandateDOM(); + if (domMandate != null) + return MandateBuilder.buildMandate(domMandate); + + return null; + } + + public void setMandate(byte[] mandate) { + this.mandate = mandate; + } + + public String getTextualDescriptionOfOID() { + if (MiscUtil.isNotEmpty(this.oid)) { + if (this.oid.equalsIgnoreCase(OID_NOTAR)) + return TEXT_NOTAR; + if (this.oid.equalsIgnoreCase(OID_RECHTSANWALT)) + return TEXT_RECHTSANWALT; + if (this.oid.equalsIgnoreCase(OID_ZIVILTECHNIKER)) + return TEXT_ZIVILTECHNIKER; + if (this.oid.equalsIgnoreCase(OID_ORGANWALTER)) + return TEXT_ORGANWALTER; + if (this.oid.equalsIgnoreCase(OID_ELGA_OMBUTSSTELLE) + || this.oid.equalsIgnoreCase(OID_ELGA_OMBUTSSTELLE_TEST)) + return TEXT_ELGA_OMBUTSSTELLE; + + return "Keine textuelle Beschreibung für OID " + oid; + + } else { + return null; + } + + } + /** + * @return the isFullMandateIncluded + */ + public boolean isFullMandateIncluded() { + return isFullMandateIncluded; + } + /** + * @param isFullMandateIncluded the isFullMandateIncluded to set + */ + public void setFullMandateIncluded(boolean isFullMandateIncluded) { + this.isFullMandateIncluded = isFullMandateIncluded; + } + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index 86d7c232f..1f4612dca 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -290,11 +290,7 @@ public class DispatcherServlet extends AuthServlet{ MOAReversionLogger.getInstance().logEvent(uniqueSessionIdentifier, protocolRequestID, MOAIDEventConstants.TRANSACTION_IP, req.getRemoteAddr()); protocolRequest = info.preProcess(req, resp, action, uniqueSessionIdentifier, protocolRequestID); - - if (protocolRequest != null) - MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), - protocolRequest, MOAIDEventConstants.AUTHPROTOCOL_TYPE, protocolRequest.requestedModule()); - + //request is a valid interfederation response if (protocolRequest != null && protocolRequest.getInterfederationResponse() != null ) { @@ -405,6 +401,10 @@ public class DispatcherServlet extends AuthServlet{ // *** end of protocol specific stuff *** + if (protocolRequest != null) + MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), + protocolRequest, MOAIDEventConstants.AUTHPROTOCOL_TYPE, protocolRequest.requestedModule()); + // *** start handling authentication *** AuthenticationManager authmanager = AuthenticationManager.getInstance(); @@ -504,7 +504,7 @@ public class DispatcherServlet extends AuthServlet{ moasession = AuthenticationSessionStoreage.getSession(moasessionID); //use new OAParameter - if (oaParam.useSSOQuestion() && !AuthenticationSessionStoreage.isAuthenticated(moasessionID)) { + if (oaParam.useSSOQuestion() && !AuthenticationSessionStoreage.isAuthenticated(moasessionID)) { authmanager.sendTransmitAssertionQuestion(req, resp, protocolRequest, oaParam); return; } @@ -514,15 +514,17 @@ public class DispatcherServlet extends AuthServlet{ moasession = AuthenticationSessionStoreage.getSession(moasessionID); } - //save SSO session usage in Database - newSSOSessionId = ssomanager.createSSOSessionInformations(moasessionID, protocolRequest.getOAURL()); + //save SSO session usage in Database + if (useSSOOA) { + newSSOSessionId = ssomanager.createSSOSessionInformations(moasessionID, protocolRequest.getOAURL()); - if (MiscUtil.isNotEmpty(newSSOSessionId)) { - ssomanager.setSSOSessionID(req, resp, newSSOSessionId); + if (MiscUtil.isNotEmpty(newSSOSessionId)) { + ssomanager.setSSOSessionID(req, resp, newSSOSessionId); - } else { - ssomanager.deleteSSOSessionID(req, resp); + } else { + ssomanager.deleteSSOSessionID(req, resp); + } } } else { @@ -545,7 +547,7 @@ public class DispatcherServlet extends AuthServlet{ RequestStorage.removePendingRequest(protocolRequestID); if (needAuthentication) { - boolean isSSOSession = MiscUtil.isNotEmpty(newSSOSessionId); + boolean isSSOSession = MiscUtil.isNotEmpty(newSSOSessionId) && useSSOOA; if ((useSSOOA || isSSOSession) //TODO: SSO with mandates requires an OVS extension && !moasession.getUseMandate()) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 18fb08f1b..b29220af2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -24,9 +24,11 @@ package at.gv.egovernment.moa.id.moduls; import java.io.IOException; import java.io.PrintWriter; +import java.lang.reflect.InvocationTargetException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; +import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; @@ -96,7 +98,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; import at.gv.egovernment.moa.id.storage.AssertionStorage; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; @@ -468,15 +469,33 @@ public class AuthenticationManager extends MOAIDAuthConstants { AuthnContextClassRef authnClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class); + //check if STORK protocol module is in ClassPath + Object storkRequst = null; + Integer storkSecClass = null; + try { + storkRequst = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest").newInstance(); + if (storkRequst != null && + target.getClass().isInstance(storkRequst)) { + Object storkAuthnRequest = target.getClass().getMethod("getStorkAuthnRequest", null).invoke(target, null); + storkSecClass = (Integer) storkAuthnRequest.getClass().getMethod("getQaa", null).invoke(storkAuthnRequest, null); + + } + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { + + + } + + if (sp != null && sp.isSTORKPVPGateway()){ //use PVP SecClass instead of STORK QAA level String secClass = null; - if (target instanceof MOASTORKRequest) { + if (storkRequst != null && + target.getClass().isInstance(storkRequst)) { - try { - MOASTORKRequest storkReq = (MOASTORKRequest) target; + try { secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( - PVPConstants.STORK_QAA_PREFIX + storkReq.getStorkAuthnRequest().getQaa()); + PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); } catch (Exception e) { Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); @@ -490,12 +509,12 @@ public class AuthenticationManager extends MOAIDAuthConstants { authnClassRef.setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"); } else { - if (target instanceof MOASTORKRequest) { + if (storkRequst != null && + target.getClass().isInstance(storkRequst)) { //use requested QAA level from STORK request try { - MOASTORKRequest storkReq = (MOASTORKRequest) target; authnClassRef.setAuthnContextClassRef( - PVPConstants.STORK_QAA_PREFIX + storkReq.getStorkAuthnRequest().getQaa()); + PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef() + " from STORK request"); @@ -605,21 +624,22 @@ public class AuthenticationManager extends MOAIDAuthConstants { try { if (legacyallowed && legacyparamavail) { - - //parse request parameter into MOASession - StartAuthentificationParameterParser.parse(request, response, moasession, target); - - Logger.info("Start Authentication Module: " + moasession.getModul() - + " Action: " + moasession.getAction()); - - // create execution context + + // create execution context ExecutionContext executionContext = new ExecutionContextImpl(); - executionContext.put("ccc", moasession.getCcc()); - executionContext.put("useMandate", moasession.getUseMandate()); - executionContext.put("bkuURL", moasession.getBkuURL()); - executionContext.put(PARAM_SESSIONID, moasession.getSessionID()); + executionContext.put(MOAIDAuthConstants.PARAM_SESSIONID, moasession.getSessionID()); executionContext.put("pendingRequestID", target.getRequestID()); - + + executionContext.put("isLegacyRequest", true); + + Enumeration<String> reqParamNames = request.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (MiscUtil.isNotEmpty(paramName)) + executionContext.put(paramName, request.getParameter(paramName)); + + } + // create process instance String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); @@ -642,7 +662,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { throw new MOAIDException("init.04", new Object[] { moasession.getSessionID()}); } - + // start process processEngine.start(processInstanceId); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java index 4a1da76e2..e65d77326 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java @@ -25,20 +25,23 @@ package at.gv.egovernment.moa.id.moduls; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.ServiceLoader; import at.gv.egovernment.moa.logging.Logger; public class ModulStorage { - private static final String[] modulClasses = new String[]{ - "at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol", - "at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol", - "at.gv.egovernment.moa.id.protocols.stork2.STORKProtocol", - "at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20Protocol" - }; - +// private static final String[] modulClasses = new String[]{ +//// "at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol", +// "at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol", +// "at.gv.egovernment.moa.id.protocols.stork2.STORKProtocol", +// "at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20Protocol" +// }; + private static ServiceLoader<IModulInfo> protocolModuleLoader = + ServiceLoader.load(IModulInfo.class); private static List<IModulInfo> registeredModules = new ArrayList<IModulInfo>(); + public static List<IModulInfo> getAllModules() { return registeredModules; @@ -56,20 +59,35 @@ public class ModulStorage { } static { - Logger.info("Loading modules:"); - for(int i = 0; i < modulClasses.length; i++) { - String modulClassName = modulClasses[i]; - try { - @SuppressWarnings("unchecked") - Class<IModulInfo> moduleClass = (Class<IModulInfo>)Class.forName(modulClassName); - IModulInfo module = moduleClass.newInstance(); - Logger.info("Loading Modul Information: " + module.getName()); - registeredModules.add(module); - } catch(Throwable e) { - Logger.error("Check configuration! " + modulClassName + - " is not a valid IModulInfo", e); + Logger.info("Loading protocol modules:"); + if (protocolModuleLoader != null ) { + Iterator<IModulInfo> moduleLoaderInterator = protocolModuleLoader.iterator(); + while (moduleLoaderInterator.hasNext()) { + try { + IModulInfo modul = moduleLoaderInterator.next(); + Logger.info("Loading Modul Information: " + modul.getName()); + registeredModules.add(modul); + + } catch(Throwable e) { + Logger.error("Check configuration! " + "Some protocol modul" + + " is not a valid IModulInfo", e); + } } } + +// for(int i = 0; i < modulClasses.length; i++) { +// String modulClassName = modulClasses[i]; +// try { +// @SuppressWarnings("unchecked") +// Class<IModulInfo> moduleClass = (Class<IModulInfo>)Class.forName(modulClassName); +// IModulInfo module = moduleClass.newInstance(); +// Logger.info("Loading Modul Information: " + module.getName()); +// registeredModules.add(module); +// } catch(Throwable e) { +// Logger.error("Check configuration! " + modulClassName + +// " is not a valid IModulInfo", e); +// } +// } Logger.info("Loading modules done"); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BPKAttributeBuilder.java index a38446826..048293fc2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BPKAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BPKAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -36,7 +37,7 @@ public class BPKAttributeBuilder implements IPVPAttributeBuilder { return BPK_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { String bpk = authData.getBPK(); String type = authData.getBPKType(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BirthdateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java index 89ec383ce..7cbdeca66 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/BirthdateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java @@ -20,11 +20,12 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.text.DateFormat; import java.text.SimpleDateFormat; +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; @@ -35,7 +36,7 @@ public class BirthdateAttributeBuilder implements IPVPAttributeBuilder { return BIRTHDATE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.getDateOfBirth() != null) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDAuthBlock.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDAuthBlock.java index 61840ea21..2d15edc7b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDAuthBlock.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDAuthBlock.java @@ -20,10 +20,11 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; +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; @@ -38,7 +39,7 @@ public class EIDAuthBlock implements IPVPAttributeBuilder { return EID_AUTH_BLOCK_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCcsURL.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCcsURL.java index 2df5ec22e..998377472 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCcsURL.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCcsURL.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -34,7 +35,7 @@ public class EIDCcsURL implements IPVPAttributeBuilder { return EID_CCS_URL_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { String bkuurl = authData.getBkuURL(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java index 365f36594..14199d808 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -32,7 +33,7 @@ public class EIDCitizenQAALevelAttributeBuilder implements IPVPAttributeBuilder return EID_CITIZEN_QAA_LEVEL_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { String qaaLevel = null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIdentityLinkBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIdentityLinkBuilder.java index 29d6df040..13addc1fd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIdentityLinkBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIdentityLinkBuilder.java @@ -20,10 +20,11 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; +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; @@ -37,7 +38,7 @@ public class EIDIdentityLinkBuilder implements IPVPAttributeBuilder { return EID_IDENTITY_LINK_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { try { String ilAssertion = null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIssuingNationAttributeBuilder.java index 9b85af9f8..3d7260af1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDIssuingNationAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIssuingNationAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -32,7 +33,7 @@ public class EIDIssuingNationAttributeBuilder implements IPVPAttributeBuilder { return EID_ISSUING_NATION_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { String countryCode = authData.getCcc(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSTORKTOKEN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSTORKTOKEN.java index 5e723baab..84b791708 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSTORKTOKEN.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSTORKTOKEN.java @@ -20,10 +20,11 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; +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; @@ -38,7 +39,7 @@ public class EIDSTORKTOKEN implements IPVPAttributeBuilder { return EID_STORK_TOKEN_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSectorForIDAttributeBuilder.java index 463658a3d..2ca56a791 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSectorForIDAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSectorForIDAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -34,7 +35,7 @@ public class EIDSectorForIDAttributeBuilder implements IPVPAttributeBuilder { return EID_SECTOR_FOR_IDENTIFIER_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { String bpktype = authData.getBPKType(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSignerCertificate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSignerCertificate.java index 8a603f53a..204c0c15d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSignerCertificate.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSignerCertificate.java @@ -20,11 +20,12 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; +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; @@ -38,7 +39,7 @@ public class EIDSignerCertificate implements IPVPAttributeBuilder { return EID_SIGNER_CERTIFICATE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePIN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java index 1327c634b..0437cd687 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePIN.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -35,7 +36,7 @@ public class EIDSourcePIN implements IPVPAttributeBuilder { return EID_SOURCE_PIN_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isBusinessService()) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePINType.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePINType.java index 2145e3af7..58f18ee23 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSourcePINType.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePINType.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -33,7 +34,7 @@ public class EIDSourcePINType implements IPVPAttributeBuilder { return EID_SOURCE_PIN_TYPE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isBusinessService()) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EncryptedBPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EncryptedBPKAttributeBuilder.java index b3256ac9a..76866c336 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EncryptedBPKAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EncryptedBPKAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -35,7 +36,7 @@ public class EncryptedBPKAttributeBuilder implements IPVPAttributeBuilder { return ENC_BPK_LIST_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.getEncbPKList() != null && diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/GivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/GivenNameAttributeBuilder.java index fcde1e9bd..61771de66 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/GivenNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/GivenNameAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -32,7 +33,7 @@ public class GivenNameAttributeBuilder implements IPVPAttributeBuilder { return GIVEN_NAME_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { return g.buildStringAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME, authData.getGivenName()); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeBuilder.java index d66b0ab02..ace4c0be0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeBuilder.java @@ -20,16 +20,16 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; public interface IAttributeBuilder { public String getName(); - public <ATT> ATT build(final OAAuthParameter oaParam, final IAuthData authData, + public <ATT> ATT build(final IOAAuthParameters oaParam, final IAuthData authData, final IAttributeGenerator<ATT> g) throws AttributeException; public <ATT> ATT buildEmpty(final IAttributeGenerator<ATT> g); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeGenerator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeGenerator.java index 9edb167ee..0d51818f8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IAttributeGenerator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeGenerator.java @@ -20,7 +20,7 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; public interface IAttributeGenerator<ATT> { public abstract ATT buildStringAttribute(final String friendlyName, final String name, final String value); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IPVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IPVPAttributeBuilder.java index 72775ec02..dbb799256 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/IPVPAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IPVPAttributeBuilder.java @@ -20,7 +20,7 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java index 790c1e8ca..27d3845ff 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateFullMandateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java @@ -20,13 +20,14 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; import javax.xml.transform.TransformerException; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +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.AuthenticationData; import at.gv.egovernment.moa.id.data.IAuthData; @@ -42,7 +43,7 @@ public class MandateFullMandateAttributeBuilder implements IPVPAttributeBuilder return MANDATE_FULL_MANDATE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { //only provide full mandate if it is included. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java index 9230e47fc..7144ebe6d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java @@ -20,12 +20,13 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; +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; @@ -39,7 +40,7 @@ public class MandateLegalPersonFullNameAttributeBuilder implements IPVPAttribute return MANDATE_LEG_PER_FULL_NAME_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java index 04103f28a..12dc8877b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java @@ -20,13 +20,14 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; +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; @@ -40,7 +41,7 @@ public class MandateLegalPersonSourcePinAttributeBuilder implements IPVPAttribu return MANDATE_LEG_PER_SOURCE_PIN_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if(authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java index 02e1d7ce0..a7a9a757b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java @@ -20,13 +20,14 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; +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; @@ -40,7 +41,7 @@ public class MandateLegalPersonSourcePinTypeAttributeBuilder implements IPVPAttr return MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java index 38456302c..be6372913 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java @@ -20,7 +20,7 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; @@ -29,6 +29,7 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.Identificati import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.exception.BuildException; +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; @@ -43,7 +44,7 @@ public class MandateNaturalPersonBPKAttributeBuilder implements IPVPAttributeBui return MANDATE_NAT_PER_BPK_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java index 4fcfd4650..e644f49e4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java @@ -20,7 +20,7 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.text.DateFormat; import java.text.ParseException; @@ -31,6 +31,7 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +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; @@ -45,7 +46,7 @@ public class MandateNaturalPersonBirthDateAttributeBuilder implements IPVPAttrib return MANDATE_NAT_PER_BIRTHDATE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java index 3452d7ed0..fa3ad691d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java @@ -20,7 +20,7 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.util.Iterator; @@ -29,6 +29,7 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType.FamilyName; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +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; @@ -42,7 +43,7 @@ public class MandateNaturalPersonFamilyNameAttributeBuilder implements IPVPAttr return MANDATE_NAT_PER_FAMILY_NAME_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if(authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java index 59d5c65fe..4c725c1c5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java @@ -20,7 +20,7 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.util.Iterator; @@ -28,6 +28,7 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +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; @@ -41,7 +42,7 @@ public class MandateNaturalPersonGivenNameAttributeBuilder implements IPVPAttrib return MANDATE_NAT_PER_GIVEN_NAME_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java index 444312759..53eca141e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java @@ -20,7 +20,7 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; @@ -28,6 +28,7 @@ import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +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.AuthenticationData; import at.gv.egovernment.moa.id.data.IAuthData; @@ -43,7 +44,7 @@ public class MandateNaturalPersonSourcePinAttributeBuilder implements IPVPAttri return MANDATE_NAT_PER_SOURCE_PIN_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if(authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java index 6adc9b532..46562c506 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java @@ -20,13 +20,14 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +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; @@ -40,7 +41,7 @@ public class MandateNaturalPersonSourcePinTypeAttributeBuilder implements IPVPAt return MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if(authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepDescAttributeBuilder.java index e7ba26158..e70326114 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepDescAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepDescAttributeBuilder.java @@ -20,17 +20,18 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.egovernment.moa.id.config.auth.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.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.util.MiscUtil; public class MandateProfRepDescAttributeBuilder implements IPVPAttributeBuilder { @@ -39,7 +40,7 @@ public class MandateProfRepDescAttributeBuilder implements IPVPAttributeBuilder return MANDATE_PROF_REP_DESC_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if(authData.isUseMandate()) { String text = null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepOIDAttributeBuilder.java index 1a3311c8a..89e9198b6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateProfRepOIDAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepOIDAttributeBuilder.java @@ -20,13 +20,14 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.data.MISMandate; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.util.MiscUtil; public class MandateProfRepOIDAttributeBuilder implements IPVPAttributeBuilder { @@ -35,7 +36,7 @@ public class MandateProfRepOIDAttributeBuilder implements IPVPAttributeBuilder { return MANDATE_PROF_REP_OID_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateReferenceValueAttributeBuilder.java index 7b41e9bb6..a1fa6c2a8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateReferenceValueAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateReferenceValueAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -32,7 +33,7 @@ public class MandateReferenceValueAttributeBuilder implements IPVPAttributeBuild return MANDATE_REFERENCE_VALUE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeAttributeBuilder.java index 63165f52a..040174e26 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/MandateTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeAttributeBuilder.java @@ -20,11 +20,12 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.egovernment.moa.id.config.auth.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; @@ -37,7 +38,7 @@ public class MandateTypeAttributeBuilder implements IPVPAttributeBuilder { return MANDATE_TYPE_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { if (authData.isUseMandate()) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PVPVersionAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PVPVersionAttributeBuilder.java index 674efa0d1..456634fb1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PVPVersionAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PVPVersionAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -32,7 +33,7 @@ public class PVPVersionAttributeBuilder implements IPVPAttributeBuilder { return PVP_VERSION_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { return g.buildStringAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME, PVP_VERSION_2_1); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PrincipalNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PrincipalNameAttributeBuilder.java index 11fdeb232..33f3a1d05 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/PrincipalNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PrincipalNameAttributeBuilder.java @@ -20,8 +20,9 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; +package at.gv.egovernment.moa.id.protocols.builder.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.pvp2x.builder.attributes.exceptions.AttributeException; @@ -32,7 +33,7 @@ public class PrincipalNameAttributeBuilder implements IPVPAttributeBuilder { return PRINCIPAL_NAME_NAME; } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator<ATT> g) throws AttributeException { return g.buildStringAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME, authData.getFamilyName()); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java deleted file mode 100644 index e2ac97535..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Configuration.java +++ /dev/null @@ -1,76 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java deleted file mode 100644 index b0736ff2e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Constants.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java deleted file mode 100644 index 4a33a44b7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20SessionObject.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java deleted file mode 100644 index 912060949..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/OAuth20Util.java +++ /dev/null @@ -1,111 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java deleted file mode 100644 index eb3cfcccb..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/Pair.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java deleted file mode 100644 index 439d08e0b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java +++ /dev/null @@ -1,267 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang.StringUtils; - -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.pvp2x.builder.attributes.BPKAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDAuthBlock; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDCcsURL; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDCitizenQAALevelAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDIdentityLinkBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDIssuingNationAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSTORKTOKEN; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSectorForIDAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSignerCertificate; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSourcePIN; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSourcePINType; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonFullNameAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinTypeAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonBPKAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonBirthDateAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonFamilyNameAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonGivenNameAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonSourcePinAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonSourcePinTypeAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateProfRepDescAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateProfRepOIDAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateReferenceValueAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateTypeAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKAdoptedFamilyNameAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKAgeAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKCanonicalResidenceAddressAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKCountryCodeOfBirthAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKFiscalNumberAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKGenderAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKInhertedFamilyNameAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKIsAgeOverAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKMaritalStatusAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKNationalityCodeAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKPseudonymAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKResidencePermitAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKTextResidenceAddressAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKTitleAttributBuilder; -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()); - buildersSTORK.add(new STORKAdoptedFamilyNameAttributBuilder()); - buildersSTORK.add(new STORKAgeAttributBuilder()); - buildersSTORK.add(new STORKCanonicalResidenceAddressAttributBuilder()); - buildersSTORK.add(new STORKCountryCodeOfBirthAttributBuilder()); - buildersSTORK.add(new STORKFiscalNumberAttributBuilder()); - buildersSTORK.add(new STORKGenderAttributBuilder()); - buildersSTORK.add(new STORKInhertedFamilyNameAttributBuilder()); - buildersSTORK.add(new STORKIsAgeOverAttributBuilder()); - buildersSTORK.add(new STORKMaritalStatusAttributBuilder()); - buildersSTORK.add(new STORKNationalityCodeAttributBuilder()); - buildersSTORK.add(new STORKPseudonymAttributBuilder()); - buildersSTORK.add(new STORKResidencePermitAttributBuilder()); - buildersSTORK.add(new STORKTextResidenceAddressAttributBuilder()); - buildersSTORK.add(new STORKTitleAttributBuilder()); - } - - 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAudiencesAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAudiencesAttribute.java deleted file mode 100644 index 404eb1b44..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAudiencesAttribute.java +++ /dev/null @@ -1,47 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java deleted file mode 100644 index 121648499..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdAuthenticationTimeAttribute.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java deleted file mode 100644 index 9230c0105..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdExpirationTimeAttribute.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -import java.util.Date; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java deleted file mode 100644 index 3bdda5c2a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssueInstantAttribute.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -import java.util.Date; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java deleted file mode 100644 index 85c46d5b2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdIssuerAttribute.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java deleted file mode 100644 index 6baa69b1e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -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.pvp2x.builder.attributes.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java deleted file mode 100644 index d5bda0dba..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdSubjectIdentifierAttribute.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java deleted file mode 100644 index dd84536ed..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileDateOfBirthAttribute.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java deleted file mode 100644 index 02cc66e4b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileFamilyNameAttribute.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java deleted file mode 100644 index 302ce8105..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/ProfileGivenNameAttribute.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.attributes; - -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.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.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(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java deleted file mode 100644 index 25a30bfcf..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20AccessDeniedException.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java deleted file mode 100644 index a938d1544..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20CertificateErrorException.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java deleted file mode 100644 index 307615fbd..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20Exception.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java deleted file mode 100644 index 9c2875cef..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidClientException.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java deleted file mode 100644 index c0f03c735..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidGrantException.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java deleted file mode 100644 index b980840c2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20InvalidRequestException.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java deleted file mode 100644 index 8de854821..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ResponseTypeException.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java deleted file mode 100644 index 470507f08..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20ServerErrorException.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java deleted file mode 100644 index ee7b4d7d6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20UnauthorizedClientException.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java deleted file mode 100644 index 48267d88c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/exceptions/OAuth20WrongParameterException.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java deleted file mode 100644 index 50e57bdc1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Signer.java +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/** - * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java deleted file mode 100644 index 374320a5a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SHA256Verifier.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java deleted file mode 100644 index 9f20ee956..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuth20SignatureUtil.java +++ /dev/null @@ -1,116 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java deleted file mode 100644 index af17825fd..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthJsonToken.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java deleted file mode 100644 index db15516e7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSignatureAlgorithm.java +++ /dev/null @@ -1,63 +0,0 @@ -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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java deleted file mode 100644 index 3904f8cef..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/json/OAuthSigner.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.oauth20.json; - -import net.oauth.jsontoken.crypto.Signer; - -public interface OAuthSigner extends Signer { - public abstract OAuthSignatureAlgorithm getOAuthSignatureAlgorithm(); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java deleted file mode 100644 index 19eb9a5f9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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) { - - //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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java deleted file mode 100644 index c375e674a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java +++ /dev/null @@ -1,240 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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.pvp2x.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(); - } - - 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java deleted file mode 100644 index 5fcac0b2f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java +++ /dev/null @@ -1,148 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java deleted file mode 100644 index 56d86df72..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java +++ /dev/null @@ -1,215 +0,0 @@ -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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java deleted file mode 100644 index 2238a25e1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java deleted file mode 100644 index f8e34cdea..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java +++ /dev/null @@ -1,164 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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(); - } - - } - 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java index 3d8661143..23ea4d7ee 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java @@ -26,65 +26,28 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.ServiceLoader; import org.opensaml.saml2.core.Attribute; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +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.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.BPKAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.BirthdateAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDAuthBlock; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDCcsURL; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDCitizenQAALevelAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDIdentityLinkBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDIssuingNationAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSTORKTOKEN; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSectorForIDAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSignerCertificate; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSourcePIN; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.EIDSourcePINType; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.GivenNameAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.IAttributeGenerator; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateFullMandateAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonFullNameAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateLegalPersonSourcePinTypeAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonBPKAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonBirthDateAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonFamilyNameAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonGivenNameAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonSourcePinAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateNaturalPersonSourcePinTypeAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateProfRepDescAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateProfRepOIDAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateReferenceValueAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.MandateTypeAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.PVPVersionAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.PrincipalNameAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKAdoptedFamilyNameAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKAgeAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKCanonicalResidenceAddressAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKCountryCodeOfBirthAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKFiscalNumberAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKGenderAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKInhertedFamilyNameAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKIsAgeOverAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKMaritalStatusAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKNationalityCodeAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKPseudonymAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKResidencePermitAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKTextResidenceAddressAttributBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.STORKTitleAttributBuilder; + import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.SamlAttributeGenerator; + import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.InvalidDateFormatAttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; + import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidDateFormatException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; +import at.gv.egovernment.moa.logging.Logger; public class PVPAttributeBuilder { @@ -92,64 +55,50 @@ public class PVPAttributeBuilder { private static HashMap<String, IAttributeBuilder> builders; + private static ServiceLoader<IAttributeBuilder> attributBuilderLoader = + ServiceLoader.load(IAttributeBuilder.class); + private static void addBuilder(IAttributeBuilder builder) { builders.put(builder.getName(), builder); } static { builders = new HashMap<String, IAttributeBuilder>(); - // Citizen Token normal - addBuilder(new PVPVersionAttributeBuilder()); - addBuilder(new PrincipalNameAttributeBuilder()); - addBuilder(new GivenNameAttributeBuilder()); - addBuilder(new BirthdateAttributeBuilder()); - addBuilder(new BPKAttributeBuilder()); - addBuilder(new EIDCitizenQAALevelAttributeBuilder()); - addBuilder(new EIDIssuingNationAttributeBuilder()); - addBuilder(new EIDSectorForIDAttributeBuilder()); - addBuilder(new EIDIdentityLinkBuilder()); - addBuilder(new EIDAuthBlock()); - addBuilder(new EIDCcsURL()); - addBuilder(new EIDSignerCertificate()); - addBuilder(new EIDSourcePIN()); - addBuilder(new EIDSourcePINType()); - // Mandate Attributes - addBuilder(new MandateTypeAttributeBuilder()); - addBuilder(new MandateLegalPersonFullNameAttributeBuilder()); - addBuilder(new MandateLegalPersonSourcePinAttributeBuilder()); - addBuilder(new MandateLegalPersonSourcePinTypeAttributeBuilder()); - addBuilder(new MandateNaturalPersonBirthDateAttributeBuilder()); - addBuilder(new MandateNaturalPersonBPKAttributeBuilder()); - addBuilder(new MandateNaturalPersonFamilyNameAttributeBuilder()); - addBuilder(new MandateNaturalPersonGivenNameAttributeBuilder()); - addBuilder(new MandateNaturalPersonSourcePinAttributeBuilder()); - addBuilder(new MandateNaturalPersonSourcePinTypeAttributeBuilder()); - addBuilder(new MandateTypeAttributeBuilder()); - addBuilder(new MandateProfRepOIDAttributeBuilder()); - addBuilder(new MandateProfRepDescAttributeBuilder()); - addBuilder(new MandateReferenceValueAttributeBuilder()); - addBuilder(new MandateFullMandateAttributeBuilder()); + Logger.info("Loading protocol attribut-builder modules:"); + if (attributBuilderLoader != null ) { + Iterator<IAttributeBuilder> moduleLoaderInterator = attributBuilderLoader.iterator(); + while (moduleLoaderInterator.hasNext()) { + try { + IAttributeBuilder modul = moduleLoaderInterator.next(); + Logger.info("Loading attribut-builder Modul Information: " + modul.getName()); + addBuilder(modul); + + } catch(Throwable e) { + Logger.error("Check configuration! " + "Some attribute-builder modul" + + " is not a valid IAttributeBuilder", e); + } + } + } + + Logger.info("Loading attribute-builder modules done"); + + } + + + /** + * Get a specific attribute builder + * + * @param name Attribute-builder friendly name + * + * @return Attribute-builder with this name or null if builder does not exists + */ + public static IAttributeBuilder getAttributeBuilder(String name) { + return builders.get(name); - //STORK Attributes - addBuilder(new EIDSTORKTOKEN()); - addBuilder(new STORKAdoptedFamilyNameAttributBuilder()); - addBuilder(new STORKAgeAttributBuilder()); - addBuilder(new STORKCanonicalResidenceAddressAttributBuilder()); - addBuilder(new STORKCountryCodeOfBirthAttributBuilder()); - addBuilder(new STORKFiscalNumberAttributBuilder()); - addBuilder(new STORKGenderAttributBuilder()); - addBuilder(new STORKInhertedFamilyNameAttributBuilder()); - addBuilder(new STORKIsAgeOverAttributBuilder()); - addBuilder(new STORKMaritalStatusAttributBuilder()); - addBuilder(new STORKNationalityCodeAttributBuilder()); - addBuilder(new STORKPseudonymAttributBuilder()); - addBuilder(new STORKResidencePermitAttributBuilder()); - addBuilder(new STORKTextResidenceAddressAttributBuilder()); - addBuilder(new STORKTitleAttributBuilder()); } - public static Attribute buildAttribute(String name, OAAuthParameter oaParam, + public static Attribute buildAttribute(String name, IOAAuthParameters oaParam, IAuthData authData) throws PVP2Exception, AttributeException { if (builders.containsKey(name)) { try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java deleted file mode 100644 index aff0fc0ef..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKAdoptedFamilyNameAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.ADOPTEDFAMILYNAME_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAgeAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAgeAttributBuilder.java deleted file mode 100644 index fb7c60a95..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAgeAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKAgeAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.AGE_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAttributHelper.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAttributHelper.java deleted file mode 100644 index 387e49d25..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKAttributHelper.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java deleted file mode 100644 index ddfa63b51..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKCanonicalResidenceAddressAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.CANONICALRESIDENCEADDRESS_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java deleted file mode 100644 index 08cd65a6d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKCountryCodeOfBirthAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.CONTRYCODEOFBIRTH_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKFiscalNumberAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKFiscalNumberAttributBuilder.java deleted file mode 100644 index f3a77708b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKFiscalNumberAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKFiscalNumberAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.FISCALNUMBER_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKGenderAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKGenderAttributBuilder.java deleted file mode 100644 index 6f62dbf89..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKGenderAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKGenderAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.GENDER_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java deleted file mode 100644 index 65bf9ff6e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKInhertedFamilyNameAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.INHERITEDFAMILYNAME_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKIsAgeOverAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKIsAgeOverAttributBuilder.java deleted file mode 100644 index a7a77d7b4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKIsAgeOverAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKIsAgeOverAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.ISAGEOVER_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKMaritalStatusAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKMaritalStatusAttributBuilder.java deleted file mode 100644 index c6ce4e32a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKMaritalStatusAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKMaritalStatusAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.MARITALSTATUS_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKNationalityCodeAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKNationalityCodeAttributBuilder.java deleted file mode 100644 index 8db5ceeb8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKNationalityCodeAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKNationalityCodeAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.NATIONALITYCODE_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKPseudonymAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKPseudonymAttributBuilder.java deleted file mode 100644 index 421f8c28d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKPseudonymAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKPseudonymAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.PSEUDONYM_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKResidencePermitAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKResidencePermitAttributBuilder.java deleted file mode 100644 index ceff4cf4f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKResidencePermitAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKResidencePermitAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.RESIDENCEPERMIT_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKTextResidenceAddressAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKTextResidenceAddressAttributBuilder.java deleted file mode 100644 index 1344883bf..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKTextResidenceAddressAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKTextResidenceAddressAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.TEXTRESIDENCEADDRESS_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKTitleAttributBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKTitleAttributBuilder.java deleted file mode 100644 index 5209697d6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/STORKTitleAttributBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -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.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKTitleAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.TITLE_NAME; - } - - public <ATT> ATT build(OAAuthParameter 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java index de77cc5b3..e462b277e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java @@ -31,6 +31,7 @@ import org.opensaml.xml.schema.XSString; import org.opensaml.xml.schema.impl.XSIntegerBuilder; import org.opensaml.xml.schema.impl.XSStringBuilder; +import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; public class SamlAttributeGenerator implements IAttributeGenerator<Attribute> { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java index fe287a433..d76e6c2f1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java @@ -59,6 +59,12 @@ public class CredentialProvider { .getIDPKeyPasswordMetadata().toCharArray()); credentials.setUsageType(UsageType.SIGNING); + if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { + Logger.error("IDP Metadata Signing credentials is not found or contains no PrivateKey."); + throw new CredentialsNotAvailableException("IDP Assertion Signing credentials (Alias: " + + config.getIDPKeyAliasMetadata() + ") is not found or contains no PrivateKey.", null); + + } return credentials; } catch (Exception e) { Logger.error("Failed to generate IDP Metadata Signing credentials"); @@ -80,6 +86,13 @@ public class CredentialProvider { .getIDPKeyPasswordAssertionSign().toCharArray()); credentials.setUsageType(UsageType.SIGNING); + if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { + Logger.error("IDP Assertion Signing credentials is not found or contains no PrivateKey."); + throw new CredentialsNotAvailableException("IDP Assertion Signing credentials (Alias: " + + config.getIDPKeyAliasAssertionSign() + ") is not found or contains no PrivateKey.", null); + + } + return (X509Credential) credentials; } catch (Exception e) { Logger.error("Failed to generate IDP Assertion Signing credentials"); @@ -105,6 +118,14 @@ public class CredentialProvider { .getIDPKeyPasswordAssertionEncryption().toCharArray()); credentials.setUsageType(UsageType.ENCRYPTION); + + if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { + Logger.error("IDP Assertion Encryption credentials is not found or contains no PrivateKey."); + throw new CredentialsNotAvailableException("IDP Assertion Encryption credentials (Alias: " + + config.getIDPKeyAliasAssertionEncryption() + ") is not found or contains no PrivateKey.", null); + + } + return (X509Credential) credentials; } catch (Exception e) { Logger.error("Failed to generate IDP Assertion Encryption credentials"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerifierMOASP.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerifierMOASP.java index 942fab4f3..9c654d42f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerifierMOASP.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerifierMOASP.java @@ -1,136 +1,136 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.verification; - -import java.io.UnsupportedEncodingException; - -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.xml.validation.ValidationException; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.auth.builder.VerifyXMLSignatureRequestBuilder; -import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; -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.invoke.SignatureVerificationInvoker; -import at.gv.egovernment.moa.id.auth.parser.VerifyXMLSignatureResponseParser; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.util.XMLUtil; -import at.gv.egovernment.moa.logging.Logger; - -public class SAMLVerifierMOASP implements ISAMLVerifier { - - - //TODO: implement via metadata validator .... - public void verifyRequest(RequestAbstractType request) - throws MOAIDException { - // validate Signature - try { - if (request.isSigned()) { - - String trustProfileID = AuthConfigurationProviderFactory.getInstance() - .getStorkConfig().getSignatureVerificationParameter() - .getTrustProfileID(); - - Logger.trace("Starting validation of Signature references"); - try { - SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); - sigValidator.validate(request.getSignature()); - } catch (ValidationException e) { - Logger.error("Validation of XML Signature refrences failed: " - + e.getMessage()); - throw new SecurityException(e); - } - Logger.debug("XML Signature references are OK."); - - Logger.debug("Invoking MOA-SP with TrustProfileID: " - + trustProfileID); - - // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP - Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() - .build(XMLUtil.printXML(request.getDOM()).getBytes("UTF-8"), - trustProfileID); - - Logger.trace("VerifyXMLSignatureRequest for MOA-SP succesfully built"); - - Logger.trace("Calling MOA-SP"); - // invokes the call - Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() - .verifyXMLSignature(domVerifyXMLSignatureRequest); - - // parses the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( - domVerifyXMLSignatureResponse).parseData(); - - Logger.trace("Received VerifyXMLSignatureResponse from MOA-SP"); - - if (verifyXMLSignatureResponse.getSignatureCheckCode() != 0) { - String msg = "Signature of SAMLResponse not valid"; - Logger.error(msg); - throw new SecurityException(msg); - } - - Logger.debug("Signature of SAML response successfully verified"); - - if (verifyXMLSignatureResponse.getCertificateCheckCode() != 0) { - String msg = "Certificate of SAMLResponse not valid"; - Logger.error(msg); - throw new SecurityException(msg); - } - - Logger.debug("Signing certificate of SAML response succesfully verified"); - - } else { - String msg = "SAML Object is not signed."; - throw new SecurityException(msg); - } - - } catch (ConfigurationException e) { - String msg = "Unable to load STORK configuration for STORK SAML Response signature verification."; - Logger.error(msg, e); - throw new SecurityException(msg, e); - } catch (ParseException e) { - String msg = "Unable to parse VerifyXMLSignature Request or Response."; - Logger.error(msg, e); - throw new SecurityException(msg, e); - } catch (BuildException e) { - String msg = "Unable to parse VerifyXMLSignature Request or Response."; - Logger.error(msg, e); - throw new SecurityException(msg, e); - } catch (ServiceException e) { - String msg = "Unable to invoke MOA-SP."; - Logger.error(msg, e); - throw new SecurityException(msg, e); - } catch (UnsupportedEncodingException e) { - String msg = "Unsupported Encoding."; - Logger.error(msg, e); - throw new SecurityException(msg, e); - } - - } - -} +///******************************************************************************* +// * Copyright 2014 Federal Chancellery Austria +// * MOA-ID has been developed in a cooperation between BRZ, the Federal +// * Chancellery Austria - ICT staff unit, and Graz University of Technology. +// * +// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by +// * the European Commission - subsequent versions of the EUPL (the "Licence"); +// * You may not use this work except in compliance with the Licence. +// * You may obtain a copy of the Licence at: +// * http://www.osor.eu/eupl/ +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the Licence is distributed on an "AS IS" basis, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the Licence for the specific language governing permissions and +// * limitations under the Licence. +// * +// * This product combines work with different licenses. See the "NOTICE" text +// * file for details on the various modules and licenses. +// * The "NOTICE" text file is part of the distribution. Any derivative works +// * that you distribute must include a readable copy of the "NOTICE" text file. +// *******************************************************************************/ +//package at.gv.egovernment.moa.id.protocols.pvp2x.verification; +// +//import java.io.UnsupportedEncodingException; +// +//import org.opensaml.saml2.core.RequestAbstractType; +//import org.opensaml.security.SAMLSignatureProfileValidator; +//import org.opensaml.xml.validation.ValidationException; +//import org.w3c.dom.Element; +// +//import at.gv.egovernment.moa.id.auth.builder.VerifyXMLSignatureRequestBuilder; +//import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; +//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.invoke.SignatureVerificationInvoker; +//import at.gv.egovernment.moa.id.auth.parser.VerifyXMLSignatureResponseParser; +//import at.gv.egovernment.moa.id.config.ConfigurationException; +//import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +//import at.gv.egovernment.moa.id.util.XMLUtil; +//import at.gv.egovernment.moa.logging.Logger; +// +//public class SAMLVerifierMOASP implements ISAMLVerifier { +// +// +// //TODO: implement via metadata validator .... +// public void verifyRequest(RequestAbstractType request) +// throws MOAIDException { +// // validate Signature +// try { +// if (request.isSigned()) { +// +// String trustProfileID = AuthConfigurationProviderFactory.getInstance() +// .getStorkConfig().getSignatureVerificationParameter() +// .getTrustProfileID(); +// +// Logger.trace("Starting validation of Signature references"); +// try { +// SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); +// sigValidator.validate(request.getSignature()); +// } catch (ValidationException e) { +// Logger.error("Validation of XML Signature refrences failed: " +// + e.getMessage()); +// throw new SecurityException(e); +// } +// Logger.debug("XML Signature references are OK."); +// +// Logger.debug("Invoking MOA-SP with TrustProfileID: " +// + trustProfileID); +// +// // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP +// Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() +// .build(XMLUtil.printXML(request.getDOM()).getBytes("UTF-8"), +// trustProfileID); +// +// Logger.trace("VerifyXMLSignatureRequest for MOA-SP succesfully built"); +// +// Logger.trace("Calling MOA-SP"); +// // invokes the call +// Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() +// .verifyXMLSignature(domVerifyXMLSignatureRequest); +// +// // parses the <VerifyXMLSignatureResponse> +// VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( +// domVerifyXMLSignatureResponse).parseData(); +// +// Logger.trace("Received VerifyXMLSignatureResponse from MOA-SP"); +// +// if (verifyXMLSignatureResponse.getSignatureCheckCode() != 0) { +// String msg = "Signature of SAMLResponse not valid"; +// Logger.error(msg); +// throw new SecurityException(msg); +// } +// +// Logger.debug("Signature of SAML response successfully verified"); +// +// if (verifyXMLSignatureResponse.getCertificateCheckCode() != 0) { +// String msg = "Certificate of SAMLResponse not valid"; +// Logger.error(msg); +// throw new SecurityException(msg); +// } +// +// Logger.debug("Signing certificate of SAML response succesfully verified"); +// +// } else { +// String msg = "SAML Object is not signed."; +// throw new SecurityException(msg); +// } +// +// } catch (ConfigurationException e) { +// String msg = "Unable to load STORK configuration for STORK SAML Response signature verification."; +// Logger.error(msg, e); +// throw new SecurityException(msg, e); +// } catch (ParseException e) { +// String msg = "Unable to parse VerifyXMLSignature Request or Response."; +// Logger.error(msg, e); +// throw new SecurityException(msg, e); +// } catch (BuildException e) { +// String msg = "Unable to parse VerifyXMLSignature Request or Response."; +// Logger.error(msg, e); +// throw new SecurityException(msg, e); +// } catch (ServiceException e) { +// String msg = "Unable to invoke MOA-SP."; +// Logger.error(msg, e); +// throw new SecurityException(msg, e); +// } catch (UnsupportedEncodingException e) { +// String msg = "Unsupported Encoding."; +// Logger.error(msg, e); +// throw new SecurityException(msg, e); +// } +// +// } +// +//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java deleted file mode 100644 index 621c7c753..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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.auth.stork.STORKResponseProcessor; -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 = STORKResponseProcessor.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java deleted file mode 100644 index 2b4aaf458..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java +++ /dev/null @@ -1,213 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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></code> containing a - * <code>SAML artifact</code> and returns the corresponding - * authentication data <code>lt;saml:Assertion></code> - * (obtained from the <code>AuthenticationServer</code>), - * enclosed in a <code>lt;samlp:Response></code>. - * <br/>Bad requests are mapped into various <code>lt;samlp:StatusCode></code>s, - * possibly containing enclosed sub-<code>lt;samlp:StatusCode></code>s. - * The status codes are defined in the SAML specification. - * - * @param requests request elements of type <code>lt;samlp:Request></code>; - * only 1 request element is allowed - * @return response element of type <code>lt;samlp:Response></code>, - * packed into an <code>Element[]</code> - * @throws AxisFault thrown when an error occurs in assembling the - * <code>lt;samlp:Response></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationData.java deleted file mode 100644 index d48c0a9bb..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationData.java +++ /dev/null @@ -1,177 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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><saml:Assertion></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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java deleted file mode 100644 index e70e71d49..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java +++ /dev/null @@ -1,592 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.saml1; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; - -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.w3c.dom.Element; -import org.xml.sax.SAXException; - -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.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; - } - - /** - * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java deleted file mode 100644 index ddd1f1394..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java +++ /dev/null @@ -1,226 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java deleted file mode 100644 index 3da7cab80..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java deleted file mode 100644 index 7757f5af6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java +++ /dev/null @@ -1,367 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java deleted file mode 100644 index 8c34d4806..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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.EHvdAttribute_deprecatedProviderPlugin; -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("EHvdAttributeProvider_deprecated")) { - return new EHvdAttribute_deprecatedProviderPlugin(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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java deleted file mode 100644 index 887944366..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java +++ /dev/null @@ -1,531 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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.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.id.util.client.mis.simple.MISMandate; -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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java deleted file mode 100644 index bde0f362d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java +++ /dev/null @@ -1,249 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/CompleteAuthentication?" + 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java deleted file mode 100644 index acbf1678a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java deleted file mode 100644 index e01a7526a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java deleted file mode 100644 index 096f223d7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java deleted file mode 100644 index 2c7e5b539..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ /dev/null @@ -1,248 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java deleted file mode 100644 index 3f1e96f2f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java +++ /dev/null @@ -1,266 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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.id.protocols.saml1.SAML1Protocol; -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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java deleted file mode 100644 index a233835bf..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java +++ /dev/null @@ -1,308 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java deleted file mode 100644 index a3fac0f6e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java +++ /dev/null @@ -1,182 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java deleted file mode 100644 index 2351450e4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java +++ /dev/null @@ -1,602 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java deleted file mode 100644 index c715b65eb..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java deleted file mode 100644 index a560bdaff..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java deleted file mode 100644 index 123d32af4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java deleted file mode 100644 index c4f9658e4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java +++ /dev/null @@ -1,233 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java deleted file mode 100644 index 2c2df3e54..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java deleted file mode 100644 index aaf13a779..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java +++ /dev/null @@ -1,139 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java deleted file mode 100644 index bd1576020..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java +++ /dev/null @@ -1,254 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttribute_deprecatedProviderPlugin.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttribute_deprecatedProviderPlugin.java deleted file mode 100644 index a16603beb..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttribute_deprecatedProviderPlugin.java +++ /dev/null @@ -1,260 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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.IsHealthCareProfessionalDeprecatedType; -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.IsHealthCareProfessionalType; // IsHealthCareProfessionalDeprecatedType; -//import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion. _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 EHvdAttribute_deprecatedProviderPlugin extends AttributeProvider { - - /** The destination. */ - private Object destination; - - /** - * Instantiates a new e hvd attribute provider plugin. - * - * @param url the service url - * @param supportedAttributes - */ - public EHvdAttribute_deprecatedProviderPlugin(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")) { - // the citizen is no HCP - acquiredAttribute = new PersonalAttribute("isHealthCareProfessional", false, new ArrayList<String>(), AttributeStatusType.NOT_AVAILABLE.value()); - } else { - // go on and parse the data - IsHealthCareProfessionalDeprecatedType result = new IsHealthCareProfessionalDeprecatedType(); - result.setNameOfOrganisation(collection.get("NameOfOrganisation")); - - if (collection.get("Type").equals("Medical doctor")) - result.setHCPType("D"); - else - result.setHCPType("?"); - - if (collection.get("Specialization").contains("Arzt für Allgemeinmedizin")) - result.setSpecialisation("GP"); - else - result.setSpecialisation("??"); - - result.setAQAA(4); - - final Marshaller m = JAXBContext.newInstance(IsHealthCareProfessionalDeprecatedType.class).createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - - StringWriter stringWriter = new StringWriter(); - m.marshal(new ObjectFactory().createIsHealthCareProfessionalDeprecated(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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java deleted file mode 100644 index f671f0807..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java +++ /dev/null @@ -1,231 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java deleted file mode 100644 index 7f06c604b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java deleted file mode 100644 index def89d0d9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java +++ /dev/null @@ -1,688 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java deleted file mode 100644 index 5ee0e380e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java +++ /dev/null @@ -1,193 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.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/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java index 704adc80d..3b97f3b08 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java @@ -145,22 +145,22 @@ public class AssertionStorage { query.setTimestamp("timeout", expioredate); results = query.list(); session.getTransaction().commit(); - } - - if (results.size() != 0) { - for(AssertionStore result : results) { - try { - cleanDelete(result); - Logger.info("Remove stored information with ID: " + result.getArtifact() - + " after timeout."); - } catch (HibernateException e){ - Logger.warn("Sessioninformation with ID=" + result.getArtifact() - + " not removed after timeout! (Error during Database communication)", e); - } - - } - } + if (results.size() != 0) { + for(AssertionStore result : results) { + try { + cleanDelete(result); + Logger.info("Remove stored information with ID: " + result.getArtifact() + + " after timeout."); + + } catch (HibernateException e){ + Logger.warn("Sessioninformation with ID=" + result.getArtifact() + + " not removed after timeout! (Error during Database communication)", e); + } + + } + } + } } public void remove(String artifact) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java index c53bacad0..9dee39fe8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java @@ -206,26 +206,34 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; - - synchronized (session) { - - session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithID"); - query.setParameter("sessionid", moaSessionID); - result = query.list(); - - - Logger.trace("Found entries: " + result.size()); + Transaction tx = null; + try { + synchronized (session) { + + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithID"); + query.setParameter("sessionid", moaSessionID); + result = query.list(); + - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - throw new MOADatabaseException("No session found with this sessionID"); + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + throw new MOADatabaseException("No session found with this sessionID"); + } + + AuthenticatedSessionStore dbsession = (AuthenticatedSessionStore) result.get(0); + tx.commit(); + cleanDelete(dbsession); } - AuthenticatedSessionStore dbsession = (AuthenticatedSessionStore) result.get(0); - session.getTransaction().commit(); - cleanDelete(dbsession); + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } } @@ -290,28 +298,36 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithSSOID"); - query.setParameter("sessionid", SSOSessionID); - result = query.list(); + Transaction tx = null; + try { + synchronized (session) { + + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithSSOID"); + query.setParameter("sessionid", SSOSessionID); + result = query.list(); - //send transaction - session.getTransaction().commit(); - } + //send transaction + tx.commit(); + + } - Logger.trace("Found entries: " + result.size()); + Logger.trace("Found entries: " + result.size()); - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - return null; + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + return null; - } else { - return result.get(0).getSessionid(); + } else { + return result.get(0).getSessionid(); - } + } + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } } public static boolean isSSOSession(String sessionID) throws MOADatabaseException { @@ -331,27 +347,33 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithSSOID"); - query.setParameter("sessionid", SSOId); - result = query.list(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithSSOID"); + query.setParameter("sessionid", SSOId); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); - //send transaction - session.getTransaction().commit(); + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + return null; + + } else { + return result.get(0); + } + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - return null; - - } else { - return result.get(0); - } } public static void addSSOInformation(String moaSessionID, String SSOSessionID, @@ -454,13 +476,15 @@ public class AuthenticationSessionStoreage { } catch(HibernateException e) { Logger.warn("Error during database saveOrUpdate. Rollback.", e); - tx.rollback(); - throw new AuthenticationException("SSO Session information can not be stored! --> SSO is deactivated", null); - } + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw new AuthenticationException("SSO Session information can not be stored! --> SSO is deactivated", null); + } } public static List<OASessionStore> getAllActiveOAFromMOASession(AuthenticationSession moaSession) { MiscUtil.assertNotNull(moaSession, "MOASession"); + Session session = null; try { List<OASessionStore> oas = new ArrayList<OASessionStore>(); @@ -468,7 +492,7 @@ public class AuthenticationSessionStoreage { AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); oas.addAll(dbsession.getActiveOAsessions()); - Session session = MOASessionDBUtils.getCurrentSession(); + session = MOASessionDBUtils.getCurrentSession(); session.getTransaction().commit(); return oas; @@ -476,6 +500,14 @@ public class AuthenticationSessionStoreage { } catch (MOADatabaseException e) { Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e); + } catch (Exception e) { + if (session != null && session.getTransaction() != null + && !session.getTransaction().wasCommitted()) { + session.getTransaction().rollback(); + throw e; + + } + } return null; @@ -483,13 +515,13 @@ public class AuthenticationSessionStoreage { public static List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(AuthenticationSession moaSession) { MiscUtil.assertNotNull(moaSession, "MOASession"); - + Session session = null; try { List<InterfederationSessionStore> idps = new ArrayList<InterfederationSessionStore>(); AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); idps.addAll(dbsession.getInderfederation()); - Session session = MOASessionDBUtils.getCurrentSession(); + session = MOASessionDBUtils.getCurrentSession(); session.getTransaction().commit(); return idps; @@ -497,6 +529,14 @@ public class AuthenticationSessionStoreage { } catch (MOADatabaseException e) { Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e); + } catch (Exception e) { + if (session != null && session.getTransaction() != null + && !session.getTransaction().wasCommitted()) { + session.getTransaction().rollback(); + throw e; + + } + } return null; @@ -508,35 +548,42 @@ public class AuthenticationSessionStoreage { Logger.trace("Get moaSession for userNameID " + userNameID + " and OA " + oaID + " from database."); Session session = MOASessionDBUtils.getCurrentSession(); - - List<AuthenticatedSessionStore> result; + Transaction tx = null; - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getMOASessionWithNameIDandOAID"); - query.setParameter("oaID", oaID); - query.setParameter("nameID", userNameID); - result = query.list(); + List<AuthenticatedSessionStore> result = null;; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getMOASessionWithNameIDandOAID"); + query.setParameter("oaID", oaID); + query.setParameter("nameID", userNameID); + result = query.list(); + + //send transaction + tx.commit(); + } - //send transaction - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No unique entry found."); - return null; - - } - try { - return decryptSession(result.get(0)); + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No unique entry found."); + return null; + + } + + return decryptSession(result.get(0)); } catch (BuildException e) { - Logger.warn("MOASession deserialization-exception by using MOASessionID=" + result.get(0).getSessionid(), e); + Logger.warn("MOASession deserialization-exception by using MOASessionID=" + result.get(0).getSessionid(), e); return null; + + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; } + } public static OASessionStore searchActiveOASSOSession(AuthenticationSession moaSession, String oaID, String protocolType) { @@ -548,29 +595,36 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol"); - query.setParameter("sessionID", moaSession.getSessionID()); - query.setParameter("oaID", oaID); - query.setParameter("protocol", protocolType); - result = query.list(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol"); + query.setParameter("sessionID", moaSession.getSessionID()); + query.setParameter("oaID", oaID); + query.setParameter("protocol", protocolType); + result = query.list(); + + //send transaction + tx.commit(); + } - //send transaction - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - - } - - return result.get(0).getActiveOAsessions().get(0); + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + + } + + return result.get(0).getActiveOAsessions().get(0); + + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } } public static String getPendingRequestID(String sessionID) { @@ -585,6 +639,7 @@ public class AuthenticationSessionStoreage { } public static AuthenticationSession getSessionWithPendingRequestID(String pedingRequestID) { + Transaction tx = null; try { MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID"); Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database."); @@ -593,13 +648,13 @@ public class AuthenticationSessionStoreage { List<AuthenticatedSessionStore> result; synchronized (session) { - session.beginTransaction(); + tx = session.beginTransaction(); Query query = session.getNamedQuery("getSessionWithPendingRequestID"); query.setParameter("sessionid", pedingRequestID); result = query.list(); //send transaction - session.getTransaction().commit(); + tx.commit(); } Logger.trace("Found entries: " + result.size()); @@ -614,8 +669,13 @@ public class AuthenticationSessionStoreage { } catch (Throwable e) { Logger.warn("MOASession deserialization-exception by using MOASessionID=" + pedingRequestID); + + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + return null; - } + + } } public static boolean deleteSessionWithPendingRequestID(String id) { @@ -624,34 +684,40 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithPendingRequestID"); - query.setParameter("sessionid", id); - result = query.list(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithPendingRequestID"); + query.setParameter("sessionid", id); + result = query.list(); + + //send transaction + tx.commit(); + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + return false; + + } else { + cleanDelete(result.get(0)); + return true; + } + } - //send transaction - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - return false; - - } else { - cleanDelete(result.get(0)); - return true; - } - - + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } } public static AuthenticationSession getSessionWithUserNameID(String nameID) { + Transaction tx = null; try { MiscUtil.assertNotNull(nameID, "nameID"); Logger.trace("Get authenticated session with pedingRequestID " + nameID + " from database."); @@ -660,13 +726,13 @@ public class AuthenticationSessionStoreage { List<AuthenticatedSessionStore> result; synchronized (session) { - session.beginTransaction(); + tx = session.beginTransaction(); Query query = session.getNamedQuery("getMOAISessionWithUserNameID"); query.setParameter("usernameid", StringEscapeUtils.escapeHtml(nameID)); result = query.list(); //send transaction - session.getTransaction().commit(); + tx.commit(); } Logger.trace("Found entries: " + result.size()); @@ -680,7 +746,9 @@ public class AuthenticationSessionStoreage { return decryptSession(result.get(0)); } catch (Throwable e) { - Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID); + Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID); + if (tx != null && !tx.wasCommitted()) + tx.rollback(); return null; } @@ -692,27 +760,33 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionID"); - query.setParameter("sessionID", sessionID); - result = query.list(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionID"); + query.setParameter("sessionID", sessionID); + result = query.list(); + + //send transaction + tx.commit(); + } - //send transaction - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - - } - - return result.get(0).getInderfederation().get(0); + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + + } + + return result.get(0).getInderfederation().get(0); + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } } public static InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASessionIDPID(String sessionID, String idpID) { @@ -722,28 +796,34 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionIDIDPID"); - query.setParameter("sessionID", sessionID); - query.setParameter("idpID", idpID); - result = query.list(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionIDIDPID"); + query.setParameter("sessionID", sessionID); + query.setParameter("idpID", idpID); + result = query.list(); + + //send transaction + tx.commit(); + } - //send transaction - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - - } - - return result.get(0).getInderfederation().get(0); + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + + } + + return result.get(0).getInderfederation().get(0); + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } } public static String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException { @@ -849,27 +929,33 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID"); - query.setParameter("sessionID", moaSession.getSessionID()); - result = query.list(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID"); + query.setParameter("sessionID", moaSession.getSessionID()); + result = query.list(); + + //send transaction + tx.commit(); + } - //send transaction - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - - } - - return result.get(0).getInderfederation().get(0); + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + + } + + return result.get(0).getInderfederation().get(0); + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } } /** @@ -932,28 +1018,35 @@ public class AuthenticationSessionStoreage { List<AuthenticatedSessionStore> results; Session session = MOASessionDBUtils.getCurrentSession(); - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getMOAISessionsWithTimeOut"); - query.setTimestamp("timeoutcreate", expioredatecreate); - query.setTimestamp("timeoutupdate", expioredateupdate); - results = query.list(); - session.getTransaction().commit(); - } - - if (results.size() != 0) { - for(AuthenticatedSessionStore result : results) { - try { - cleanDelete(result); - Logger.info("Authenticated session with sessionID=" + result.getSessionid() - + " after session timeout."); - - } catch (HibernateException e){ - Logger.warn("Authenticated session with sessionID=" + result.getSessionid() - + " not removed after timeout! (Error during Database communication)", e); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getMOAISessionsWithTimeOut"); + query.setTimestamp("timeoutcreate", expioredatecreate); + query.setTimestamp("timeoutupdate", expioredateupdate); + results = query.list(); + tx.commit(); + + if (results.size() != 0) { + for(AuthenticatedSessionStore result : results) { + try { + cleanDelete(result); + Logger.info("Authenticated session with sessionID=" + result.getSessionid() + + " after session timeout."); + + } catch (HibernateException e){ + Logger.warn("Authenticated session with sessionID=" + result.getSessionid() + + " not removed after timeout! (Error during Database communication)", e); + } + } } - } + } + + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; } } @@ -1006,26 +1099,32 @@ public class AuthenticationSessionStoreage { Session session = MOASessionDBUtils.getCurrentSession(); List result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithID"); - query.setParameter("sessionid", sessionID); - result = query.list(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithID"); + query.setParameter("sessionid", sessionID); + result = query.list(); + + //send transaction + if (commit) + tx.commit(); + } - //send transaction - if (commit) - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - throw new MOADatabaseException("No session found with this sessionID"); - } - - return (AuthenticatedSessionStore) result.get(0); + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + throw new MOADatabaseException("No session found with this sessionID"); + } + + return (AuthenticatedSessionStore) result.get(0); + } catch (Exception e) { + if (tx != null && !tx.wasCommitted() && commit) + tx.rollback(); + throw e; + } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBExceptionStoreImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBExceptionStoreImpl.java index 054ad1014..4cddd141b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBExceptionStoreImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBExceptionStoreImpl.java @@ -126,22 +126,22 @@ public class DBExceptionStoreImpl implements IExceptionStore { query.setTimestamp("timeout", expioredate); results = query.list(); session.getTransaction().commit(); - } - - if (results.size() != 0) { - for(ExceptionStore result : results) { - try { - MOASessionDBUtils.delete(result); - Logger.info("Remove Exception with ID=" + result.getExid() - + " after timeout."); - } catch (HibernateException e){ - Logger.warn("Exception with ID=" + result.getExid() - + " not removed after timeout! (Error during Database communication)", e); - } - - } - } + if (results.size() != 0) { + for(ExceptionStore result : results) { + try { + MOASessionDBUtils.delete(result); + Logger.info("Remove Exception with ID=" + result.getExid() + + " after timeout."); + + } catch (HibernateException e){ + Logger.warn("Exception with ID=" + result.getExid() + + " not removed after timeout! (Error during Database communication)", e); + } + + } + } + } } @SuppressWarnings("rawtypes") diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ErrorResponseUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ErrorResponseUtils.java index aff7e5057..99ac6ba4c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ErrorResponseUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ErrorResponseUtils.java @@ -27,8 +27,6 @@ import java.util.Locale; import at.gv.egovernment.moa.id.auth.exception.BKUException; import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; import at.gv.egovernment.moa.util.Messages; import at.gv.egovernment.moa.util.MiscUtil; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/HTTPRequestJSPForwarder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/HTTPRequestJSPForwarder.java deleted file mode 100644 index 3e31c0403..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/HTTPRequestJSPForwarder.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * 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. - */ - - -/* - * Created on 17.02.2004 - * - * To change the template for this generated file go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -package at.gv.egovernment.moa.id.util; - -import java.io.IOException; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author rschamberger - * - * To change the template for this generated type comment go to - * Window>Preferences>Java>Code Generation>Code and Comments - */ -public class HTTPRequestJSPForwarder { - - /** - * Forwards the HttpServletRequest to a customizable JSP Page and serves the Response. <br> - * <ul> - * <li>Logs the message</li> - * </ul> - * - * @param message message text - * @param jspPageURI URI of the JSP page - * @param context the servlet context of the servlet belonging to the req, resp - * @param req servlet request - * @param resp servlet response - */ - public static void forwardNamed( - String message, - String jspPageURI, - ServletContext context, - HttpServletRequest req, - HttpServletResponse resp) { - - if (null != message) { - Logger.info(message); - req.setAttribute("Message", message); - } - - //forward this to the given jsp page where the HTML response is generated - try { - context.getRequestDispatcher(jspPageURI).forward(req, resp); - } catch (IOException e) { - Logger.error(e); - } catch (ServletException e) { - Logger.error(e); - } - } - - /** - * Forwards the HttpServletRequest to the customizable JSP Page 'message.jsp' and serves the Response. <br> - * <ul> - * <li>Logs the message</li> - * </ul> - * - * @param message message text - * @param context the servlet context of the servlet belonging to the req, resp - * @param req servlet request - * @param resp servlet response - */ - public static void forwardDefault( - String message, - ServletContext context, - HttpServletRequest req, - HttpServletResponse resp) { - forwardNamed(message, "/message.jsp", context, req, resp); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java index 3dbc0ab7b..a4d79ac05 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java @@ -1,183 +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.
- ******************************************************************************/
-/*
- * 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.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.MOAIDException;
-import at.gv.egovernment.moa.logging.Logger;
-
-/**
- * @author <a href="mailto:peter.danner@egiz.gv.at">Peter Danner</a>
- *
- */
-public class 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(), AuthenticationServer.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);
-
- }
-
- public static String getBaseUrl( HttpServletRequest request ) {
- if ( ( request.getServerPort() == 80 ) ||
- ( request.getServerPort() == 443 ) )
- return request.getScheme() + "://" +
- request.getServerName() +
- request.getContextPath();
- else
- return request.getScheme() + "://" +
- request.getServerName() + ":" + request.getServerPort() +
- request.getContextPath();
- }
-
-}
+/******************************************************************************* + * 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 javax.servlet.http.HttpServletRequest; + +public class ServletUtils { + + + public static String getBaseUrl( HttpServletRequest request ) { + if ( ( request.getServerPort() == 80 ) || + ( request.getServerPort() == 443 ) ) + return request.getScheme() + "://" + + request.getServerName() + + request.getContextPath(); + else + return request.getScheme() + "://" + + request.getServerName() + ":" + request.getServerPort() + + request.getContextPath(); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSessionId.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSessionId.java deleted file mode 100644 index 9050a0f38..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSessionId.java +++ /dev/null @@ -1,68 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java deleted file mode 100644 index 24c96a78f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java +++ /dev/null @@ -1,358 +0,0 @@ -/*******************************************************************************
- * Copyright 2014 Federal Chancellery Austria
- * MOA-ID has been developed in a cooperation between BRZ, the Federal
- * Chancellery Austria - ICT staff unit, and Graz University of Technology.
- *
- * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
- * the European Commission - subsequent versions of the EUPL (the "Licence");
- * You may not use this work except in compliance with the Licence.
- * You may obtain a copy of the Licence at:
- * http://www.osor.eu/eupl/
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the Licence is distributed on an "AS IS" basis,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the Licence for the specific language governing permissions and
- * limitations under the Licence.
- *
- * This product combines work with different licenses. See the "NOTICE" text
- * file for details on the various modules and licenses.
- * The "NOTICE" text file is part of the distribution. Any derivative works
- * that you distribute must include a readable copy of the "NOTICE" text file.
- ******************************************************************************/
-/*
- * 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.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);
- }
- }
-}
|