diff options
author | Thomas Lenz <tlenz@iaik.tugraz.at> | 2016-02-15 18:12:06 +0100 |
---|---|---|
committer | Thomas Lenz <tlenz@iaik.tugraz.at> | 2016-02-15 18:12:06 +0100 |
commit | 1b7401488933f031a68dfe929b25db86279b52d2 (patch) | |
tree | 5b6126d66845e97d962e080396b740b2935deb07 /id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth | |
parent | ff8ae7727e4de105a1179288b129429a29bc07ca (diff) | |
download | moa-id-spss-1b7401488933f031a68dfe929b25db86279b52d2.tar.gz moa-id-spss-1b7401488933f031a68dfe929b25db86279b52d2.tar.bz2 moa-id-spss-1b7401488933f031a68dfe929b25db86279b52d2.zip |
First untested part: Refactor authentication modules and process management to Spring
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth')
29 files changed, 1758 insertions, 1284 deletions
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 1f12675ca..a1ba00e02 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 @@ -3,6 +3,14 @@ package at.gv.egovernment.moa.id.auth; +import java.util.Date; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; @@ -13,22 +21,47 @@ import at.gv.egovernment.moa.logging.Logger; * @author Paul Ivancsics * @version $Id$ */ +@Service("AuthenticationSessionCleaner") public class AuthenticationSessionCleaner implements Runnable { + @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; + @Autowired private ITransactionStorage transactionStorage; + @Autowired protected AuthConfiguration authConfig; + /** interval the <code>AuthenticationSessionCleaner</code> is run in */ private static final long SESSION_CLEANUP_INTERVAL = 5 * 60; // 5 min /** * Runs the thread. Cleans the <code>AuthenticationServer</code> session store * and authentication data store from garbage, then sleeps for given interval, and restarts. + * + * Cleans up expired session and authentication data stores. + * */ public void run() { while (true) { try { Logger.debug("AuthenticationSessionCleaner run"); - BaseAuthenticationServer.cleanup(); - } - catch (Exception e) { + Date now = new Date(); + + try { + int sessionTimeOutCreated = authConfig.getSSOCreatedTimeOut() * 1000; + int sessionTimeOutUpdated = authConfig.getSSOUpdatedTimeOut() * 1000; + int authDataTimeOut = authConfig.getTransactionTimeOut() * 1000; + + //clean AuthenticationSessionStore + authenticationSessionStorage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); + + //clean TransactionStorage + transactionStorage.clean(now, authDataTimeOut); + + + } catch (Exception e) { + Logger.error("Session cleanUp FAILED!" , e); + + } + + } catch (Exception e) { Logger.error(MOAIDMessageProvider.getInstance().getMessage("cleaner.01", null), e); } try { @@ -42,10 +75,10 @@ public class AuthenticationSessionCleaner implements Runnable { /** * start the sessionCleaner */ - public static void start() { + public static void start(Runnable clazz) { // start the session cleanup thread Thread sessionCleaner = - new Thread(new AuthenticationSessionCleaner(), "AuthenticationSessionCleaner"); + new Thread(clazz, "AuthenticationSessionCleaner"); sessionCleaner.setName("SessionCleaner"); sessionCleaner.setDaemon(true); sessionCleaner.setPriority(Thread.MIN_PRIORITY); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java index 5e3b6653b..1ce6fa1e9 100644 --- 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 @@ -1,37 +1,13 @@ 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 org.springframework.beans.factory.annotation.Autowired; 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; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; /** * API for MOA ID Authentication Service.<br> {@link AuthenticationSession} is @@ -43,6 +19,9 @@ import at.gv.util.xsd.srzgw.MISType.Filters; */ public abstract class BaseAuthenticationServer extends MOAIDAuthConstants { + @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; + @Autowired protected AuthConfiguration authConfig; + /** * Retrieves a session from the session store. * @@ -50,11 +29,11 @@ public abstract class BaseAuthenticationServer extends MOAIDAuthConstants { * @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) + public AuthenticationSession getSession(String id) throws AuthenticationException { AuthenticationSession session; try { - session = AuthenticationSessionStoreage.getSession(id); + session = authenticationSessionStorage.getSession(id); if (session == null) throw new AuthenticationException("auth.02", new Object[]{id}); @@ -68,33 +47,4 @@ public abstract class BaseAuthenticationServer extends MOAIDAuthConstants { } } - /** - * 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 fa30f9ffd..082ebcdcd 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 @@ -10,8 +10,6 @@ import java.util.List; import java.util.Map; import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import at.gv.egovernment.moa.id.commons.config.persistence.MOAIDConfiguration; - import iaik.asn1.ObjectID; @@ -35,6 +33,7 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String PARAM_ACTION = "ACTION"; public static final String PARAM_SSO = "SSO"; public static final String INTERFEDERATION_IDP = "interIDP"; + public static final String PARAM_TARGET_PENDINGREQUESTID = "pendingid"; public static final String PARAM_SLOSTATUS = "status"; public static final String PARAM_SLORESTART = "restart"; @@ -130,6 +129,8 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String REQ_BKU_TYPE_HANDY = "handy"; public static final List<String> REQ_BKU_TYPES = Arrays.asList(REQ_BKU_TYPE_LOCAL, REQ_BKU_TYPE_ONLINE, REQ_BKU_TYPE_HANDY); + public static final List<String> LEGACYPARAMETERWHITELIST + = Arrays.asList(PARAM_TARGET, PARAM_BKU, PARAM_OA, PARAM_TEMPLATE, PARAM_USEMANDATE, PARAM_CCC, PARAM_SOURCEID); public final static String EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION = "OIDTextualDescription"; public final static String EXT_SAML_MANDATE_OID = "OID"; 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 4a004cdf0..5968736f8 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 @@ -223,7 +223,6 @@ public class MOAIDAuthInitializer implements WebApplicationInitializer { // Initialize configuration provider AuthConfiguration authConf = AuthConfigurationProviderFactory.reload(rootContext); - //test, if MOA-ID is already configured authConf.getPublicURLPrefix(); @@ -245,7 +244,9 @@ public class MOAIDAuthInitializer implements WebApplicationInitializer { // Starts the session cleaner thread to remove unpicked authentication data - AuthenticationSessionCleaner.start(); + AuthenticationSessionCleaner sessioncleaner = rootContext.getBean("AuthenticationSessionCleaner", AuthenticationSessionCleaner.class); + AuthenticationSessionCleaner.start(sessioncleaner); + MOAGarbageCollector.start(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java index 06a1f0936..a82a958db 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java @@ -40,8 +40,10 @@ public class MOAIDAuthSpringResourceProvider implements SpringResourceProvider { public Resource[] getResourcesToLoad() { ClassPathResource moaidauthConfig = new ClassPathResource("/moaid.configuration.beans.xml", MOAIDAuthSpringResourceProvider.class); ClassPathResource configurationDBConfig = new ClassPathResource("/configuration.beans.xml", MOAIDAuthSpringResourceProvider.class); - - return new Resource[] {configurationDBConfig, moaidauthConfig}; + ClassPathResource moaIdAuthBeans = new ClassPathResource("/moaid.authentication.beans.xml", MOAIDAuthSpringResourceProvider.class); + + return new Resource[] {configurationDBConfig, moaidauthConfig, moaIdAuthBeans}; + } /* (non-Javadoc) 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 fe29dd2b7..5bde82899 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 @@ -22,8 +22,6 @@ */ package at.gv.egovernment.moa.id.auth.builder; -import iaik.x509.X509Certificate; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -51,6 +49,8 @@ import org.opensaml.saml2.core.Response; import org.opensaml.ws.soap.common.SOAPException; import org.opensaml.xml.XMLObject; import org.opensaml.xml.security.SecurityException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -81,7 +81,6 @@ import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; 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.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.data.AuthenticationData; @@ -89,6 +88,7 @@ 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.moduls.RequestImpl; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; @@ -96,11 +96,12 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExt import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; 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.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; @@ -114,14 +115,19 @@ import at.gv.util.config.EgovUtilPropertiesConfiguration; import at.gv.util.ex.EgovUtilException; import at.gv.util.wsdl.szr.SZRException; import at.gv.util.xsd.szr.PersonInfoType; +import iaik.x509.X509Certificate; /** * @author tlenz * */ +@Service("AuthenticationDataBuilder") public class AuthenticationDataBuilder extends MOAIDAuthConstants { - public static IAuthData buildAuthenticationData(IRequest protocolRequest, + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; + @Autowired protected AuthConfiguration authConfig; + + public IAuthData buildAuthenticationData(IRequest protocolRequest, AuthenticationSession session, List<Attribute> reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { @@ -166,7 +172,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } //reuse some parameters if it is a reauthentication - OASessionStore activeOA = AuthenticationSessionStoreage.searchActiveOASSOSession(session, oaID, protocolRequest.requestedModule()); + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, oaID, protocolRequest.requestedModule()); if (activeOA != null) { authdata.setSessionIndex(activeOA.getAssertionSessionID()); authdata.setNameID(activeOA.getUserNameID()); @@ -187,13 +193,12 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } - InterfederationSessionStore interfIDP = AuthenticationSessionStoreage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); + InterfederationSessionStore interfIDP = authenticatedSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); IOAAuthParameters oaParam = null; if (reqAttributes == null) { //get OnlineApplication from MOA-ID-Auth configuration - oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(oaID); + oaParam = authConfig.getOnlineApplicationParameter(oaID); //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway if (oaParam.isSTORKPVPGateway()) @@ -215,7 +220,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } else { //get attributes from interfederated IDP - OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(interfIDP.getIdpurlprefix()); + OAAuthParameter idp = authConfig.getOnlineApplicationParameter(interfIDP.getIdpurlprefix()); getAuthDataFromInterfederation(authdata, session, oaParam, protocolRequest, interfIDP, idp, reqAttributes); //mark attribute request as used @@ -248,7 +253,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * @throws BuildException * @throws DynamicOABuildException */ - public static IAuthData buildAuthenticationData(IRequest req, + public IAuthData buildAuthenticationData(IRequest req, AuthenticationSession session) throws WrongParametersException, ConfigurationException, BuildException, DynamicOABuildException { return buildAuthenticationData(req, session, null); } @@ -263,7 +268,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * @param reqQueryAttr * @throws ConfigurationException */ - private static void getAuthDataFromInterfederation( + private void getAuthDataFromInterfederation( AuthenticationData authdata, AuthenticationSession session, IOAAuthParameters oaParam, IRequest req, InterfederationSessionStore interfIDP, OAAuthParameter idp, List<Attribute> reqQueryAttr) throws BuildException, ConfigurationException{ @@ -280,11 +285,13 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //IDP is a service provider IDP and request interfederated IDP to collect attributes } else { //get PVP 2.1 attributes from protocol specific requested attributes - attributs = req.getRequestedAttributes(); + attributs = (List<Attribute>) req.getGenericData(RequestImpl.DATAID_REQUESTED_ATTRIBUTES); } - Response intfResp = (Response) req.getInterfederationResponse().getResponse(); + Response intfResp = + (Response) req.getGenericData( + RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, MOAResponse.class).getResponse(); AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(intfResp); @@ -362,7 +369,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } - private static void buildAuthDataFormInterfederationResponse( + private void buildAuthDataFormInterfederationResponse( AuthenticationData authData, AuthenticationSession session, AssertionAttributeExtractor extractor, @@ -500,7 +507,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { if (MiscUtil.isEmpty(authData.getIdentificationValue())) { Logger.info("No baseID found. Connect SZR to reveive baseID ..."); try { - EgovUtilPropertiesConfiguration eGovClientsConfig = AuthConfigurationProviderFactory.getInstance().geteGovUtilsConfig(); + EgovUtilPropertiesConfiguration eGovClientsConfig = authConfig.geteGovUtilsConfig(); if (eGovClientsConfig != null) { SZRClient szrclient = new SZRClient(eGovClientsConfig); @@ -534,11 +541,6 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } - } catch (ConfigurationException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); - } catch (EgovUtilException e) { Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME @@ -843,7 +845,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * @param authData * @return */ - private static boolean matchsReceivedbPKToOnlineApplication( + private boolean matchsReceivedbPKToOnlineApplication( IOAAuthParameters oaParam, AuthenticationData authData) { String oaTarget = null; @@ -870,7 +872,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { return false; } - private static void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, + private void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { IdentityLink identityLink = session.getIdentityLink(); @@ -964,11 +966,11 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } try { - authData.setSsoSession(AuthenticationSessionStoreage.isSSOSession(session.getSessionID())); + authData.setSsoSession(protocolRequest.needSingleSignOnFunctionality()); //set max. SSO session time if (authData.isSsoSession()) { - long maxSSOSessionTime = AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut() * 1000; + long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; Date ssoSessionValidTo = new Date(session.getSessionCreated().getTime() + maxSSOSessionTime); authData.setSsoSessionValidTo(ssoSessionValidTo); @@ -1016,7 +1018,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } - private static void buildOAspecificIdentityLink(IOAAuthParameters oaParam, AuthenticationData authData, IdentityLink idl) throws MOAIDException { + private void buildOAspecificIdentityLink(IOAAuthParameters oaParam, AuthenticationData authData, IdentityLink idl) throws MOAIDException { if (oaParam.getBusinessService()) { Element idlassertion = idl.getSamlAssertion(); //set bpk/wpbk; @@ -1033,9 +1035,8 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); Element resignedilAssertion; - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - if (config.isIdentityLinkResigning()) { - resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), config.getIdentityLinkResigningKey()); + if (authConfig.isIdentityLinkResigning()) { + resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), authConfig.getIdentityLinkResigningKey()); } else { resignedilAssertion = businessServiceIdl.getSamlAssertion(); } @@ -1050,7 +1051,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } - private static void buildOAspecificbPK(IRequest protocolRequest, IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { + private void buildOAspecificbPK(IRequest protocolRequest, IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { if (oaParam.getBusinessService()) { //since we have foreigner, wbPK is not calculated in BKU @@ -1082,7 +1083,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } if (saml1Requst != null && protocolRequest.getClass().isInstance(saml1Requst)) - target = protocolRequest.getTarget(); + target = protocolRequest.getGenericData("target", String.class); else target = oaParam.getTarget(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DataURLBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DataURLBuilder.java index d4350f97b..9a2baf873 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DataURLBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DataURLBuilder.java @@ -47,7 +47,6 @@ package at.gv.egovernment.moa.id.auth.builder; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; /** * Builds a DataURL parameter meant for the security layer implementation @@ -76,31 +75,13 @@ public class DataURLBuilder { * @return String */ public String buildDataURL(String authBaseURL, String authServletName, String sessionID) { - -// String individualDataURLPrefix = null; - String dataURL; - - //is removed from config in MOA-ID 2.0 - //check if an individual prefix is configured -// individualDataURLPrefix = AuthConfigurationProvider.getInstance(). -// getGenericConfigurationParameter(AuthConfigurationProvider.INDIVIDUAL_DATA_URL_PREFIX); -// -// if (null != individualDataURLPrefix) { -// -// //check individualDataURLPrefix -// if(!individualDataURLPrefix.startsWith("http")) -// throw(new ConfigurationException("config.13", new Object[] { individualDataURLPrefix})); -// -// //when ok then use it -// dataURL = individualDataURLPrefix + authServletName; -// } else - + String dataURL; if (!authBaseURL.endsWith("/")) authBaseURL += "/"; dataURL = authBaseURL + authServletName; - dataURL = addParameter(dataURL, MOAIDAuthConstants.PARAM_SESSIONID, sessionID); + dataURL = addParameter(dataURL, MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, sessionID); return dataURL; } 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 99ba49d26..c22432d0d 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 @@ -36,7 +36,6 @@ import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; 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.stork.CPEPS; import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.logging.Logger; @@ -119,7 +118,7 @@ public class LoginFormBuilder { return template; } - public static String buildLoginForm(String modul, String action, OAAuthParameter oaParam, String contextpath, String moaSessionID) { + public static String buildLoginForm(String modul, String action, IOAAuthParameters oaParam, String contextpath, String moaSessionID) { String value = null; 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 ae3ec9a9b..3849eb8a2 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 @@ -36,8 +36,6 @@ package at.gv.egovernment.moa.id.auth.data; -import iaik.x509.X509Certificate; - import java.io.Serializable; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; @@ -53,6 +51,7 @@ 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.MiscUtil; +import iaik.x509.X509Certificate; /** * Session data to be stored between <code>AuthenticationServer</code> API calls. @@ -218,16 +217,7 @@ public class AuthenticationSession implements Serializable { */ private String pushInfobox; - // private AuthenticationData authData; - - // protocol selection - private String action; - private String modul; - - private String processInstanceId; - private boolean authenticated; - private boolean authenticatedUsed = false; private boolean ssoRequested = false; @@ -238,31 +228,7 @@ public class AuthenticationSession implements Serializable { private boolean isForeigner; private Map<String, Object> genericSessionDataStorate = new HashedMap<String, Object>(); - - public String getModul() { - return modul; - } - - public void setModul(String modul) { - this.modul = modul; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - public boolean isAuthenticatedUsed() { - return authenticatedUsed; - } - - public void setAuthenticatedUsed(boolean authenticatedUsed) { - this.authenticatedUsed = authenticatedUsed; - } - public boolean isAuthenticated() { return authenticated; } @@ -852,22 +818,6 @@ public class AuthenticationSession implements Serializable { return sessionCreated; } - /** - * Returns the identifier of the process instance associated with this moaid session. - * @return The process instance id (may be {@code null} if no process has been created yet). - */ - public String getProcessInstanceId() { - return processInstanceId; - } - - /** - * Sets the process instance identifier in order to associate a certain process instance with this moaid session. - * @param processInstanceId The process instance id. - */ - public void setProcessInstanceId(String processInstanceId) { - this.processInstanceId = processInstanceId; - } - public Map<String, Object> getGenericSessionDataStorage() { return genericSessionDataStorate; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java index 67ddd170a..a73fd6858 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java @@ -1,6 +1,12 @@ package at.gv.egovernment.moa.id.auth.modules;
-import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*;
+import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_CACHE_CONTROL;
+import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_EXPIRES;
+import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_PRAGMA;
+import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL;
+import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE;
+import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_EXPIRES;
+import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_PRAGMA;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -24,17 +30,23 @@ import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.ArrayUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger;
+import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
-import at.gv.egovernment.moa.id.auth.servlet.AuthServlet;
+import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
import at.gv.egovernment.moa.id.config.ConfigurationException;
-import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet;
+import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
+import at.gv.egovernment.moa.id.moduls.IRequestStorage;
import at.gv.egovernment.moa.id.process.springweb.MoaIdTask;
-import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl;
-import at.gv.egovernment.moa.id.storage.IExceptionStore;
+import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController;
+import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage;
+import at.gv.egovernment.moa.id.storage.ITransactionStorage;
+import at.gv.egovernment.moa.id.util.Random;
import at.gv.egovernment.moa.id.util.ServletUtils;
import at.gv.egovernment.moa.logging.Logger;
import at.gv.egovernment.moa.util.MiscUtil;
@@ -45,6 +57,13 @@ import at.gv.egovernment.moa.util.MiscUtil; */
public abstract class AbstractAuthServletTask extends MoaIdTask {
+ @Autowired private StatisticLogger statisticLogger;
+ @Autowired private ITransactionStorage transactionStorage;
+ @Autowired protected IRequestStorage requestStoreage;
+ @Autowired protected IAuthenticationSessionStoreage authenticatedSessionStorage;
+ @Autowired protected MOAReversionLogger revisionsLogger;
+ @Autowired protected AuthConfiguration authConfig;
+
protected static final String ERROR_CODE_PARAM = "errorid";
protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown,
@@ -66,11 +85,8 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { req.setAttribute("LogLevel", "debug");
}
-
- StatisticLogger logger = StatisticLogger.getInstance();
- logger.logErrorOperation(exceptionThrown);
-
-
+ statisticLogger.logErrorOperation(exceptionThrown);
+
// forward this to errorpage-auth.jsp where the HTML error page is
// generated
ServletContext context = req.getServletContext();
@@ -132,31 +148,42 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown);
}
+
- IExceptionStore store = DBExceptionStoreImpl.getStore();
- String id = store.storeException(exceptionThrown);
-
- if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) {
-
- String redirectURL = null;
-
- redirectURL = ServletUtils.getBaseUrl(req);
- redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id
- + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID;
-
- resp.setContentType("text/html");
- resp.setStatus(302);
-
- resp.addHeader("Location", redirectURL);
- Logger.debug("REDIRECT TO: " + redirectURL);
-
- return;
+ try {
+ String key = Random.nextRandom();
+ transactionStorage.put(key, exceptionThrown);
- } else {
+ if (key != null && MiscUtil.isNotEmpty(pendingRequestID)) {
+ String redirectURL = null;
+
+ redirectURL = ServletUtils.getBaseUrl(req) + "/";
+ redirectURL += AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT
+ + "?" + ERROR_CODE_PARAM + "=" + key
+ + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID;
- //Exception can not be stored in database
+ resp.setContentType("text/html");
+ resp.setStatus(302);
+
+ resp.addHeader("Location", redirectURL);
+ Logger.debug("REDIRECT TO: " + redirectURL);
+
+ return;
+
+ } else {
+ //Exception can not be stored in database
+ handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp);
+ }
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("Exception can not be stored to Database.", e);
handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp);
+
}
+
+
+
+
}
/**
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java new file mode 100644 index 000000000..8b02a5bf6 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java @@ -0,0 +1,68 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules; + +import at.gv.egovernment.moa.id.process.api.ExecutionContext; + +/** + * @author tlenz + * + */ +public class BKUSelectionModuleImpl implements AuthModule { + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getPriority() + */ + @Override + public int getPriority() { + return 0; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process.api.ExecutionContext) + */ + @Override + public String selectProcess(ExecutionContext context) { + boolean performBKUSelection = false; + Object performBKUSelectionObj = context.get("performBKUSelection"); + if (performBKUSelectionObj != null && performBKUSelectionObj instanceof Boolean) + performBKUSelection = (boolean) performBKUSelectionObj; + + if (performBKUSelection) + return "BKUSelectionProcess"; + + else + return null; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() + */ + @Override + public String[] getProcessDefinitions() { + return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/internal/BKUSelection.process.xml" }; + + } + +} 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 index 4a6ecd56a..f1ab58ee0 100644 --- 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 @@ -44,9 +44,9 @@ 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 org.springframework.stereotype.Service; 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; @@ -55,13 +55,12 @@ 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.moduls.RequestImpl; 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; @@ -73,6 +72,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ +@Service("CreateInterfedeartionRequestTask") public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { /* (non-Javadoc) @@ -84,8 +84,8 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { throws TaskExecutionException { boolean requiredLocalAuthentication = true; - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); + IRequest pendingReq = requestStoreage.getPendingRequest( + (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); String idpEntityID = (String) executionContext.get(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID); @@ -105,8 +105,10 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(idpEntityID); OAAuthParameter sp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(pendingReq.getOAURL()); + String requestedIDP = pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { - Logger.info("Requested interfederation IDP " + pendingReq.getRequestedIDP() + " is not valid for interfederation."); + Logger.info("Requested interfederation IDP " + requestedIDP + " 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 ... "); @@ -252,18 +254,18 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { //build and send request without an error requiredLocalAuthentication = false; - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_IDP, idpEntity.getEntityID()); } else { - Logger.warn("Requested IDP " + pendingReq.getRequestedIDP() + Logger.warn("Requested IDP " + requestedIDP + " does not support POST or Redirect Binding."); } } else { - Logger.warn("Requested IDP " + pendingReq.getRequestedIDP() + Logger.warn("Requested IDP " + requestedIDP + " is not found in InterFederation configuration"); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java new file mode 100644 index 000000000..fe3e8680c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java @@ -0,0 +1,119 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import java.util.Enumeration; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.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.process.api.ExecutionContext; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +@Service("EvaluateBKUSelectionTask") +public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try { + //load pending request + String pendingReqID = request.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); + pendingReqID = StringEscapeUtils.escapeHtml(pendingReqID); + IRequest pendingReq = requestStoreage.getPendingRequest(pendingReqID); + + if (pendingReq == null) { + Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); + throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); + + } + + //change pending-request ID + String newPendingRequestID = requestStoreage.changePendingRequestID(pendingReq); + executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, newPendingRequestID); + + AuthenticationSession moaSession = null; + String moaSessionID = pendingReq.getMOASessionIdentifier(); + try { + moaSession = authenticatedSessionStorage.getSession(moaSessionID); + + if (moaSession == null) { + Logger.info("MOASession with SessionID="+ moaSessionID + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { + moaSessionID}); + + } + + // set parameter execution context + Enumeration<String> reqParamNames = request.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (MiscUtil.isNotEmpty(paramName)) + executionContext.put(paramName, request.getParameter(paramName)); + + } + + Logger.info("BKU is selected finished -> Start BKU communication ..."); + + } 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[] {}); + } + + + + + } catch (MOAIDException e) { + throw new TaskExecutionException(e.getMessage(), e); + + } catch (Exception e) { + Logger.warn("EvaluateBKUSelectionTask has an internal 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/FinalizeAuthenticationTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java index 712ebb731..ed309d85a 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 @@ -22,11 +22,12 @@ */ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -34,10 +35,9 @@ 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.ModulUtils; -import at.gv.egovernment.moa.id.moduls.RequestStorage; +import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -45,6 +45,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ +@Service("FinalizeAuthenticationTask") public class FinalizeAuthenticationTask extends AbstractAuthServletTask { /* (non-Javadoc) @@ -56,8 +57,8 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { throws TaskExecutionException { try { - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); + IRequest pendingReq = requestStoreage.getPendingRequest( + (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); if (pendingReq == null) { Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); @@ -66,7 +67,7 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { } //get Session from context - String moasessionid = (String) executionContext.get(PARAM_SESSIONID); + String moasessionid = pendingReq.getMOASessionIdentifier(); AuthenticationSession session = null; if (MiscUtil.isEmpty(moasessionid)) { Logger.warn("MOASessionID is empty."); @@ -74,9 +75,14 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { } try { - session = AuthenticationSessionStoreage.getSession(moasessionid); - AuthenticationSessionStoreage.changeSessionID(session); - + session = authenticatedSessionStorage.getSession(moasessionid); + if (session == null) { + Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { moasessionid }); + + } + + } catch (MOADatabaseException e) { Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); throw new MOAIDException("init.04", new Object[] { moasessionid }); @@ -86,25 +92,25 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { throw new MOAIDException("auth.18", new Object[] {}); } finally { - executionContext.remove(PARAM_SESSIONID); + executionContext.remove(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID); } - - session.setAuthenticatedUsed(false); - session.setAuthenticated(true); - - String oldsessionID = session.getSessionID(); + //set MOASession to authenticated and store MOASession + session.setAuthenticated(true); + String newMOASessionID = authenticatedSessionStorage.changeSessionID(session); - //Session is implicte stored in changeSessionID!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + //set pendingRequest to authenticated and set new MOASessionID + ((RequestImpl)pendingReq).setMOASessionIdentifier(newMOASessionID); + pendingReq.setAuthenticated(true); + requestStoreage.storePendingRequest(pendingReq); Logger.info("AuthProcess finished. Redirect to Protocol Dispatcher."); - String redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(pendingReq.requestedModule(), pendingReq.requestedAction(), pendingReq.getRequestID()), newMOASessionID); - + String redirectURL = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), + AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT, pendingReq.getRequestID()); + response.setContentType("text/html"); response.setStatus(302); response.addHeader("Location", redirectURL); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java new file mode 100644 index 000000000..1bdc132d9 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java @@ -0,0 +1,102 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of 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.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Service("GenerateBKUSelectionFrameTask") +public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try { + IRequest pendingReq = requestStoreage.getPendingRequest( + (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); + + if (pendingReq == null) { + Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); + throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); + + } + + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUSELECTION_INIT); + + //load Parameters from OnlineApplicationConfiguration + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + + if (oaParam == null) { + throw new AuthenticationException("auth.00", new Object[] { pendingReq.getOAURL() }); + + } + + //Build authentication form + String publicURLPreFix = pendingReq.getAuthURL(); + if (publicURLPreFix.endsWith("/")) + publicURLPreFix = publicURLPreFix.substring(0, publicURLPreFix.length() - 1); + String loginForm = LoginFormBuilder.buildLoginForm(pendingReq.requestedModule(), + pendingReq.requestedAction(), oaParam, publicURLPreFix, MOAIDAuthConstants.PARAM_SESSIONID); + + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.print(loginForm); + out.flush(); + + + } catch (MOAIDException e) { + throw new TaskExecutionException(e.getMessage(), e); + + } catch (Exception e) { + Logger.warn("FinalizeAuthenticationTask has an internal 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/ReceiveInterfederationResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java index f05ff07e9..77aab8ddb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java @@ -25,6 +25,8 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Service; + 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; @@ -33,6 +35,7 @@ import at.gv.egovernment.moa.id.process.api.ExecutionContext; * @author tlenz * */ +@Service("ReceiveInterfederationResponseTask") public class ReceiveInterfederationResponseTask extends AbstractAuthServletTask { /* (non-Javadoc) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java new file mode 100644 index 000000000..d8b558846 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java @@ -0,0 +1,123 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +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.auth.modules.registration.ModuleRegistration; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.process.ExecutionContextImpl; +import at.gv.egovernment.moa.id.process.ProcessEngine; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Service("RestartAuthProzessManagement") +public class RestartAuthProzessManagement extends AbstractAuthServletTask { + + @Autowired ProcessEngine processEngine; + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try { + IRequest pendingReq = requestStoreage.getPendingRequest( + (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); + + if (pendingReq == null) { + Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); + throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); + + } + + //create a new execution context and copy all elements to new context + ExecutionContext newec = new ExecutionContextImpl(); + Set<String> entries = executionContext.keySet(); + for (String key : entries) { + newec.put(key, executionContext.get(key)); + + } + + //remove BKU selection flag + newec.remove("performBKUSelection"); + + + Logger.debug("Swicht to specific authentication process after BKU is selected"); + + // select and create new process instance + String processDefinitionId = ModuleRegistration.getInstance().selectProcess(newec); + if (processDefinitionId == null) { + Logger.warn("No suitable authentication process found for SessionID " + pendingReq.getRequestID()); + throw new MOAIDException("process.02", new Object[] { pendingReq.getRequestID() }); + } + + String processInstanceId = processEngine.createProcessInstance(processDefinitionId, newec); + + // keep process instance id in moa session + ((RequestImpl)pendingReq).setProcessInstanceId(processInstanceId); + + // make sure pending request has been persisted before running the process + try { + requestStoreage.storePendingRequest(pendingReq); + + } catch (MOAIDException e) { + Logger.error("Database Error! MOASession is not stored!"); + throw new MOAIDException("init.04", new Object[] { pendingReq.getRequestID() }); + + } + + Logger.info("BKU is selected -> Start BKU communication ..."); + + // start process + processEngine.start(processInstanceId); + + + } catch (MOAIDException e) { + throw new TaskExecutionException(e.getMessage(), e); + + } catch (Exception e) { + Logger.warn("RestartAuthProzessManagement has an internal error", e); + throw new TaskExecutionException(e.getMessage(), e); + + } + + } + +} 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 e659c9447..8af8ed238 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 @@ -25,7 +25,6 @@ package at.gv.egovernment.moa.id.auth.parser; import java.util.List; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; @@ -54,8 +53,6 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ String templateURL, String useMandate, String ccc, - String module, - String action, HttpServletRequest req, IRequest protocolReq) throws WrongParametersException, MOAIDException { @@ -129,7 +126,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ if (!oaParam.getBusinessService()) { if (StringUtils.isEmpty(targetConfig) - || (module.equals("id_saml1") && + || (protocolReq.requestedModule().equals("at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol") && !StringUtils.isEmpty(target)) ) { //INFO: ONLY SAML1 legacy mode @@ -278,25 +275,8 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ public static void parse(ExecutionContext ec, HttpServletRequest req, AuthenticationSession moasession, IRequest request) throws WrongParametersException, MOAIDException { - - - String modul = request.requestedModule();//req.getParameter(PARAM_MODUL); - String action = request.requestedAction();//req.getParameter(PARAM_ACTION); - - modul = StringEscapeUtils.escapeHtml(modul); - action = StringEscapeUtils.escapeHtml(action); -// if(modul == null) { -// modul = SAML1Protocol.PATH; -// } -// -// if(action == null) { -// action = SAML1Protocol.GETARTIFACT; -// } - moasession.setModul(modul); - moasession.setAction(action); - + //get Parameters from request - 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); @@ -312,9 +292,11 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ } oaURL = request.getOAURL(); - target = request.getTarget(); + + //only needed for SAML1 + String target = request.getGenericData("target", String.class); - parse(moasession, target, oaURL, bkuURL, templateURL, useMandate, ccc, modul, action, req, request); + parse(moasession, target, oaURL, bkuURL, templateURL, useMandate, ccc, req, request); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java new file mode 100644 index 000000000..26e24f5b4 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -0,0 +1,238 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.servlet; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; +import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; +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.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.moduls.IRequestStorage; +import at.gv.egovernment.moa.id.process.ProcessExecutionException; +import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; +import at.gv.egovernment.moa.id.util.ErrorResponseUtils; +import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +public abstract class AbstractController extends MOAIDAuthConstants { + + public static final String ERROR_CODE_PARAM = "errorid"; + + @Autowired protected StatisticLogger statisticLogger; + @Autowired protected IRequestStorage requestStorage; + @Autowired protected ITransactionStorage transactionStorage; + @Autowired protected MOAReversionLogger revisionsLogger; + @Autowired protected AuthConfiguration authConfig; + + + protected void handleError(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) throws IOException { + + Throwable loggedException = null; + + if (exceptionThrown != null + && exceptionThrown instanceof ProcessExecutionException) { + ProcessExecutionException procExc = + (ProcessExecutionException) exceptionThrown; + if (procExc.getCause() != null && + procExc.getCause() instanceof TaskExecutionException) { + TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); + loggedException = taskExc.getOriginalException(); + + } + } + + if (loggedException == null) + loggedException = exceptionThrown; + + + if (!(loggedException instanceof MOAIDException)) { + Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); + + } else { + if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { + Logger.error(loggedException.getMessage(), loggedException); + + } else { + Logger.error(loggedException.getMessage()); + + } + } + + //store error into transaction store + try { + String key = Random.nextRandom(); + transactionStorage.put(key, exceptionThrown); + + if (key != null && MiscUtil.isNotEmpty(pendingRequestID)) { + String redirectURL = null; + + redirectURL = ServletUtils.getBaseUrl(req); + redirectURL += AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT + + "?" + ERROR_CODE_PARAM + "=" + key + + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + return; + + } else { + //Exception can not be stored in database + handleErrorNoRedirect(loggedException, req, resp); + + } + + } catch (MOADatabaseException e) { + Logger.warn("Exception can not be stored to Database.", e); + handleErrorNoRedirect(loggedException, req, resp); + + } + + + } + + + /** + * Handles all exceptions with no pending request. + * Therefore, the error is written to the users browser + * + * @param throwable + * @param req + * @param resp + * @throws IOException + */ + protected void handleErrorNoRedirect(Throwable throwable, HttpServletRequest req, + HttpServletResponse resp) throws IOException { + + //log Exception into statistic database + statisticLogger.logErrorOperation(throwable); + + //write errror to console + Logger.error(throwable.getMessage(), throwable); + + //return error to Web browser + if (throwable instanceof MOAIDException) + MOAIDExceptionHandler(req, resp, (MOAIDException)throwable); + + else + GenericExceptionHandler(req, resp, (Exception)throwable); + } + + @ExceptionHandler({MOAIDException.class}) + public void MOAIDExceptionHandler(HttpServletRequest req, HttpServletResponse resp, MOAIDException e) throws IOException { + if (e instanceof ProtocolNotActiveException) { + resp.getWriter().write(e.getMessage()); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); + return; + + } else if (e instanceof AuthnRequestValidatorException) { + AuthnRequestValidatorException ex = (AuthnRequestValidatorException)e; + //log Error Message + statisticLogger.logErrorOperation(ex, ex.getErrorRequest()); + return; + + } else if (e instanceof InvalidProtocolRequestException) { + //write log entry + String samlRequest = req.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + + //send error response + ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); + String code = utils.mapInternalErrorToExternalError(e.getMessageId()); + String descr = e.getMessage(); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Protocol validation FAILED!" + + "(Errorcode=" + code + + " | Description=" + descr + ")"); + return; + } else if (e instanceof ConfigurationException) { + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + + "(Errorcode=9199" + +" | Description="+ e.getMessage() + ")"); + return; + + //TODO: check exception type + } else if (e instanceof MOAIDException) { + String samlRequest = req.getParameter("SAMLRequest"); + if (MiscUtil.isNotEmpty(samlRequest)) + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + else + Logger.error("Failed to generate a valid protocol request!"); + + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + + "(Errorcode=6000" + +" | Description=Das Authentifizierungsprotokoll wurde nicht erkannt oder wird nicht unterst\u00FCzt" + ")"); + return; + + } + + } + + @ExceptionHandler({Exception.class}) + public void GenericExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception exception) throws IOException { + Logger.error("Internel Server Error." , exception); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + + "(Errorcode=9199" + +" | Description="+ exception.getMessage() + ")"); + return; + + } + + @ExceptionHandler({IOException.class}) + public void IOExceptionHandler(HttpServletRequest req, HttpServletResponse resp, IOException exception) { + Logger.error("Internel Server Error." , exception); + resp.setContentType("text/html;charset=UTF-8"); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractProcessEngineSignalController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractProcessEngineSignalController.java new file mode 100644 index 000000000..375afca4d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractProcessEngineSignalController.java @@ -0,0 +1,84 @@ +package at.gv.egovernment.moa.id.auth.servlet;
+
+import java.io.IOException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang.StringEscapeUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils;
+import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
+import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.process.ProcessEngine;
+import at.gv.egovernment.moa.logging.Logger;
+
+/**
+ * Servlet that resumes a suspended process (in case of asynchronous tasks).
+ *
+ * @author tknall
+ *
+ */
+public abstract class AbstractProcessEngineSignalController extends AbstractController {
+
+ @Autowired ProcessEngine processEngine;
+
+ protected void signalProcessManagement(HttpServletRequest req, HttpServletResponse resp) throws IOException {
+ String pendingRequestID = StringEscapeUtils.escapeHtml(getPendingRequestId(req));
+
+ try {
+ if (pendingRequestID == null) {
+ throw new IllegalStateException("Unable to determine MOA pending-request id.");
+ }
+
+ 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});
+
+ }
+
+ //add transactionID and unique sessionID to Logger
+ TransactionIDUtils.setSessionId(pendingReq.getUniqueSessionIdentifier());
+ TransactionIDUtils.setTransactionId(pendingReq.getUniqueTransactionIdentifier());
+
+ // process instance is mandatory
+ if (pendingReq.getProcessInstanceId() == null) {
+ throw new IllegalStateException("MOA session does not provide process instance id.");
+ }
+
+ // wake up next task
+ processEngine.signal(pendingReq.getProcessInstanceId());
+
+ } catch (Exception ex) {
+ handleError(null, ex, req, resp, pendingRequestID);
+
+ } finally {
+ //MOASessionDBUtils.closeSession();
+ TransactionIDUtils.removeTransactionId();
+ TransactionIDUtils.removeSessionId();
+
+ }
+
+
+ }
+
+ /**
+ * Retrieves the current pending-request id from the HttpServletRequest parameter
+ * {@link MOAIDAuthConstants#PARAM_TARGET_PENDINGREQUESTID}.
+ * <p/>
+ * Note that this class/method can be overwritten by modules providing their own strategy of retrieving the
+ * respective pending-request id.
+ *
+ * @param request
+ * The unterlying HttpServletRequest.
+ * @return The current pending-request id.
+ */
+ public String getPendingRequestId(HttpServletRequest request) {
+ return StringEscapeUtils.escapeHtml(request.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID));
+
+ }
+
+}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java index fe24d45dd..fb6c71846 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java @@ -1,507 +1,378 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - -package at.gv.egovernment.moa.id.auth.servlet; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileItemFactory; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.NoUniqueBeanDefinitionException; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - -import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; -import at.gv.egovernment.moa.id.process.ProcessEngine; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -import at.gv.egovernment.moa.id.storage.IExceptionStore; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.egovernment.moa.util.URLDecoder; - -/** - * Base class for MOA-ID Auth Servlets, providing standard error handling and - * constant names. - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class AuthServlet extends HttpServlet { - - /** - * - */ - private static final long serialVersionUID = -6929905344382283738L; - - protected static final String ERROR_CODE_PARAM = "errorid"; - - /** - * The process engine. - */ - private ProcessEngine processEngine; - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - Logger.debug("GET " + this.getServletName()); - - this.setNoCachingHeadersInHttpRespone(req, resp); - } - - protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp) { - - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); - } - - - StatisticLogger logger = StatisticLogger.getInstance(); - logger.logErrorOperation(exceptionThrown); - - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Handles an error. <br>> - * <ul> - * <li>Logs the error</li> - * <li>Places error message and exception thrown into the request as request - * attributes (to be used by <code>"/errorpage-auth.jsp"</code>)</li> - * <li>Sets HTTP status 500 (internal server error)</li> - * </ul> - * - * @param errorMessage - * error message - * @param exceptionThrown - * exception thrown - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleError(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { - - Throwable loggedException = null; - - if (exceptionThrown != null - && exceptionThrown instanceof ProcessExecutionException) { - ProcessExecutionException procExc = - (ProcessExecutionException) exceptionThrown; - if (procExc.getCause() != null && - procExc.getCause() instanceof TaskExecutionException) { - TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); - loggedException = taskExc.getOriginalException(); - - } - } - - if (loggedException == null) - loggedException = exceptionThrown; - - - if (!(loggedException instanceof MOAIDException)) { - Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); - - } else { - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { - Logger.error(loggedException.getMessage(), loggedException); - - } else { - Logger.error(loggedException.getMessage()); - - } - } - - IExceptionStore store = DBExceptionStoreImpl.getStore(); - String id = store.storeException(loggedException); - - if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { - - String redirectURL = null; - - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id - + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - return; - - } else { - - //Exception can not be stored in database - handleErrorNoRedirect(errorMessage, loggedException, req, resp); - } - } - - /** - * Handles a <code>WrongParametersException</code>. - * - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleWrongParameters(WrongParametersException ex, - HttpServletRequest req, HttpServletResponse resp) { - Logger.error(ex.toString()); - req.setAttribute("WrongParameters", ex.getMessage()); - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Logs all servlet parameters for debugging purposes. - */ - protected void logParameters(HttpServletRequest req) { - for (Enumeration params = req.getParameterNames(); params - .hasMoreElements();) { - String parname = (String) params.nextElement(); - Logger.debug("Parameter " + parname + req.getParameter(parname)); - } - } - - /** - * Parses the request input stream for parameters, assuming parameters are - * encoded UTF-8 (no standard exists how browsers should encode them). - * - * @param req - * servlet request - * - * @return mapping parameter name -> value - * - * @throws IOException - * if parsing request parameters fails. - * - * @throws FileUploadException - * if parsing request parameters fails. - */ - protected Map<String, String> getParameters(HttpServletRequest req) throws IOException, - FileUploadException { - - Map<String, String> parameters = new HashMap<String, String>(); - - if (ServletFileUpload.isMultipartContent(req)) { - // request is encoded as mulitpart/form-data - FileItemFactory factory = new DiskFileItemFactory(); - ServletFileUpload upload = null; - upload = new ServletFileUpload(factory); - List items = null; - items = upload.parseRequest(req); - for (int i = 0; i < items.size(); i++) { - FileItem item = (FileItem) items.get(i); - if (item.isFormField()) { - // Process only form fields - no file upload items - String logString = item.getString("UTF-8"); - - // TODO use RegExp - String startS = "<pr:Identification><pr:Value>"; - String endS = "</pr:Value><pr:Type>urn:publicid:gv.at:baseid</pr:Type>"; - String logWithMaskedBaseid = logString; - int start = logString.indexOf(startS); - if (start > -1) { - int end = logString.indexOf(endS); - if (end > -1) { - logWithMaskedBaseid = logString.substring(0, start); - logWithMaskedBaseid += startS; - logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx"; - logWithMaskedBaseid += logString.substring(end, - logString.length()); - } - } - parameters - .put(item.getFieldName(), item.getString("UTF-8")); - Logger.debug("Processed multipart/form-data request parameter: \nName: " - + item.getFieldName() - + "\nValue: " - + logWithMaskedBaseid); - } - } - } - - else { - // request is encoded as application/x-www-urlencoded - InputStream in = req.getInputStream(); - - String paramName; - String paramValueURLEncoded; - do { - paramName = new String(readBytesUpTo(in, '=')); - if (paramName.length() > 0) { - paramValueURLEncoded = readBytesUpTo(in, '&'); - String paramValue = URLDecoder.decode(paramValueURLEncoded, - "UTF-8"); - parameters.put(paramName, paramValue); - } - } while (paramName.length() > 0); - in.close(); - } - - return parameters; - } - - /** - * Reads bytes up to a delimiter, consuming the delimiter. - * - * @param in - * input stream - * @param delimiter - * delimiter character - * @return String constructed from the read bytes - * @throws IOException - */ - protected String readBytesUpTo(InputStream in, char delimiter) - throws IOException { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - boolean done = false; - int b; - while (!done && (b = in.read()) >= 0) { - if (b == delimiter) - done = true; - else - bout.write(b); - } - return bout.toString(); - } - - /** - * Calls the web application initializer. - * - * @see javax.servlet.Servlet#init(ServletConfig) - */ - public void init(ServletConfig servletConfig) throws ServletException { - super.init(servletConfig); - } - - -// public void contextDestroyed(ServletContextEvent arg0) { -// Security.removeProvider((new IAIK()).getName()); -// Security.removeProvider((new ECCProvider()).getName()); +///******************************************************************************* +// * Copyright 2014 Federal Chancellery Austria +// * MOA-ID has been developed in a cooperation between BRZ, the Federal +// * Chancellery Austria - ICT staff unit, and Graz University of Technology. +// * +// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by +// * the European Commission - subsequent versions of the EUPL (the "Licence"); +// * You may not use this work except in compliance with the Licence. +// * You may obtain a copy of the Licence at: +// * http://www.osor.eu/eupl/ +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the Licence is distributed on an "AS IS" basis, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the Licence for the specific language governing permissions and +// * limitations under the Licence. +// * +// * This product combines work with different licenses. See the "NOTICE" text +// * file for details on the various modules and licenses. +// * The "NOTICE" text file is part of the distribution. Any derivative works +// * that you distribute must include a readable copy of the "NOTICE" text file. +// ******************************************************************************/ +///* +// * Copyright 2003 Federal Chancellery Austria +// * MOA-ID has been developed in a cooperation between BRZ, the Federal +// * Chancellery Austria - ICT staff unit, and Graz University of Technology. +// * +// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by +// * the European Commission - subsequent versions of the EUPL (the "Licence"); +// * You may not use this work except in compliance with the Licence. +// * You may obtain a copy of the Licence at: +// * http://www.osor.eu/eupl/ +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the Licence is distributed on an "AS IS" basis, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the Licence for the specific language governing permissions and +// * limitations under the Licence. +// * +// * This product combines work with different licenses. See the "NOTICE" text +// * file for details on the various modules and licenses. +// * The "NOTICE" text file is part of the distribution. Any derivative works +// * that you distribute must include a readable copy of the "NOTICE" text file. +// */ +// +//package at.gv.egovernment.moa.id.auth.servlet; +// +//import java.io.IOException; +// +//import javax.servlet.RequestDispatcher; +//import javax.servlet.ServletConfig; +//import javax.servlet.ServletContext; +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServlet; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import org.springframework.beans.BeansException; +//import org.springframework.beans.factory.NoSuchBeanDefinitionException; +//import org.springframework.beans.factory.NoUniqueBeanDefinitionException; +//import org.springframework.web.context.WebApplicationContext; +//import org.springframework.web.context.support.WebApplicationContextUtils; +// +//import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; +//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +//import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +//import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +//import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +//import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +//import at.gv.egovernment.moa.id.config.ConfigurationException; +//import at.gv.egovernment.moa.id.process.ProcessEngine; +//import at.gv.egovernment.moa.id.process.ProcessExecutionException; +//import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; +//import at.gv.egovernment.moa.id.storage.IExceptionStore; +//import at.gv.egovernment.moa.id.util.ServletUtils; +//import at.gv.egovernment.moa.logging.Logger; +//import at.gv.egovernment.moa.util.MiscUtil; +// +///** +// * Base class for MOA-ID Auth Servlets, providing standard error handling and +// * constant names. +// * +// * @author Paul Ivancsics +// * @version $Id$ +// */ +//public class AuthServlet extends HttpServlet { +// +// /** +// * +// */ +// private static final long serialVersionUID = -6929905344382283738L; +// +// protected static final String ERROR_CODE_PARAM = "errorid"; +// +// /** +// * The process engine. +// */ +// private ProcessEngine processEngine; +// +// @Override +// protected void doGet(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// Logger.debug("GET " + this.getServletName()); +// +// this.setNoCachingHeadersInHttpRespone(req, resp); // } - - /** - * Set response headers to avoid caching - * - * @param request - * HttpServletRequest - * @param response - * HttpServletResponse - */ - protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, - HttpServletResponse response) { - response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - } - - /** - * Adds a parameter to a URL. - * - * @param url - * the URL - * @param paramname - * parameter name - * @param paramvalue - * parameter value - * @return the URL with parameter added - */ - protected static String addURLParameter(String url, String paramname, - String paramvalue) { - String param = paramname + "=" + paramvalue; - if (url.indexOf("?") < 0) - return url + "?" + param; - else - return url + "&" + param; - } - - /** - * Checks if HTTP requests are allowed - * - * @param authURL - * requestURL - * @throws AuthenticationException - * if HTTP requests are not allowed - * @throws ConfigurationException - */ - protected void checkIfHTTPisAllowed(String authURL) - throws AuthenticationException, ConfigurationException { - // check if HTTP Connection may be allowed (through - // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) - - //Removed from MOA-ID 2.0 config -// String boolStr = AuthConfigurationProvider -// .getInstance() -// .getGenericConfigurationParameter( -// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); - if ((!authURL.startsWith("https:")) - //&& (false == BoolUtils.valueOf(boolStr)) - ) - throw new AuthenticationException("auth.07", new Object[] { authURL - + "*" }); - - } - - - /** - * Returns the underlying process engine instance. - * - * @return The process engine (never {@code null}). - * @throws NoSuchBeanDefinitionException - * if no {@link ProcessEngine} bean was found. - * @throws NoUniqueBeanDefinitionException - * if more than one {@link ProcessEngine} bean was found. - * @throws BeansException - * if a problem getting the {@link ProcessEngine} bean occurred. - * @throws IllegalStateException - * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a - * Spring web environment. - */ - public synchronized ProcessEngine getProcessEngine() { - if (processEngine == null) { - WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); - if (ctx == null) { - throw new IllegalStateException( - "Unable to find Spring WebApplicationContext. Servlet needs to be executed within a Spring web environment."); - } - processEngine = ctx.getBean(ProcessEngine.class); - } - return processEngine; - } - -} +// +// protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, +// HttpServletRequest req, HttpServletResponse resp) { +// +// if (null != errorMessage) { +// Logger.error(errorMessage); +// req.setAttribute("ErrorMessage", errorMessage); +// } +// +// if (null != exceptionThrown) { +// if (null == errorMessage) +// errorMessage = exceptionThrown.getMessage(); +// Logger.error(errorMessage, exceptionThrown); +// req.setAttribute("ExceptionThrown", exceptionThrown); +// } +// +// if (Logger.isDebugEnabled()) { +// req.setAttribute("LogLevel", "debug"); +// } +// +// +// StatisticLogger logger = StatisticLogger.getInstance(); +// logger.logErrorOperation(exceptionThrown); +// +// +// // forward this to errorpage-auth.jsp where the HTML error page is +// // generated +// ServletContext context = getServletContext(); +// RequestDispatcher dispatcher = context +// .getRequestDispatcher("/errorpage-auth.jsp"); +// try { +// +// resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, +// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); +// resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, +// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); +// resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); +// resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); +// +// dispatcher.forward(req, resp); +// } catch (ServletException e) { +// Logger.error(e); +// } catch (IOException e) { +// Logger.error(e); +// } +// } +// +// /** +// * Handles an error. <br>> +// * <ul> +// * <li>Logs the error</li> +// * <li>Places error message and exception thrown into the request as request +// * attributes (to be used by <code>"/errorpage-auth.jsp"</code>)</li> +// * <li>Sets HTTP status 500 (internal server error)</li> +// * </ul> +// * +// * @param errorMessage +// * error message +// * @param exceptionThrown +// * exception thrown +// * @param req +// * servlet request +// * @param resp +// * servlet response +// */ +// protected void handleError(String errorMessage, Throwable exceptionThrown, +// HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { +// +// Throwable loggedException = null; +// +// if (exceptionThrown != null +// && exceptionThrown instanceof ProcessExecutionException) { +// ProcessExecutionException procExc = +// (ProcessExecutionException) exceptionThrown; +// if (procExc.getCause() != null && +// procExc.getCause() instanceof TaskExecutionException) { +// TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); +// loggedException = taskExc.getOriginalException(); +// +// } +// } +// +// if (loggedException == null) +// loggedException = exceptionThrown; +// +// +// if (!(loggedException instanceof MOAIDException)) { +// Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); +// +// } else { +// if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { +// Logger.error(loggedException.getMessage(), loggedException); +// +// } else { +// Logger.error(loggedException.getMessage()); +// +// } +// } +// +// IExceptionStore store = DBExceptionStoreImpl.getStore(); +// String id = store.storeException(loggedException); +// +// if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { +// +// String redirectURL = null; +// +// redirectURL = ServletUtils.getBaseUrl(req); +// +// //TODO: DEVELOPMENT +//// redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id +//// + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; +// +// resp.setContentType("text/html"); +// resp.setStatus(302); +// +// resp.addHeader("Location", redirectURL); +// Logger.debug("REDIRECT TO: " + redirectURL); +// +// return; +// +// } else { +// +// //Exception can not be stored in database +// handleErrorNoRedirect(errorMessage, loggedException, req, resp); +// } +// } +// +// /** +// * Handles a <code>WrongParametersException</code>. +// * +// * @param req +// * servlet request +// * @param resp +// * servlet response +// */ +// protected void handleWrongParameters(WrongParametersException ex, +// HttpServletRequest req, HttpServletResponse resp) { +// Logger.error(ex.toString()); +// req.setAttribute("WrongParameters", ex.getMessage()); +// +// // forward this to errorpage-auth.jsp where the HTML error page is +// // generated +// ServletContext context = getServletContext(); +// RequestDispatcher dispatcher = context +// .getRequestDispatcher("/errorpage-auth.jsp"); +// try { +// resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, +// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); +// resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, +// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); +// resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); +// resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); +// +// dispatcher.forward(req, resp); +// } catch (ServletException e) { +// Logger.error(e); +// } catch (IOException e) { +// Logger.error(e); +// } +// } +// +// +// /** +// * Calls the web application initializer. +// * +// * @see javax.servlet.Servlet#init(ServletConfig) +// */ +// public void init(ServletConfig servletConfig) throws ServletException { +// super.init(servletConfig); +// } +// +// +// /** +// * Set response headers to avoid caching +// * +// * @param request +// * HttpServletRequest +// * @param response +// * HttpServletResponse +// */ +// protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, +// HttpServletResponse response) { +// response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, +// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); +// response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, +// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); +// response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); +// response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); +// +// } +// +// /** +// * Adds a parameter to a URL. +// * +// * @param url +// * the URL +// * @param paramname +// * parameter name +// * @param paramvalue +// * parameter value +// * @return the URL with parameter added +// */ +// protected static String addURLParameter(String url, String paramname, +// String paramvalue) { +// String param = paramname + "=" + paramvalue; +// if (url.indexOf("?") < 0) +// return url + "?" + param; +// else +// return url + "&" + param; +// } +// +// /** +// * Checks if HTTP requests are allowed +// * +// * @param authURL +// * requestURL +// * @throws AuthenticationException +// * if HTTP requests are not allowed +// * @throws ConfigurationException +// */ +// protected void checkIfHTTPisAllowed(String authURL) +// throws AuthenticationException, ConfigurationException { +// // check if HTTP Connection may be allowed (through +// // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) +// +// //Removed from MOA-ID 2.0 config +//// String boolStr = AuthConfigurationProvider +//// .getInstance() +//// .getGenericConfigurationParameter( +//// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); +// if ((!authURL.startsWith("https:")) +// //&& (false == BoolUtils.valueOf(boolStr)) +// ) +// throw new AuthenticationException("auth.07", new Object[] { authURL +// + "*" }); +// +// } +// +// +// /** +// * Returns the underlying process engine instance. +// * +// * @return The process engine (never {@code null}). +// * @throws NoSuchBeanDefinitionException +// * if no {@link ProcessEngine} bean was found. +// * @throws NoUniqueBeanDefinitionException +// * if more than one {@link ProcessEngine} bean was found. +// * @throws BeansException +// * if a problem getting the {@link ProcessEngine} bean occurred. +// * @throws IllegalStateException +// * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a +// * Spring web environment. +// */ +// public synchronized ProcessEngine getProcessEngine() { +// if (processEngine == null) { +// WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); +// if (ctx == null) { +// throw new IllegalStateException( +// "Unable to find Spring WebApplicationContext. Servlet needs to be executed within a Spring web environment."); +// } +// processEngine = ctx.getBean(ProcessEngine.class); +// } +// return processEngine; +// } +// +//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java new file mode 100644 index 000000000..6bccd5b88 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.servlet; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * @author tlenz + * + */ +@Controller +public class GeneralProcessEngineSignalController extends AbstractProcessEngineSignalController { + + + @RequestMapping(value = {"/GenerateIframeTemplate", + "/SSOSendAssertionServlet", + "/signalProcess" + }, + method = {RequestMethod.POST, RequestMethod.GET}) + public void performGenericAuthenticationProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException { + signalProcessManagement(req, resp); + + } +} 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 15d596049..663a14881 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 @@ -1,168 +1,168 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -package at.gv.egovernment.moa.id.auth.servlet; - -import java.io.IOException; -import java.util.Enumeration; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.process.ExecutionContextImpl; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -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; - -public class GenerateIFrameTemplateServlet extends AuthServlet { - - private static final long serialVersionUID = 1L; - - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - Logger.debug("Receive " + GenerateIFrameTemplateServlet.class + " Request"); - - String pendingRequestID = null; - - try { - String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); - moasessionid = StringEscapeUtils.escapeHtml(moasessionid); - AuthenticationSession moasession = null; - try { - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); - moasession = AuthenticationSessionStoreage.getSession(moasessionid); - - } 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[] {}); - } - - - - ExecutionContext ec = new ExecutionContextImpl(); - // 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); - 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); - - // make sure moa session has been persisted before running the process - try { - AuthenticationSessionStoreage.storeSession(moasession); - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { moasession.getSessionID() }); - } - - Logger.info("BKU is selected -> Start BKU communication ..."); - - // start process - getProcessEngine().start(processInstanceId); - - } - catch (WrongParametersException ex) { - handleWrongParameters(ex, req, resp); - } - - catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (ProcessExecutionException e) { - Throwable cause = e.getCause(); - if (cause != null && cause instanceof TaskExecutionException) { - Throwable taskCause = cause.getCause(); - if (taskCause != null && taskCause instanceof WrongParametersException) { - WrongParametersException internalEx = (WrongParametersException) taskCause; - handleWrongParameters(internalEx, req, resp); - return; - - } else if (taskCause != null && taskCause instanceof MOAIDException) { - MOAIDException moaTaskCause = (MOAIDException) taskCause; - handleError(null, moaTaskCause, req, resp, pendingRequestID); - return; - - } - } - - Logger.error("BKUSelectionServlet has an interal Error.", e); - - } catch (Exception e) { - Logger.error("BKUSelectionServlet has an interal Error.", e); - - } - - finally { - - } - } - - - - - - - - - -} +///******************************************************************************* +// * Copyright 2014 Federal Chancellery Austria +// * MOA-ID has been developed in a cooperation between BRZ, the Federal +// * Chancellery Austria - ICT staff unit, and Graz University of Technology. +// * +// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by +// * the European Commission - subsequent versions of the EUPL (the "Licence"); +// * You may not use this work except in compliance with the Licence. +// * You may obtain a copy of the Licence at: +// * http://www.osor.eu/eupl/ +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the Licence is distributed on an "AS IS" basis, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the Licence for the specific language governing permissions and +// * limitations under the Licence. +// * +// * This product combines work with different licenses. See the "NOTICE" text +// * file for details on the various modules and licenses. +// * The "NOTICE" text file is part of the distribution. Any derivative works +// * that you distribute must include a readable copy of the "NOTICE" text file. +// ******************************************************************************/ +//package at.gv.egovernment.moa.id.auth.servlet; +// +//import java.io.IOException; +//import java.util.Enumeration; +// +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import org.apache.commons.lang.StringEscapeUtils; +// +//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +//import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +//import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +//import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +//import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +//import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; +//import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +//import at.gv.egovernment.moa.id.process.ExecutionContextImpl; +//import at.gv.egovernment.moa.id.process.ProcessExecutionException; +//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; +// +//public class GenerateIFrameTemplateServlet extends AuthServlet { +// +// private static final long serialVersionUID = 1L; +// +// protected void doGet(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// Logger.debug("Receive " + GenerateIFrameTemplateServlet.class + " Request"); +// +// String pendingRequestID = null; +// +// try { +// String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); +// moasessionid = StringEscapeUtils.escapeHtml(moasessionid); +// AuthenticationSession moasession = null; +// try { +// pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); +// moasession = AuthenticationSessionStoreage.getSession(moasessionid); +// +// } 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[] {}); +// } +// +// +// +// ExecutionContext ec = new ExecutionContextImpl(); +// // 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); +// 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); +// +// // make sure moa session has been persisted before running the process +// try { +// AuthenticationSessionStoreage.storeSession(moasession); +// } catch (MOADatabaseException e) { +// Logger.error("Database Error! MOASession is not stored!"); +// throw new MOAIDException("init.04", new Object[] { moasession.getSessionID() }); +// } +// +// Logger.info("BKU is selected -> Start BKU communication ..."); +// +// // start process +// getProcessEngine().start(processInstanceId); +// +// } +// catch (WrongParametersException ex) { +// handleWrongParameters(ex, req, resp); +// } +// +// catch (MOAIDException ex) { +// handleError(null, ex, req, resp, pendingRequestID); +// +// } catch (ProcessExecutionException e) { +// Throwable cause = e.getCause(); +// if (cause != null && cause instanceof TaskExecutionException) { +// Throwable taskCause = cause.getCause(); +// if (taskCause != null && taskCause instanceof WrongParametersException) { +// WrongParametersException internalEx = (WrongParametersException) taskCause; +// handleWrongParameters(internalEx, req, resp); +// return; +// +// } else if (taskCause != null && taskCause instanceof MOAIDException) { +// MOAIDException moaTaskCause = (MOAIDException) taskCause; +// handleError(null, moaTaskCause, req, resp, pendingRequestID); +// return; +// +// } +// } +// +// Logger.error("BKUSelectionServlet has an interal Error.", e); +// +// } catch (Exception e) { +// Logger.error("BKUSelectionServlet has an interal Error.", e); +// +// } +// +// finally { +// +// } +// } +// +// +// +// +// +// +// +// +// +//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java index fe5cd1ac0..48292cee1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java @@ -31,6 +31,8 @@ import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import org.opensaml.saml2.core.LogoutResponse; import org.opensaml.saml2.metadata.SingleLogoutService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -43,8 +45,7 @@ import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NOSLOServiceDescriptorException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.Random; @@ -56,10 +57,13 @@ import at.gv.egovernment.moa.util.URLEncoder; * @author tlenz * */ -public class IDPSingleLogOutServlet extends AuthServlet { +@Controller +public class IDPSingleLogOutServlet extends AbstractController { - private static final long serialVersionUID = -1301786072691577221L; - + @Autowired SSOManager ssoManager; + @Autowired AuthenticationManager authManager; + @Autowired IAuthenticationSessionStoreage authenicationStorage; + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Logger.debug("receive IDP SingleLogOut Request"); @@ -79,9 +83,8 @@ public class IDPSingleLogOutServlet extends AuthServlet { return; } - - SSOManager ssomanager = SSOManager.getInstance(); - String ssoid = ssomanager.getSSOSessionID(req); + + String ssoid = ssoManager.getSSOSessionID(req); Object restartProcessObj = req.getParameter(MOAIDAuthConstants.PARAM_SLORESTART); @@ -91,9 +94,9 @@ public class IDPSingleLogOutServlet extends AuthServlet { if (tokkenObj != null && tokkenObj instanceof String) { tokken = (String) tokkenObj; try { - status = AssertionStorage.getInstance().get(tokken, String.class); + status = transactionStorage.get(tokken, String.class); if (MiscUtil.isNotEmpty(status)) { - AssertionStorage.getInstance().remove(tokken); + transactionStorage.remove(tokken); } VelocityContext context = new VelocityContext(); @@ -104,13 +107,13 @@ public class IDPSingleLogOutServlet extends AuthServlet { context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssomanager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp); } catch (MOAIDException e) { - handleErrorNoRedirect(e.getMessage(), e, req, resp); + handleErrorNoRedirect(e, req, resp); } catch (MOADatabaseException e) { - handleErrorNoRedirect(e.getMessage(), e, req, resp); + handleErrorNoRedirect(e, req, resp); } @@ -118,16 +121,14 @@ public class IDPSingleLogOutServlet extends AuthServlet { } else if (MiscUtil.isNotEmpty(ssoid)) { try { - if (ssomanager.isValidSSOSession(ssoid, null)) { + if (ssoManager.isValidSSOSession(ssoid, null)) { - AuthenticationManager authmanager = AuthenticationManager.getInstance(); - String moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoid); + String moaSessionID = authenicationStorage.getMOASessionSSOID(ssoid); if (MiscUtil.isNotEmpty(moaSessionID)) { - AuthenticationSession authSession = AuthenticationSessionStoreage - .getSession(moaSessionID); + AuthenticationSession authSession = authenicationStorage.getSession(moaSessionID); if(authSession != null) { - authmanager.performSingleLogOut(req, resp, authSession, authURL); + authManager.performSingleLogOut(req, resp, authSession, authURL); return; } @@ -147,7 +148,7 @@ public class IDPSingleLogOutServlet extends AuthServlet { if (MiscUtil.isNotEmpty(restartProcess)) { Logger.info("Restart Single LogOut process after timeout ... "); try { - SLOInformationContainer sloContainer = AssertionStorage.getInstance().get(restartProcess, SLOInformationContainer.class); + SLOInformationContainer sloContainer = transactionStorage.get(restartProcess, SLOInformationContainer.class); if (sloContainer.hasFrontChannelOA()) sloContainer.putFailedOA("differntent OAs"); @@ -171,13 +172,13 @@ public class IDPSingleLogOutServlet extends AuthServlet { else statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; - AssertionStorage.getInstance().put(artifact, statusCode); - redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); + transactionStorage.put(artifact, statusCode); + redirectURL = HTTPUtils.addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); } - //redirect to Redirect Servlet - String url = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix() + "/RedirectServlet"; - url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(redirectURL, "UTF-8")); + //redirect to Redirect Servlet + String url = authURL + "/RedirectServlet"; + url = HTTPUtils.addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(redirectURL, "UTF-8")); url = resp.encodeRedirectURL(url); resp.setContentType("text/html"); @@ -205,10 +206,11 @@ public class IDPSingleLogOutServlet extends AuthServlet { MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); try { - ssomanager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp); } catch (MOAIDException e) { e.printStackTrace(); + } return; } @@ -218,10 +220,11 @@ public class IDPSingleLogOutServlet extends AuthServlet { context.put("successMsg", MOAIDMessageProvider.getInstance().getMessage("slo.02", null)); try { - ssomanager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp); } catch (MOAIDException e) { e.printStackTrace(); + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java index a5504ec4c..4ed276814 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java @@ -51,6 +51,7 @@ import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -58,9 +59,8 @@ import org.springframework.web.bind.annotation.RequestMethod; 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.AuthenticationManager; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -70,14 +70,16 @@ import at.gv.egovernment.moa.util.MiscUtil; public class LogOutServlet { private static final String REDIRECT_URL = "redirect"; + @Autowired private SSOManager ssomanager; + @Autowired private AuthenticationManager authmanager; + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; + @RequestMapping(value = "/LogOut", method = {RequestMethod.POST, RequestMethod.GET}) public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { Logger.debug("receive LogOut Request"); String redirectUrl = (String) req.getParameter(REDIRECT_URL); - - SSOManager ssomanager = SSOManager.getInstance(); - + try { //get SSO token from request String ssoid = ssomanager.getSSOSessionID(req); @@ -103,15 +105,13 @@ public class LogOutServlet { //TODO: Single LogOut Implementation //delete SSO session and MOA session - AuthenticationManager authmanager = AuthenticationManager.getInstance(); - String moasessionid = AuthenticationSessionStoreage.getMOASessionSSOID(ssoid); - - RequestStorage.removePendingRequest(AuthenticationSessionStoreage.getPendingRequestID(moasessionid)); - + String moasessionid = authenticatedSessionStorage.getMOASessionSSOID(ssoid); authmanager.performOnlyIDPLogOut(req, resp, moasessionid); + Logger.info("User with SSO Id " + ssoid + " is logged out and get redirect to "+ redirectUrl); } else { Logger.info("No active SSO session found. User is maybe logout already and get redirect to "+ redirectUrl); + } //Remove SSO token 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 deleted file mode 100644 index f3e3ae8a4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ /dev/null @@ -1,122 +0,0 @@ -package at.gv.egovernment.moa.id.auth.servlet;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringEscapeUtils;
-
-import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils;
-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.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.logging.Logger;
-
-/**
- * Servlet that resumes a suspended process (in case of asynchronous tasks).
- *
- * @author tknall
- *
- */
-public class ProcessEngineSignalServlet extends AuthServlet {
-
- private static final long serialVersionUID = 1L;
-
- /**
- * Sets response headers that prevent caching (code taken from {@link AuthServlet}).
- *
- * @param resp
- * The HttpServletResponse.
- */
- private void setNoCachingHeaders(HttpServletResponse resp) {
- resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
- resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
- resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
- resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);
- }
-
- /**
- * Processes a GET request, delegating the call to {@link #doPost(HttpServletRequest, HttpServletResponse)}.
- */
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- this.doPost(req, resp);
- }
-
- /**
- * Resumes the current process instance that has been suspended due to an asynchronous task. The process instance is
- * retrieved from the MOA session referred to by the request parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}.
- */
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- String sessionID = StringEscapeUtils.escapeHtml(getMoaSessionId(req));
-
- setNoCachingHeaders(resp);
- String pendingRequestID = null;
- try {
-
- if (sessionID == null) {
- throw new IllegalStateException("Unable to determine MOA session id.");
- }
-
- // retrieve moa session
- pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID);
-
- 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});
-
- }
-
- AuthenticationSessionExtensions extendedSessionInformation = AuthenticationSessionStoreage.getAuthenticationSessionExtensions(sessionID);
- AuthenticationSession session = BaseAuthenticationServer.getSession(sessionID);
-
- //add transactionID and unique sessionID to Logger
- if (extendedSessionInformation != null)
- TransactionIDUtils.setSessionId(extendedSessionInformation.getUniqueSessionId());
- TransactionIDUtils.setTransactionId(pendingRequestID);
-
- // process instance is mandatory
- if (session.getProcessInstanceId() == null) {
- throw new IllegalStateException("MOA session does not provide process instance id.");
- }
-
- // wake up next task
- getProcessEngine().signal(session.getProcessInstanceId());
-
- } catch (Exception ex) {
- handleError(null, ex, req, resp, pendingRequestID);
-
- } finally {
- //MOASessionDBUtils.closeSession();
- TransactionIDUtils.removeTransactionId();
- TransactionIDUtils.removeSessionId();
-
- }
-
- }
-
- /**
- * Retrieves the current MOA session id from the HttpServletRequest parameter
- * {@link MOAIDAuthConstants#PARAM_SESSIONID}.
- * <p/>
- * Note that this class/method can be overwritten by modules providing their own strategy of retrieving the
- * respective MOA session id.
- *
- * @param request
- * The unterlying HttpServletRequest.
- * @return The current MOA session id.
- */
- public String getMoaSessionId(HttpServletRequest request) {
- return StringEscapeUtils.escapeHtml(request.getParameter(MOAIDAuthConstants.PARAM_SESSIONID));
- }
-
-}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java index a914659b0..ba8ace6c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java @@ -25,13 +25,16 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; import java.io.PrintWriter; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.RedirectFormBuilder; - 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.SSOManager; @@ -42,18 +45,16 @@ import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; - -public class RedirectServlet extends AuthServlet{ - - private static final long serialVersionUID = 1L; +@Controller +public class RedirectServlet { public static final String REDIRCT_PARAM_URL = "redirecturl"; - private static final String DEFAULT_REDIRECTTARGET = "_parent"; + @Autowired SSOManager ssoManager; - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + @RequestMapping(value = "/RedirectServlet", method = RequestMethod.GET) + public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { Logger.debug("Receive " + RedirectServlet.class + " Request"); String url = req.getParameter(REDIRCT_PARAM_URL); @@ -89,12 +90,12 @@ public class RedirectServlet extends AuthServlet{ if (MiscUtil.isNotEmpty(target)) { // redirectURL = addURLParameter(redirectURL, PARAM_TARGET, // URLEncoder.encode(session.getTarget(), "UTF-8")); - url = addURLParameter(url, MOAIDAuthConstants.PARAM_TARGET, + url = HTTPUtils.addURLParameter(url, MOAIDAuthConstants.PARAM_TARGET, URLEncoder.encode(target, "UTF-8")); } - url = addURLParameter(url, MOAIDAuthConstants.PARAM_SAMLARTIFACT, + url = HTTPUtils.addURLParameter(url, MOAIDAuthConstants.PARAM_SAMLARTIFACT, URLEncoder.encode(artifact, "UTF-8")); url = resp.encodeRedirectURL(url); @@ -109,8 +110,7 @@ public class RedirectServlet extends AuthServlet{ } else if (MiscUtil.isNotEmpty(interIDP)) { //store IDP identifier and redirect to generate AuthRequst service Logger.info("Receive an interfederation redirect request for IDP " + interIDP); - SSOManager sso = SSOManager.getInstance(); - sso.setInterfederationIDPCookie(req, resp, interIDP); + ssoManager.setInterfederationIDPCookie(req, resp, interIDP); Logger.debug("Redirect to " + url); url = resp.encodeRedirectURL(url); @@ -141,7 +141,7 @@ public class RedirectServlet extends AuthServlet{ } + } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java index 62ee1ed85..1d18ccb2c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java @@ -28,9 +28,7 @@ package at.gv.egovernment.moa.id.auth.servlet; */ public class SAML2InterfederationSignalServlet extends - ProcessEngineSignalServlet { - - private static final long serialVersionUID = 8208970012249149156L; + AbstractProcessEngineSignalController { //TODO: getMOASessionID from SAML2 relayState 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 064431a6b..4c895e387 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 @@ -1,176 +1,177 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -package at.gv.egovernment.moa.id.auth.servlet; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.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.WrongParametersException; -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.moduls.SSOManager; -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.MiscUtil; - -public class SSOSendAssertionServlet extends AuthServlet{ - - private static final long serialVersionUID = 1L; - - private static final String PARAM = "value"; - private static final String MODULE = "mod"; - private static final String ACTION = "action"; - private static final String ID = "identifier"; - - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - String id = null; - Logger.debug("Receive " + SSOSendAssertionServlet.class + " Request"); - try { - - Object idObject = req.getParameter(ID); - - if (idObject != null && (idObject instanceof String)) { - id = (String) idObject; - } - - String value = req.getParameter(PARAM); - value = StringEscapeUtils.escapeHtml(value); - if (!ParamValidatorUtils.isValidUseMandate(value)) - throw new WrongParametersException("SSOSendAssertionServlet", PARAM, null); - - //get module and action - Object moduleObject = req.getParameter(MODULE); - String module = null; - if (moduleObject != null && (moduleObject instanceof String)) { - module = (String) moduleObject; - } - - - Object actionObject = req.getParameter(ACTION); - String action = null; - if (actionObject != null && (actionObject instanceof String)) { - action = (String) actionObject; - } - - if (MiscUtil.isEmpty(module) || MiscUtil.isEmpty(action) || MiscUtil.isEmpty(id)) { - Logger.warn("No Moduel or Action parameter received!"); - throw new WrongParametersException("Module or Action is empty", "", "auth.10"); - } - - - SSOManager ssomanager = SSOManager.getInstance(); - //get SSO Cookie for Request - String ssoId = ssomanager.getSSOSessionID(req); - - //check SSO session - if (ssoId != null) { - String correspondingMOASession = ssomanager.existsOldSSOSession(ssoId); - - if (correspondingMOASession != null) { - Logger.warn("Request sends an old SSO Session ID("+ssoId+")! " + - "Invalidate the corresponding MOASession with ID="+ correspondingMOASession); - - - AuthenticationSessionStoreage.destroySession(correspondingMOASession); - - ssomanager.deleteSSOSessionID(req, resp); - } - } - - boolean isValidSSOSession = ssomanager.isValidSSOSession(ssoId, null); - - String moaSessionID = null; - - if (isValidSSOSession) { - - - //check UseMandate flag - String valueString = null;; - if ((value != null) && (value.compareTo("") != 0)) { - valueString = value; - } else { - valueString = "false"; - } - - if (valueString.compareToIgnoreCase("true") == 0) { - moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoId); - AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moaSessionID); - AuthenticationSessionStoreage.setAuthenticated(moaSessionID, true); - - //log event - //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(), - ModulUtils.buildAuthURL(module, action, id), ""); - - resp.setContentType("text/html"); - resp.setStatus(302); - - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - } - - else { - throw new AuthenticationException("auth.21", new Object[] {}); - } - - } else { - handleError("SSO Session is not valid", null, req, resp, id); - } - - - } catch (MOADatabaseException e) { - handleError("SSO Session is not found", e, req, resp, id); - - } catch (WrongParametersException e) { - handleError("Parameter is not valid", e, req, resp, id); - - } catch (AuthenticationException e) { - handleError(e.getMessage(), e, req, resp, id); - - } catch (Exception e) { - Logger.error("SSOSendAssertion has an interal Error.", 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.auth.servlet; +// +//import java.io.IOException; +// +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import org.apache.commons.lang.StringEscapeUtils; +// +//import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +//import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; +//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.WrongParametersException; +//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.moduls.SSOManager; +//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.MiscUtil; +// +//public class SSOSendAssertionServlet extends AuthServlet{ +// +// private static final long serialVersionUID = 1L; +// +// private static final String PARAM = "value"; +// private static final String MODULE = "mod"; +// private static final String ACTION = "action"; +// private static final String ID = "identifier"; +// +// protected void doPost(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// +// String id = null; +// Logger.debug("Receive " + SSOSendAssertionServlet.class + " Request"); +// try { +// +// Object idObject = req.getParameter(ID); +// +// if (idObject != null && (idObject instanceof String)) { +// id = (String) idObject; +// } +// +// String value = req.getParameter(PARAM); +// value = StringEscapeUtils.escapeHtml(value); +// if (!ParamValidatorUtils.isValidUseMandate(value)) +// throw new WrongParametersException("SSOSendAssertionServlet", PARAM, null); +// +// //get module and action +// Object moduleObject = req.getParameter(MODULE); +// String module = null; +// if (moduleObject != null && (moduleObject instanceof String)) { +// module = (String) moduleObject; +// } +// +// +// Object actionObject = req.getParameter(ACTION); +// String action = null; +// if (actionObject != null && (actionObject instanceof String)) { +// action = (String) actionObject; +// } +// +// if (MiscUtil.isEmpty(module) || MiscUtil.isEmpty(action) || MiscUtil.isEmpty(id)) { +// Logger.warn("No Moduel or Action parameter received!"); +// throw new WrongParametersException("Module or Action is empty", "", "auth.10"); +// } +// +// +// SSOManager ssomanager = SSOManager.getInstance(); +// //get SSO Cookie for Request +// String ssoId = ssomanager.getSSOSessionID(req); +// +// //check SSO session +// if (ssoId != null) { +// String correspondingMOASession = ssomanager.existsOldSSOSession(ssoId); +// +// if (correspondingMOASession != null) { +// Logger.warn("Request sends an old SSO Session ID("+ssoId+")! " + +// "Invalidate the corresponding MOASession with ID="+ correspondingMOASession); +// +// +// AuthenticationSessionStoreage.destroySession(correspondingMOASession); +// +// ssomanager.deleteSSOSessionID(req, resp); +// } +// } +// +// boolean isValidSSOSession = ssomanager.isValidSSOSession(ssoId, null); +// +// String moaSessionID = null; +// +// if (isValidSSOSession) { +// +// +// //check UseMandate flag +// String valueString = null;; +// if ((value != null) && (value.compareTo("") != 0)) { +// valueString = value; +// } else { +// valueString = "false"; +// } +// +// if (valueString.compareToIgnoreCase("true") == 0) { +// moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoId); +// AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moaSessionID); +// AuthenticationSessionStoreage.setAuthenticated(moaSessionID, true); +// +// //log event +// //String pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); +// IRequest pendingReq = RequestStorage.getPendingRequest(id); +// MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_FINISHED); +// +// //TODO: only for development!!!!!!! +//// String redirectURL = new DataURLBuilder().buildDataURL(moasession.getAuthURL(), +//// ModulUtils.buildAuthURL(module, action, id), ""); +// +// String redirectURL = "Remove commants in Class:SSOSendAssertionServlet Line:141"; +// +// resp.setContentType("text/html"); +// resp.setStatus(302); +// +// +// resp.addHeader("Location", redirectURL); +// Logger.debug("REDIRECT TO: " + redirectURL); +// +// } +// +// else { +// throw new AuthenticationException("auth.21", new Object[] {}); +// } +// +// } else { +// handleError("SSO Session is not valid", null, req, resp, id); +// } +// +// +// } catch (MOADatabaseException e) { +// handleError("SSO Session is not found", e, req, resp, id); +// +// } catch (WrongParametersException e) { +// handleError("Parameter is not valid", e, req, resp, id); +// +// } catch (AuthenticationException e) { +// handleError(e.getMessage(), e, req, resp, id); +// +// } catch (Exception e) { +// Logger.error("SSOSendAssertion has an interal Error.", e); +// } +// +// } +// +//} |