diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls')
8 files changed, 379 insertions, 1421 deletions
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 7f183c5eb..77abe07af 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -22,491 +22,82 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; -import java.io.IOException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; import java.util.Enumeration; -import java.util.Iterator; import java.util.List; -import java.util.Map.Entry; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; import org.opensaml.saml2.core.LogoutRequest; -import org.opensaml.saml2.core.LogoutResponse; -import org.opensaml.saml2.core.StatusCode; -import org.opensaml.saml2.metadata.SingleLogoutService; -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 at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.idp.auth.AbstractAuthenticationManager; +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; -import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.auth.frontend.builder.DefaultGUIFormBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; -import at.gv.egovernment.moa.id.auth.frontend.exception.GUIBuildException; -import at.gv.egovernment.moa.id.auth.modules.SingleSignOnConsentsModuleImpl; -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.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.data.SLOInformationContainer; -import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.process.ExecutionContextImpl; -import at.gv.egovernment.moa.id.process.ProcessEngine; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.id.util.legacy.LegacyHelper; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Service("MOAID_AuthenticationManager") -public class AuthenticationManager extends MOAIDAuthConstants { +public class AuthenticationManager extends AbstractAuthenticationManager { - private static List<String> reqParameterWhiteListeForModules = new ArrayList<String>(); + public static final String eIDAS_GENERIC_REQ_DATA_LEVELOFASSURENCE = "eIDAS_LoA"; + public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; public static final String MOA_SESSION = "MoaAuthenticationSession"; public static final String MOA_AUTHENTICATED = "MoaAuthenticated"; - public static final int SLOTIMEOUT = 30 * 1000; //30 sec + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; + @Autowired private SingleLogOutBuilder sloBuilder;; - @Autowired private ProcessEngine processEngine; - @Autowired private SSOManager ssoManager; - @Autowired private IRequestStorage requestStoreage; - @Autowired private ITransactionStorage transactionStorage; - @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; - @Autowired private MOAReversionLogger revisionsLogger; - @Autowired protected AuthConfiguration authConfig; - @Autowired private SingleLogOutBuilder sloBuilder; - @Autowired private SAMLVerificationEngineSP samlVerificationEngine; - @Autowired private IGUIFormBuilder guiBuilder; - @Autowired(required=true) private MOAMetadataProvider metadataProvider; - public void performSingleLogOut(HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { - performSingleLogOut(httpReq, httpResp, session, pvpReq, null); - - } - - public void performSingleLogOut(HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthenticationSession session, String authURL) throws MOAIDException { - performSingleLogOut(httpReq, httpResp, session, null, authURL); - - } - - /** - * @param req - * @param resp - * @param moasessionid - */ - public void performOnlyIDPLogOut(AuthenticationSession authSession) { - - if (authSession == null) { - Logger.info("No internal MOA SSO-Session found. Nothing to destroy"); - return; - - } - - try { - - authSession.setAuthenticated(false); - //HTTPSessionUtils.setHTTPSessionString(session, MOA_SESSION, null); // remove moa session from HTTP Session - - //log Session_Destroy to reversionslog - AuthenticationSessionExtensions sessionExtensions = authenticatedSessionStore.getAuthenticationSessionExtensions(authSession.getSessionID()); - revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); - - authenticatedSessionStore.destroyInternalSSOSession(authSession.getSessionID()); - - //session.invalidate(); - - } catch (MOADatabaseException e) { - Logger.info("NO MOA Authentication data for ID " + authSession.getSessionID()); - return; - } - - } - - - public void performOnlyIDPLogOut(HttpServletRequest request, - HttpServletResponse response, String internalMOASsoSessionID) { - Logger.info("Remove active user-session"); - - if(internalMOASsoSessionID == null) { - internalMOASsoSessionID = StringEscapeUtils.escapeHtml((String) request.getParameter(PARAM_SESSIONID)); - } - - if(internalMOASsoSessionID == null) { - Logger.info("NO MOA Session to logout"); - return; - } - - AuthenticationSession authSession; - try { - authSession = authenticatedSessionStore.getInternalSSOSession(internalMOASsoSessionID); - - if(authSession == null) { - Logger.info("NO MOA Authentication data for ID " + internalMOASsoSessionID); - return; - } - - performOnlyIDPLogOut(authSession); - - } catch (MOADatabaseException e) { - Logger.info("NO MOA Authentication data for ID " + internalMOASsoSessionID); - return; - } - - } - - - /** - * Authenticates the authentication request {pendingReq}, which is actually processed - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * - * @return Return already authenticated MOASession if exists, otherwise return null - * @throws MOADatabaseException - * @throws MOAIDException - * @throws IOException - * @throws ServletException - * - */ - public AuthenticationSession doAuthentication(HttpServletRequest httpReq, - HttpServletResponse httpResp, RequestImpl pendingReq) throws MOADatabaseException, ServletException, IOException, MOAIDException { - - //load OA configuration from pending request - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - //set logging context and log unique OA identifier to revision log - TransactionIDUtils.setServiceProviderId(pendingReq.getOnlineApplicationConfiguration().getPublicURLPrefix()); - revisionsLogger.logEvent(oaParam, - pendingReq, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, pendingReq.getOAURL()); - - //generic authentication request validation - if (pendingReq.isPassiv() - && pendingReq.forceAuth()) { - // conflict! - throw new NoPassivAuthenticationException(); - } - - //get SSO cookie from http request - String ssoId = ssoManager.getSSOSessionID(httpReq); - - //check if interfederation IDP is requested - ssoManager.checkInterfederationIsRequested(httpReq, httpResp, pendingReq); - - //check if SSO session cookie is already used - 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); - - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_INVALID); - - //destroy internal SSO-session object and SSO-session cooky - authenticatedSessionStore.destroyInternalSSOSession(correspondingMOASession); - ssoManager.deleteSSOSessionID(httpReq, httpResp); - } - } - - //check if SSO Session is valid - boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); - - // check if Service-Provider allows SSO sessions - boolean useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); - - //if a legacy request is used SSO should not be allowed in case of mandate authentication - boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(httpReq); - - //check if SSO is allowed for the actually executed request - //INFO: Actually, useMandate disables SSO functionality!!!!! - boolean isSSOAllowed = (useSSOOA && !isUseMandateRequested); - pendingReq.setNeedSingleSignOnFunctionality(isSSOAllowed); - - //get MOASession from SSO-Cookie if SSO is allowed - AuthenticationSession ssoMOASession = null; - if (isValidSSOSession && isSSOAllowed) { - ssoMOASession = ssoManager.getInternalMOASession(ssoId); - - if (ssoMOASession == null) - Logger.info("No MOASession FOUND with provided SSO-Cookie."); - - else { - Logger.debug("Found authenticated MOASession with provided SSO-Cookie."); - revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO); - - } - } - - //check if session is already authenticated - boolean isSessionAuthenticated = tryPerformAuthentication((RequestImpl) pendingReq, ssoMOASession); - - //force new authentication authentication process - if (pendingReq.forceAuth()) { - startAuthenticationProcess(httpReq, httpResp, pendingReq); - return null; - - //perform SSO-Consents evaluation if it it required - } else if (isSessionAuthenticated && oaParam.useSSOQuestion()) { - sendSingleSignOnConsentsEvaluation(httpReq, httpResp, pendingReq); - return null; - - } else if (pendingReq.isPassiv()) { - if (isSessionAuthenticated) { - // Passive authentication ok! - revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); - return ssoMOASession; - - } else { - throw new NoPassivAuthenticationException(); - - } - } else { - if (isSessionAuthenticated) { - // Is authenticated .. proceed - revisionsLogger.logEvent(oaParam, - pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); - return ssoMOASession; - - } else { - // Start authentication! - startAuthenticationProcess(httpReq, httpResp, pendingReq); - return null; - } - } - } - - /** - * Add a request parameter to whitelist. All parameters that are part of the white list are added into {@link ExecutionContext} - * - * @param httpReqParam http parameter name, but never null - */ - public void addParameterNameToWhiteList(String httpReqParam) { - if (MiscUtil.isNotEmpty(httpReqParam)) - reqParameterWhiteListeForModules.add(httpReqParam); - - } - - - /** - * Checks if a authenticated MOASession already exists and if {protocolRequest} is authenticated - * - * @param protocolRequest Authentication request which is actually in process - * @param moaSession MOASession with authentication information or null if no active MOASession exists - * - * @return true if session is already authenticated, otherwise false - * @throws MOAIDException - */ - private boolean tryPerformAuthentication(RequestImpl protocolRequest, AuthenticationSession ssoMOASession) { - - //if no MOASession exist -> authentication is required - if (ssoMOASession == null) { - return false; - - } else { - //if MOA SSO-Session is found but not authenticated --> authentication is required - if (!ssoMOASession.isAuthenticated()) { - return false; - } - - //if MOASession is already authenticated and protocol-request is authenticated - // --> no authentication is required any more - else if (ssoMOASession.isAuthenticated() && protocolRequest.isAuthenticated()) { - protocolRequest.setInternalSSOSessionIdentifier(ssoMOASession.getSessionID()); - return true; - - // if MOASession is authenticated and SSO is allowed --> authenticate pendingRequest - } else if (!protocolRequest.isAuthenticated() - && ssoMOASession.isAuthenticated() && protocolRequest.needSingleSignOnFunctionality()) { - Logger.debug("Found active MOASession and SSO is allowed --> pendingRequest is authenticted"); - protocolRequest.setAuthenticated(true); - protocolRequest.setInternalSSOSessionIdentifier(ssoMOASession.getSessionID()); - return true; - - } - - // force authentication as backup solution - else { - Logger.warn("Authentication-required check find an unsuspected state --> force authentication"); - return false; - - } - } - } - - private void startAuthenticationProcess(HttpServletRequest httpReq, - HttpServletResponse httpResp, RequestImpl pendingReq) - throws ServletException, IOException, MOAIDException { - - Logger.info("Starting authentication ..."); - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_START); - - //is legacy allowed - List<String> legacyallowed_prot = authConfig.getLegacyAllowedProtocols(); - boolean legacyallowed = legacyallowed_prot.contains(pendingReq.requestedModule()); - - //check legacy request parameter - boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(httpReq); - - //create authentication process execution context - ExecutionContext executionContext = new ExecutionContextImpl(); - - //set oaIdentifeir - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_UNIQUE_OA_IDENTFIER, - pendingReq.getOnlineApplicationConfiguration().getPublicURLPrefix()); - - //set interfederation authentication flag - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH, - MiscUtil.isNotEmpty( - pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); - - //set legacy mode or BKU-selection flags - boolean leagacyMode = (legacyallowed && legacyparamavail); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_ISLEGACYREQUEST, leagacyMode); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, !leagacyMode - && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); - - //add X509 SSL client certificate if exist - if (httpReq.getAttribute("javax.servlet.request.X509Certificate") != null) { - Logger.debug("Find SSL-client-certificate on request --> Add it to context"); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_SSL_CLIENT_CERTIFICATE, - ((X509Certificate[])httpReq.getAttribute("javax.servlet.request.X509Certificate"))); - - } - - //add additional http request parameter to context - if (!reqParameterWhiteListeForModules.isEmpty() || leagacyMode) { - Enumeration<String> reqParamNames = httpReq.getParameterNames(); - while(reqParamNames.hasMoreElements()) { - String paramName = reqParamNames.nextElement(); - if (MiscUtil.isNotEmpty(paramName) && - ( MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName) - || reqParameterWhiteListeForModules.contains(paramName) )) - executionContext.put(paramName, - StringEscapeUtils.escapeHtml(httpReq.getParameter(paramName))); - } - } - - //start process engine - startProcessEngine(pendingReq, executionContext); - - } - - private void sendSingleSignOnConsentsEvaluation(HttpServletRequest request, - HttpServletResponse response, RequestImpl pendingReq) - throws ServletException, IOException, MOAIDException { - - Logger.info("Start SSO user-consents evaluation ..."); - - //set authenticated flag to false, because user consents is required - pendingReq.setAuthenticated(false); - - //create execution context - ExecutionContext executionContext = new ExecutionContextImpl(); - executionContext.put(SingleSignOnConsentsModuleImpl.PARAM_SSO_CONSENTS_EVALUATION, true); - - //start process engine - startProcessEngine(pendingReq, executionContext); - - } - - private void startProcessEngine(RequestImpl pendingReq, ExecutionContext executionContext) throws MOAIDException { - try { - //put pending-request ID on execurtionContext - executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, pendingReq.getRequestID()); - - // create process instance - String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); - - if (processDefinitionId == null) { - Logger.warn("No suitable process found for SessionID " + pendingReq.getRequestID() ); - throw new MOAIDException("process.02",new Object[] { - pendingReq.getRequestID()}); - } - - String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); - - // keep process instance id in protocol pending-request - pendingReq.setProcessInstanceId(processInstanceId); - - //store pending-request - requestStoreage.storePendingRequest(pendingReq); - - // start process - processEngine.start(pendingReq); - - } catch (ProcessExecutionException e) { - Throwable cause = e.getCause(); - if (cause != null && cause instanceof TaskExecutionException) { - Throwable taskCause = cause.getCause(); - if (taskCause != null && taskCause instanceof MOAIDException) { - MOAIDException moaTaskCause = (MOAIDException) taskCause; - Logger.warn(taskCause); - throw moaTaskCause; - - } - } - - throw new MOAIDException("process.01", new Object[] { pendingReq.getProcessInstanceId(), pendingReq.getRequestID() }, e); - } - } - - private void performSingleLogOut(HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthenticationSession session, PVPTargetConfiguration pvpReq, String authURL) throws MOAIDException { + @Override + public ISLOInformationContainer performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq, String internalSSOId) + throws EAAFException { String pvpSLOIssuer = null; - String inboundRelayState = null; String uniqueSessionIdentifier = "notSet"; String uniqueTransactionIdentifier = "notSet"; - + PVPSProfilePendingRequest pvpReq = null; Logger.debug("Start technical Single LogOut process ... "); - if (pvpReq != null) { - MOARequest samlReq = (MOARequest) pvpReq.getRequest(); - LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); - pvpSLOIssuer = logOutReq.getIssuer().getValue(); - inboundRelayState = samlReq.getRelayState(); - uniqueSessionIdentifier = pvpReq.getUniqueSessionIdentifier(); - uniqueTransactionIdentifier = pvpReq.getUniqueTransactionIdentifier(); + + if (pendingReq != null) { + uniqueSessionIdentifier = pendingReq.getUniqueSessionIdentifier(); + uniqueTransactionIdentifier = pendingReq.getUniqueTransactionIdentifier(); + + if (pendingReq instanceof PVPSProfileRequest) { + pvpReq = ((PVPSProfilePendingRequest)pendingReq); + PVPSProfileRequest samlReq = (PVPSProfileRequest) pvpReq.getRequest(); + LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); + pvpSLOIssuer = logOutReq.getIssuer().getValue(); + } + if (MiscUtil.isEmpty(internalSSOId)) + internalSSOId = pendingReq.getInternalSSOSessionIdentifier(); + } else { AuthenticationSessionExtensions sessionExt; try { - sessionExt = authenticatedSessionStore.getAuthenticationSessionExtensions(session.getSessionID()); + sessionExt = authenticatedSessionStore.getAuthenticationSessionExtensions(internalSSOId); if (sessionExt != null) uniqueSessionIdentifier = sessionExt.getUniqueSessionId(); @@ -520,8 +111,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { } //store active OAs to SLOContaine - List<OASessionStore> dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); - List<InterfederationSessionStore> dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); + List<OASessionStore> dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(internalSSOId); + List<InterfederationSessionStore> dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(internalSSOId); SLOInformationContainer sloContainer = new SLOInformationContainer(); sloContainer.setTransactionID(uniqueTransactionIdentifier); sloContainer.setSessionID(uniqueSessionIdentifier); @@ -534,13 +125,13 @@ public class AuthenticationManager extends MOAIDAuthConstants { + " BackChannel:" + sloContainer.getActiveBackChannelOAs().size() + " FrontChannel:" + sloContainer.getActiveFrontChannalOAs().size() + " NO_SLO_Support:" + sloContainer.getSloFailedOAs().size()); - + + //terminate MOASession try { - authenticatedSessionStore.destroyInternalSSOSession(session.getSessionID()); - ssoManager.deleteSSOSessionID(httpReq, httpResp); + authenticatedSessionStore.destroyInternalSSOSession(internalSSOId); + ssoManager.destroySSOSessionOnIDPOnly(httpReq, httpResp, pendingReq); revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, uniqueSessionIdentifier); - Logger.debug("Active SSO Session on IDP is remove."); } catch (MOADatabaseException e) { @@ -549,165 +140,48 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - Logger.trace("Starting Service-Provider logout process ... "); - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_STARTED); - //start service provider back channel logout process - Iterator<String> nextOAInterator = sloContainer.getNextBackChannelOA(); - while (nextOAInterator.hasNext()) { - SLOInformationImpl sloDescr = sloContainer.getBackChannelOASessionDescripten(nextOAInterator.next()); - LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(sloDescr); - - try { - Logger.trace("Send backchannel SLO Request to " + sloDescr.getSpEntityID()); - List<XMLObject> soapResp = MOASAMLSOAPClient.send(sloDescr.getServiceURL(), sloReq); - - LogoutResponse sloResp = null; - for (XMLObject el : soapResp) { - if (el instanceof LogoutResponse) - sloResp = (LogoutResponse) el; - } - - if (sloResp == null) { - Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() - + " FAILED. NO LogOut response received."); - sloContainer.putFailedOA(sloDescr.getSpEntityID()); - - } else { - samlVerificationEngine.verifySLOResponse(sloResp, - TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); - - } - - sloBuilder.checkStatusCode(sloContainer, sloResp); - - } catch (SOAPException e) { - Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() - + " FAILED.", e); - sloContainer.putFailedOA(sloDescr.getSpEntityID()); - - } catch (SecurityException | InvalidProtocolRequestException e) { - Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() - + " FAILED.", e); - sloContainer.putFailedOA(sloDescr.getSpEntityID()); - - } - } - - //start service provider front channel logout process - try { - if (sloContainer.hasFrontChannelOA()) { - String relayState = Random.nextRandom(); - - Collection<Entry<String, SLOInformationImpl>> sloDescr = sloContainer.getFrontChannelOASessionDescriptions(); - List<String> sloReqList = new ArrayList<String>(); - for (Entry<String, SLOInformationImpl> el : sloDescr) { - Logger.trace("Build frontChannel SLO Request for " + el.getValue().getSpEntityID()); - - LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(el.getValue()); - try { - sloReqList.add(sloBuilder.getFrontChannelSLOMessageURL(el.getValue().getServiceURL(), el.getValue().getBinding(), - sloReq, httpReq, httpResp, relayState)); - - } catch (Exception e) { - Logger.warn("Failed to build SLO request for OA:" + el.getKey()); - sloContainer.putFailedOA(el.getKey()); - - } - } - - //put SLO process-information into transaction storage - transactionStorage.put(relayState, sloContainer, -1); - - if (MiscUtil.isEmpty(authURL)) - authURL = pvpReq.getAuthURL(); - - String timeOutURL = authURL - + "/idpSingleLogout" - + "?restart=" + relayState; - - DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( - authURL, - DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, - null); - - config.putCustomParameterWithOutEscaption("redirectURLs", sloReqList); - config.putCustomParameterWithOutEscaption("timeoutURL", timeOutURL); - config.putCustomParameter("timeout", String.valueOf(SLOTIMEOUT)); - - guiBuilder.build(httpResp, config, "Single-LogOut GUI"); - - - } else { - if (pvpReq != null) { - //send SLO response to SLO request issuer - SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); - sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState, pvpReq); - - } else { - //print SLO information directly - DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( - authURL, - DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, - null); - - if (sloContainer.getSloFailedOAs() == null || - sloContainer.getSloFailedOAs().size() == 0) { - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); - config.putCustomParameter("successMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); - - } else { - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); - config.putCustomParameterWithOutEscaption("errorMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - - } - guiBuilder.build(httpResp, config, "Single-LogOut GUI"); - - } - - } + return sloContainer; - } catch (GUIBuildException e) { - Logger.warn("Can not build GUI:'Single-LogOut'. Msg:" + e.getMessage()); - throw new MOAIDException("builder.09", new Object[]{e.getMessage()}, e); + } + + @Override + protected void populateExecutionContext(ExecutionContext executionContext, RequestImpl pendingReq, HttpServletRequest httpReq) + throws EAAFException { + //is legacy allowed + boolean legacyallowed = false; + if (authConfig instanceof AuthConfiguration) { + List<String> legacyallowed_prot = ((AuthConfiguration)authConfig).getLegacyAllowedProtocols(); + legacyallowed = legacyallowed_prot.contains(pendingReq.requestedModule()); - } catch (MOADatabaseException e) { - Logger.error("MOA AssertionDatabase ERROR", e); - if (pvpReq != null) { - SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState, pvpReq); + } else + Logger.info("Base configuration is NOT of type 'AuthConfiguration'. LegacyMode is disabled"); + - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); + //check legacy request parameter + boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(httpReq); - }else { - //print SLO information directly - DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( - authURL, - DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, - null); + + //set interfederation authentication flag + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH, + MiscUtil.isNotEmpty( + pendingReq.getRawData(SSOManager.DATAID_INTERFEDERATIOIDP_URL, String.class))); + + //set legacy mode or BKU-selection flags + boolean leagacyMode = (legacyallowed && legacyparamavail); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_ISLEGACYREQUEST, leagacyMode); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, !leagacyMode + && MiscUtil.isEmpty(pendingReq.getRawData(SSOManager.DATAID_INTERFEDERATIOIDP_URL, String.class))); - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); - config.putCustomParameterWithOutEscaption("errorMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - - try { - guiBuilder.build(httpResp, config, "Single-LogOut GUI"); - - } catch (GUIBuildException e1) { - Logger.warn("Can not build GUI:'Single-LogOut'. Msg:" + e.getMessage()); - throw new MOAIDException("builder.09", new Object[]{e.getMessage()}, e); - - } - - } - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + //add additional http request parameter to context + if (leagacyMode) { + Enumeration<String> reqParamNames = httpReq.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (StringUtils.isNotEmpty(paramName) && MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName) ) + executionContext.put(paramName, StringEscapeUtils.escapeHtml(httpReq.getParameter(paramName))); + } + } + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java deleted file mode 100644 index ae2771427..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; - -public interface IAction { - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) - throws MOAIDException; - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp); - - public String getDefaultActionName(); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java deleted file mode 100644 index b9b161bb6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.commons.api.IRequest; - - -public interface IModulInfo { - //public List<ServletInfo> getServlets(); - public String getName(); - public String getPath(); - - public boolean generateErrorMessage(Throwable e, - HttpServletRequest request, HttpServletResponse response, - IRequest protocolRequest) throws Throwable; - - public boolean validate(HttpServletRequest request, - HttpServletResponse response, IRequest pending); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java deleted file mode 100644 index 987d92e16..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.moduls; - -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; - -/** - * @author tlenz - * - */ -public interface IRequestStorage { - - public IRequest getPendingRequest(String pendingReqID); - - public void storePendingRequest(IRequest pendingRequest) throws MOAIDException; - - public void removePendingRequest(String requestID); - - public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException, MOADatabaseException; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java deleted file mode 100644 index f1db466e9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; - -public class NoPassivAuthenticationException extends MOAIDException { - - public NoPassivAuthenticationException() { - super("auth.18", null); - } - - /** - * - */ - private static final long serialVersionUID = 596920452166197688L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java deleted file mode 100644 index b87574d52..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ /dev/null @@ -1,454 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import java.io.Serializable; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; - -import org.opensaml.saml2.metadata.provider.MetadataProvider; - -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionWrapper; -import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.commons.api.data.AuthProzessDataConstants; -import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; -import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public abstract class RequestImpl implements IRequest, Serializable{ - - public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; - public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; - public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; - public static final String DATAID_INTERFEDERATIOIDP_ENTITYID = "interIDPEntityID"; - - public static final String DATAID_REQUESTER_IP_ADDRESS = "requesterIP"; - -// public static final String eIDAS_GENERIC_REQ_DATA_COUNTRY = "country"; - public static final String eIDAS_GENERIC_REQ_DATA_LEVELOFASSURENCE = "eIDAS_LoA"; - - - - private static final long serialVersionUID = 1L; - - private String module = null; - private String action = null; - - private String requestID; - private String processInstanceId; - private String ssoMoaSessionId; - - private String uniqueTransactionIdentifer; - private String uniqueSessionIdentifer; - - private String oaURL; - private String authURL = null; - - private IOAAuthParameters OAConfiguration = null; - - private boolean passiv = false; - private boolean force = false; - private boolean needSSO = false; - private boolean isAbortedByUser = false; - - //every request needs authentication by default - private boolean needAuthentication = true; - - //every request is not authenticated by default - private boolean isAuthenticated = false; - - private Map<String, Object> genericDataStorage = new HashMap<String, Object>(); - - private IAuthenticationSession moaSSOSessionContainer = null; - - - /** - * @throws ConfigurationException - * - */ - public final void initialize(HttpServletRequest req) throws ConfigurationException { - //set requestID - requestID = Random.nextLongRandom(); - - //set unique transaction identifier for logging - uniqueTransactionIdentifer = Random.nextLongRandom(); - TransactionIDUtils.setTransactionId(uniqueTransactionIdentifer); - - //initialize session object - genericDataStorage.put(AuthProzessDataConstants.VALUE_CREATED, new Date()); - genericDataStorage.put(AuthProzessDataConstants.VALUE_SESSIONID, Random.nextLongRandom()); - - //check if End-Point is valid - String authURLString = HTTPUtils.extractAuthURLFromRequest(req); - URL authURL; - try { - authURL = new URL(authURLString); - - } catch (MalformedURLException e) { - Logger.error("IDP AuthenticationServiceURL Prefix is not a valid URL." + authURLString, e); - throw new ConfigurationException("1299", null, e); - - } - - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - List<String> configuredPublicURLPrefix = config.getPublicURLPrefix(); - - if (!config.isVirtualIDPsEnabled()) { - Logger.trace("Virtual IDPs are disabled. Use default IDP PublicURLPrefix from configuration: " + configuredPublicURLPrefix.get(0)); - this.authURL = configuredPublicURLPrefix.get(0); - - } else { - Logger.debug("Extract AuthenticationServiceURL: " + authURLString); - URL resultURL = null; - - for (String el : configuredPublicURLPrefix) { - try { - URL configuredURL = new URL(el); - - //get Ports from URL - int configPort = configuredURL.getPort(); - if (configPort == -1) - configPort = configuredURL.getDefaultPort(); - - int authURLPort = authURL.getPort(); - if (authURLPort == -1) - authURLPort = authURL.getDefaultPort(); - - //check AuthURL against ConfigurationURL - if (configuredURL.getHost().equals(authURL.getHost()) && - configPort == authURLPort && - configuredURL.getPath().equals(authURL.getPath())) { - Logger.debug("Select configurated PublicURLPrefix: " + configuredURL - + " for authURL: " + authURLString); - resultURL = configuredURL; - } - - } catch (MalformedURLException e) { - Logger.error("Configurated IDP PublicURLPrefix is not a valid URL." + el); - - } - } - - if (resultURL == null) { - Logger.warn("Extract AuthenticationServiceURL: " + authURL + " is NOT found in configuration."); - throw new ConfigurationException("config.25", new Object[]{authURLString}); - - } else { - this.authURL = resultURL.toExternalForm(); - - } - } - - //set unique session identifier - String uniqueID = (String) req.getAttribute(MOAIDConstants.UNIQUESESSIONIDENTIFIER); - if (MiscUtil.isNotEmpty(uniqueID)) - uniqueSessionIdentifer = uniqueID; - - else - Logger.warn("No unique session-identifier FOUND, but it should be allready set into request!?!"); - - //set requester's IP address - try { - setGenericDataToSession(DATAID_REQUESTER_IP_ADDRESS, req.getRemoteAddr()); - - } catch (SessionDataStorageException e) { - Logger.warn("Can not store remote IP address to 'pendingRequest' during an exception." , e); - - } - - } - - /** - * This method map the protocol specific requested attributes to PVP 2.1 attributes. - * - * @return List of PVP 2.1 attribute names with maps all protocol specific attributes - */ - public abstract Collection<String> getRequestedAttributes(MetadataProvider metadataProvider); - - public void setOAURL(String value) { - oaURL = value; - } - - public String getOAURL() { - return oaURL; - } - - public boolean isPassiv() { - return passiv; - } - - public boolean forceAuth() { - return force; - } - - public void setPassiv(boolean passiv) { - this.passiv = passiv; - } - - public void setForce(boolean force) { - this.force = force; - } - - public String requestedAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - /** - * @return the module - */ - public String requestedModule() { - return module; - } - - /** - * @param module the module to set - */ - public void setModule(String module) { - this.module = module; - } - - public void setRequestID(String id) { - this.requestID = id; - - } - - public String getRequestID() { - return requestID; - } - - public String getInternalSSOSessionIdentifier() { - return this.ssoMoaSessionId; - } - - /** - * Set the internal SSO session identifier, which associated with this pending request - * - * @param internalSSOSessionId - */ - public void setInternalSSOSessionIdentifier(String internalSSOSessionId) { - this.ssoMoaSessionId = internalSSOSessionId; - - } - - public IAuthenticationSession getMOASession() { - //if SSO session information are set, use this - if (moaSSOSessionContainer != null) - return moaSSOSessionContainer; - - else - return new AuthenticationSessionWrapper(genericDataStorage); - - } - - public void populateMOASessionWithSSOInformation(IAuthenticationSession ssoSession) { - if (ssoSession instanceof AuthenticationSession) { - moaSSOSessionContainer = ssoSession; - - } else - throw new IllegalStateException("Session information can only be populated with SSO information from database"); - - - } - - - public IOAAuthParameters getOnlineApplicationConfiguration() { - return this.OAConfiguration; - - } - - public void setOnlineApplicationConfiguration(IOAAuthParameters oaConfig) { - this.OAConfiguration = oaConfig; - - } - - public String getUniqueTransactionIdentifier() { - return this.uniqueTransactionIdentifer; - - } - - public String getUniqueSessionIdentifier() { - return this.uniqueSessionIdentifer; - - } - - public String getProcessInstanceId() { - return this.processInstanceId; - - } - - public void setUniqueTransactionIdentifier(String id) { - this.uniqueTransactionIdentifer = id; - - } - - public void setUniqueSessionIdentifier(String id) { - this.uniqueSessionIdentifer = id; - - } - - public void setProcessInstanceId(String id) { - this.processInstanceId = id; - - } - - /** - * @return the authURL - */ - public String getAuthURL() { - return authURL; - } - - public String getAuthURLWithOutSlash() { - if (authURL.endsWith("/")) - return authURL.substring(0, authURL.length()-1); - else - return authURL; - - } - - /** - * @return the needAuthentication - */ - public boolean isNeedAuthentication() { - return needAuthentication; - } - - /** - * @param needAuthentication the needAuthentication to set - */ - public void setNeedAuthentication(boolean needAuthentication) { - this.needAuthentication = needAuthentication; - } - - /** - * @return the isAuthenticated - */ - public boolean isAuthenticated() { - return isAuthenticated; - } - - /** - * @param isAuthenticated the isAuthenticated to set - */ - public void setAuthenticated(boolean isAuthenticated) { - this.isAuthenticated = isAuthenticated; - } - - public boolean needSingleSignOnFunctionality() { - return needSSO; - } - public void setNeedSingleSignOnFunctionality(boolean needSSO) { - this.needSSO = needSSO; - - } - - public boolean isAbortedByUser() { - return this.isAbortedByUser; - } - - public void setAbortedByUser(boolean isAborted) { - this.isAbortedByUser = isAborted; - - } - - public Object getGenericData(String key) { - if (MiscUtil.isNotEmpty(key)) { - return genericDataStorage.get(key); - - } - - Logger.warn("Can not load generic request-data with key='null'"); - return null; - } - - public <T> T getGenericData(String key, final Class<T> clazz) { - if (MiscUtil.isNotEmpty(key)) { - Object data = genericDataStorage.get(key); - - if (data == null) - return null; - - try { - @SuppressWarnings("unchecked") - T test = (T) data; - return test; - - } catch (Exception e) { - Logger.warn("Generic request-data object can not be casted to requested type", e); - return null; - - } - - } - - Logger.warn("Can not load generic request-data with key='null'"); - return null; - - } - - public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException { - if (MiscUtil.isEmpty(key)) { - Logger.warn("Generic request-data can not be stored with a 'null' key"); - throw new SessionDataStorageException("Generic request-data can not be stored with a 'null' key", null); - - } - - if (object != null) { - if (!Serializable.class.isInstance(object)) { - Logger.warn("Generic request-data can only store objects which implements the 'Seralizable' interface"); - throw new SessionDataStorageException("Generic request-data can only store objects which implements the 'Seralizable' interface", null); - - } - } - - if (genericDataStorage.containsKey(key)) - Logger.debug("Overwrite generic request-data with key:" + key); - else - Logger.trace("Add generic request-data with key:" + key + " to session."); - - genericDataStorage.put(key, object); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java deleted file mode 100644 index 90ccb3c27..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ /dev/null @@ -1,135 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAO; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.logging.Logger; - -@Service("RequestStorage") -public class RequestStorage implements IRequestStorage{ - - @Autowired ITransactionStorage transactionStorage; - @Autowired ProcessInstanceStoreDAO processInstanceStore; - - @Override - public IRequest getPendingRequest(String pendingReqID) { - - try { - IRequest pendingRequest = transactionStorage.get(pendingReqID, IRequest.class); - if (pendingRequest == null) { - Logger.info("No PendingRequst found with pendingRequestID " + pendingReqID); - return null; - - } - - //set transactionID and sessionID to Logger - TransactionIDUtils.setAllLoggingVariables(pendingRequest); - - return pendingRequest; - - } catch (MOADatabaseException | NullPointerException e) { - Logger.info("No PendingRequst found with pendingRequestID " + pendingReqID); - return null; - - } - } - - @Override - public void storePendingRequest(IRequest pendingRequest) throws MOAIDException { - try { - if (pendingRequest instanceof IRequest) { - transactionStorage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest, -1); - - } else { - throw new MOAIDException("auth.20", null); - - } - - } catch (MOADatabaseException e) { - Logger.warn("Pending Request with ID=" + ((IRequest)pendingRequest).getRequestID() + - " can not stored.", e); - throw new MOAIDException("auth.20", null); - } - - } - - @Override - public void removePendingRequest(String requestID) { - - if (requestID != null) { - - //remove process-management execution instance - try { - IRequest pendingReq = getPendingRequest(requestID); - - if (pendingReq != null && - pendingReq.getProcessInstanceId() != null) { - processInstanceStore.remove(pendingReq.getProcessInstanceId()); - - } - - } catch (MOADatabaseException e) { - Logger.warn("Removing process associated with pending-request:" + requestID + " FAILED.", e); - - } - - transactionStorage.remove(requestID); - - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.storage.IRequestStorage#changePendingRequestID(at.gv.egovernment.moa.id.moduls.IRequest) - */ - @Override - public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException, MOADatabaseException { - - if (pendingRequest instanceof RequestImpl) { - String newRequestID = Random.nextRandom(); - String oldRequestID = pendingRequest.getRequestID(); - - Logger.debug("Change pendingRequestID from " + pendingRequest.getRequestID() - + " to " + newRequestID); - - ((RequestImpl)pendingRequest).setRequestID(newRequestID); - transactionStorage.changeKey(oldRequestID, newRequestID, pendingRequest); - //only delete oldRequestID, no change. - - return newRequestID; - - } else { - Logger.error("PendingRequest object is not of type 'RequestImpl.class'"); - throw new MOAIDException("internal.00", null); - } - - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java index 557d9af48..b5005d0c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java @@ -23,32 +23,49 @@ package at.gv.egovernment.moa.id.moduls; import java.util.Date; +import java.util.Map; +import java.util.Map.Entry; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.auth.ISSOManager; +import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; +import at.gv.egiz.eaaf.core.exceptions.EAAFSSOException; +import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; 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.AuthenticationException; +import at.gv.egovernment.moa.id.auth.exception.BuildException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.db.dao.session.AuthenticatedSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OldSSOSessionIDStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.id.util.legacy.LegacyHelper; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Service("MOAID_SSOManager") -public class SSOManager { +public class SSOManager implements ISSOManager { + private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; private static final String HTMLTEMPLATEFULL = "slo_template.html"; public static String CONTEXTPATH = "contextPath"; @@ -58,10 +75,228 @@ public class SSOManager { private static final int INTERFEDERATIONCOOKIEMAXAGE = 5 * 60;// sec + public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; + public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; + public static final String DATAID_INTERFEDERATIOIDP_ENTITYID = "interIDPEntityID"; + + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; - @Autowired protected AuthConfiguration authConfig; + @Autowired private AuthConfiguration authConfig; + @Autowired private IRevisionLogger revisionsLogger; + + + + //@Autowired private MOASessionDBUtils moaSessionDBUtils; + @Override + public boolean checkAndValidateSSOSession(IRequest pendingReq, HttpServletRequest httpReq, HttpServletResponse httpResp) throws EAAFSSOException { + try { + //get SSO cookie from http request + String ssoId = getSSOSessionID(httpReq); + + //check if interfederation IDP is requested + checkInterfederationIsRequested(httpReq, httpResp, pendingReq); + + //check if SSO session cookie is already used + if (ssoId != null) { + String correspondingMOASession = existsOldSSOSession(ssoId); + + if (correspondingMOASession != null) { + Logger.warn("Request sends an old SSO Session ID("+ssoId+")! " + + "Invalidate the corresponding MOASession with ID="+ correspondingMOASession); + + revisionsLogger.logEvent(pendingReq, EVENT_SSO_SESSION_INVALID); + + //destroy internal SSO-session object and SSO-session cooky + authenticatedSessionStore.destroyInternalSSOSession(correspondingMOASession); + deleteSSOSessionID(httpReq, httpResp); + } + } + + //check if SSO Session is valid + boolean isSSOValid = isValidSSOSession(ssoId, pendingReq); + + return isSSOValid; + + + } catch (SessionDataStorageException | ConfigurationException | EAAFStorageException e) { + Logger.warn("Cann not process SSO session. Reason: " + e.getMessage(), e); + Logger.info("All SSO session will be ignored."); + + } + + return false; + + } + + + @Override + public void isSSOAllowedForSP(IRequest pendingReq, HttpServletRequest httpReq) { + // check if Service-Provider allows SSO sessions + IOAAuthParameters oaConfig = pendingReq.getServiceProviderConfiguration(OAAuthParameterDecorator.class); + boolean useSSOOA = oaConfig.useSSO() || oaConfig.isInderfederationIDP(); + + //if a legacy request is used SSO should not be allowed in case of mandate authentication + boolean isUseMandateRequested = false; + try { + isUseMandateRequested = LegacyHelper.isUseMandateRequested(httpReq); + + //check if SSO is allowed for the actually executed request + //INFO: Actually, useMandate disables SSO functionality!!!!! + pendingReq.setNeedSingleSignOnFunctionality((useSSOOA && !isUseMandateRequested)); + + //check if current service provider needs user consent for SSO + pendingReq.setNeedUserConsent(oaConfig.useSSOQuestion()); + + } catch (WrongParametersException e) { + Logger.warn("Find suspect http parameter for mandates! Reason: " + e.getMessage()); + + } + + } + + @Override + public void populatePendingRequestWithSSOInformation(IRequest pendingReq) throws EAAFSSOException { + //populate pending request with eID data from SSO session if no userConsent is required + try { + AuthenticationSession ssoMOASession = authenticatedSessionStore.getInternalSSOSession(pendingReq.getInternalSSOSessionIdentifier()); + + if (ssoMOASession == null) + Logger.info("No MOASession FOUND with provided SSO-Cookie."); + + else { + Logger.debug("Found authenticated MOASession with provided SSO-Cookie."); + revisionsLogger.logEvent(pendingReq, EVENT_SSO_SESSION_VALID); + + Logger.trace("Populatint pending request with SSO session information .... "); + Map<String, Object> fullSSOData = ssoMOASession.getKeyValueRepresentationFromAuthSession(); + if (Logger.isTraceEnabled()) { + Logger.trace("Full SSO DataSet: "); + for (Entry<String, Object> el : fullSSOData.entrySet()) { + Logger.trace(" Key: " + el.getKey() + " Value: " + el.getValue()); + + } + + } + pendingReq.setRawDataToTransaction(fullSSOData); + pendingReq.setAuthenticated(true); + + } + + } catch (EAAFStorageException e) { + Logger.warn("Can NOT populate pending request from SSO session.", e); + throw new EAAFSSOException("", new Object[] {}, e); + + } + + } + + + @Override + public boolean destroySSOSessionOnIDPOnly(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq) throws EAAFSSOException { + //get SSO token from request + String internalSSOSessionId = null; + try { + if (pendingReq != null && MiscUtil.isNotEmpty(pendingReq.getInternalSSOSessionIdentifier())) { + internalSSOSessionId = pendingReq.getInternalSSOSessionIdentifier(); + + } else { + String ssoid = getSSOSessionID(httpReq); + if (isValidSSOSession(ssoid, null)) { + internalSSOSessionId = authenticatedSessionStore.getInternalSSOSessionWithSSOID(ssoid); + + } + } + + //destroy SSO session if it was found + if (StringUtils.isNotEmpty(internalSSOSessionId)) { + //delete SSO session and MOA session + AuthenticationSession ssoMOASession = authenticatedSessionStore.getInternalSSOSession(internalSSOSessionId); + + if (ssoMOASession == null) { + Logger.info("No internal MOA SSO-Session found. Nothing to destroy"); + return false; + + } + + + ssoMOASession.setAuthenticated(false); + + //log Session_Destroy to reversionslog + AuthenticationSessionExtensions sessionExtensions = + authenticatedSessionStore.getAuthenticationSessionExtensions(ssoMOASession.getSSOSessionID()); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); + authenticatedSessionStore.destroyInternalSSOSession(ssoMOASession.getSSOSessionID()); + } + + } catch (ConfigurationException | SessionDataStorageException | EAAFStorageException e) { + Logger.info("NO MOA Authentication data for ID " + internalSSOSessionId); + return false; + + } + + + //Remove SSO token + deleteSSOSessionID(httpReq, httpResp); + + return true; + + } + + @Override + public String createNewSSOSessionCookie(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq) + throws EAAFSSOException { + Logger.debug("Creating new SSO session-cookie for http response ... "); + + //Store SSO information into database + String newSSOSessionId = Random.nextHexRandom32(); + + //set SSO cookie to response + if (StringUtils.isNotEmpty(newSSOSessionId)) + setSSOSessionID(httpReq, httpResp, newSSOSessionId); + else + deleteSSOSessionID(httpReq, httpResp); + + return newSSOSessionId; + } + + +@Override +public void createNewSSOSession(IRequest pendingReq, String newSSOSessionId) throws EAAFSSOException { + AuthenticationSession internalDBSSOSession; + try { + internalDBSSOSession = authenticatedSessionStore.createInternalSSOSession(pendingReq); + pendingReq.setInternalSSOSessionIdentifier(internalDBSSOSession.getSSOSessionID()); + + } catch (MOADatabaseException | BuildException e) { + Logger.warn("Can NOT create SSO session.", e); + throw new EAAFSSOException("builder.10", null, e); + + } + +} + + +@Override +public void updateSSOSession(IRequest pendingReq, String newSSOSessionId, SLOInformationInterface sloInformation) throws EAAFSSOException { + try { + authenticatedSessionStore.addSSOInformation( + pendingReq.getInternalSSOSessionIdentifier(), + newSSOSessionId, + sloInformation, + pendingReq); + + } catch (AuthenticationException e) { + Logger.warn("Can NOT update SSO session.", e); + throw new EAAFSSOException("builder.10", null, e); + } + +} + + + //*********************************** old ************************************** + /** * Check if interfederation IDP is requested via HTTP GET parameter or if interfederation cookie exists. * Set the requested interfederation IDP as attribte of the {protocolRequest} @@ -70,14 +305,15 @@ public class SSOManager { * @param httpResp HttpServletResponse * @param protocolRequest Authentication request which is actually in process * @throws SessionDataStorageException + * @throws EAAFStorageException * **/ public void checkInterfederationIsRequested(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest protocolRequest) throws SessionDataStorageException { + IRequest protocolRequest) throws SessionDataStorageException, EAAFStorageException { String interIDP = httpReq.getParameter(MOAIDAuthConstants.INTERFEDERATION_IDP); String interfederationIDP = - protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + protocolRequest.getRawData(DATAID_INTERFEDERATIOIDP_URL, String.class); if (MiscUtil.isNotEmpty(interfederationIDP)) { Logger.debug("Protocolspecific preprocessing already set interfederation IDP " + interfederationIDP); return; @@ -89,14 +325,14 @@ public class SSOManager { RequestImpl moaReq = (RequestImpl) protocolRequest; if (MiscUtil.isNotEmpty(interIDP)) { Logger.info("Receive SSO request for interfederation IDP " + interIDP); - moaReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, interIDP); + moaReq.setRawDataToTransaction(DATAID_INTERFEDERATIOIDP_URL, interIDP); } else { //check if IDP cookie is set String cookie = getValueFromCookie(httpReq, SSOINTERFEDERATION); if (MiscUtil.isNotEmpty(cookie)) { Logger.info("Receive SSO request for interfederated IDP from Cookie " + cookie); - moaReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, cookie); + moaReq.setRawDataToTransaction(DATAID_INTERFEDERATIOIDP_URL, cookie); deleteCookie(httpReq, httpResp, SSOINTERFEDERATION); } @@ -113,8 +349,7 @@ public class SSOManager { } - - public boolean isValidSSOSession(String ssoSessionID, IRequest protocolRequest) throws ConfigurationException, SessionDataStorageException { + public boolean isValidSSOSession(String ssoSessionID, IRequest protocolRequest) throws ConfigurationException, SessionDataStorageException, EAAFStorageException { // search SSO Session if (ssoSessionID == null) { @@ -144,7 +379,7 @@ public class SSOManager { //in case of federated SSO session, jump to federated IDP for authentication String interfederationIDP = - protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + protocolRequest.getRawData(DATAID_INTERFEDERATIOIDP_URL, String.class); if (MiscUtil.isEmpty(interfederationIDP)) { InterfederationSessionStore selectedIDP = authenticatedSessionStore.searchInterfederatedIDPFORSSOWithMOASession(storedSession.getSessionid()); @@ -152,8 +387,8 @@ public class SSOManager { if (selectedIDP != null) { //no local SSO session exist -> request interfederated IDP Logger.info("SSO Session refer to federated IDP: " + selectedIDP.getIdpurlprefix()); - protocolRequest.setGenericDataToSession( - RequestImpl.DATAID_INTERFEDERATIOIDP_URL, selectedIDP.getIdpurlprefix()); + protocolRequest.setRawDataToTransaction( + DATAID_INTERFEDERATIOIDP_URL, selectedIDP.getIdpurlprefix()); } else { Logger.warn("MOASession is marked as interfederated SSO session but no interfederated IDP is found. Switch to local authentication ..."); @@ -170,25 +405,32 @@ public class SSOManager { return false; } - + + //set internal SSO SessionID + if (protocolRequest != null) + protocolRequest.setInternalSSOSessionIdentifier(storedSession.getSessionid()); + return true; } } - public AuthenticationSession getInternalMOASession(String ssoSessionID) throws MOADatabaseException { - return authenticatedSessionStore.getInternalMOASessionWithSSOID(ssoSessionID); - - } +// public String getInternalSSOSession(String ssoSessionID) throws MOADatabaseException { +// return authenticatedSessionStore.getInternalSSOSessionWithSSOID(ssoSessionID); +// +// } //TODO: refactor for faster DB access public String getUniqueSessionIdentifier(String ssoSessionID) { try { if (MiscUtil.isNotEmpty(ssoSessionID)) { - AuthenticationSession moaSession = authenticatedSessionStore.getInternalMOASessionWithSSOID(ssoSessionID); - if (moaSession != null) { - AuthenticationSessionExtensions extSessionInformation = authenticatedSessionStore.getAuthenticationSessionExtensions(moaSession.getSessionID()); + String ssoSessionId = authenticatedSessionStore.getInternalSSOSessionWithSSOID(ssoSessionID); + if (MiscUtil.isNotEmpty(ssoSessionId)) { + AuthenticationSessionExtensions extSessionInformation = authenticatedSessionStore.getAuthenticationSessionExtensions(ssoSessionId); + if (extSessionInformation != null) return extSessionInformation.getUniqueSessionId(); + else + Logger.warn("Extended SSO-Session Information ARE NULL. Something looks wrong!"); } } @@ -199,55 +441,13 @@ public class SSOManager { return null; } - - public String existsOldSSOSession(String ssoId) { - - Logger.trace("Check that the SSOID has already been used"); - - OldSSOSessionIDStore oldSSOSession = authenticatedSessionStore.checkSSOTokenAlreadyUsed(ssoId); - - if (oldSSOSession == null) { - Logger.debug("SSO session-cookie was not used in parst"); - return null; - } - - AuthenticatedSessionStore correspondingMoaSession = oldSSOSession.getMoasession(); - - if (correspondingMoaSession == null) { - Logger.info("Get request with old SSO SessionID but no corresponding SSO Session is found."); - return null; - } - - return correspondingMoaSession.getSessionid(); - - } - - public String createSSOSessionInformations(String moaSessionID, String OAUrl) { - - String newSSOId = Random.nextRandom(); - - if (MiscUtil.isEmpty(moaSessionID) || MiscUtil.isEmpty(OAUrl)) { - Logger.warn("MoaSessionID or OAUrl are empty -> SSO is not enabled!"); - return null; - } - - return newSSOId; - - } - - public void setSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp, String ssoId) { - setCookie(httpReq, httpResp, SSOCOOKIE, ssoId, -1); - - } - + public String getSSOSessionID(HttpServletRequest httpReq) { return getValueFromCookie(httpReq, SSOCOOKIE); } - public void deleteSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp) { - deleteCookie(httpReq, httpResp, SSOCOOKIE); - } + /** * @param entityID @@ -284,7 +484,41 @@ public class SSOManager { return false; } - + + + private String existsOldSSOSession(String ssoId) { + + Logger.trace("Check that the SSOID has already been used"); + + OldSSOSessionIDStore oldSSOSession = authenticatedSessionStore.checkSSOTokenAlreadyUsed(ssoId); + + if (oldSSOSession == null) { + Logger.debug("SSO session-cookie was not used in parst"); + return null; + } + + AuthenticatedSessionStore correspondingMoaSession = oldSSOSession.getMoasession(); + + if (correspondingMoaSession == null) { + Logger.info("Get request with old SSO SessionID but no corresponding SSO Session is found."); + return null; + } + + return correspondingMoaSession.getSessionid(); + + } + + + private void setSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp, String ssoId) { + setCookie(httpReq, httpResp, SSOCOOKIE, ssoId, -1); + + } + + private void deleteSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp) { + deleteCookie(httpReq, httpResp, SSOCOOKIE); + + } + private String getValueFromCookie(HttpServletRequest httpReq, String cookieName) { Cookie[] cookies = httpReq.getCookies(); @@ -312,6 +546,7 @@ public class SSOManager { private void deleteCookie(HttpServletRequest httpReq, HttpServletResponse httpResp, String cookieName) { setCookie(httpReq, httpResp, cookieName, "", 0); + } - + } |