aboutsummaryrefslogtreecommitdiff
path: root/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java
diff options
context:
space:
mode:
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java')
-rw-r--r--id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java1049
1 files changed, 1049 insertions, 0 deletions
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java
new file mode 100644
index 000000000..743caec55
--- /dev/null
+++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java
@@ -0,0 +1,1049 @@
+/*******************************************************************************
+ * Copyright 2014 Federal Chancellery Austria
+ * MOA-ID has been developed in a cooperation between BRZ, the Federal
+ * Chancellery Austria - ICT staff unit, and Graz University of Technology.
+ *
+ * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by
+ * the European Commission - subsequent versions of the EUPL (the "Licence");
+ * You may not use this work except in compliance with the Licence.
+ * You may obtain a copy of the Licence at:
+ * http://www.osor.eu/eupl/
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the Licence is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the Licence for the specific language governing permissions and
+ * limitations under the Licence.
+ *
+ * This product combines work with different licenses. See the "NOTICE" text
+ * file for details on the various modules and licenses.
+ * The "NOTICE" text file is part of the distribution. Any derivative works
+ * that you distribute must include a readable copy of the "NOTICE" text file.
+ *******************************************************************************/
+package at.gv.egovernment.moa.id.storage;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang.StringEscapeUtils;
+import org.hibernate.HibernateException;
+import org.hibernate.Query;
+import org.hibernate.Session;
+import org.hibernate.Transaction;
+import org.springframework.stereotype.Service;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+
+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.commons.db.MOASessionDBUtils;
+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.OASessionStore;
+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.commons.utils.JsonMapper;
+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.data.EncryptedData;
+import at.gv.egovernment.moa.id.data.SLOInformationInterface;
+import at.gv.egovernment.moa.id.moduls.IRequest;
+import at.gv.egovernment.moa.id.moduls.RequestImpl;
+import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption;
+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.util.Random;
+import at.gv.egovernment.moa.id.util.SessionEncrytionUtil;
+import at.gv.egovernment.moa.logging.Logger;
+import at.gv.egovernment.moa.util.MiscUtil;
+
+@Service("AuthenticationSessionStoreage")
+public class DBAuthenticationSessionStoreage implements IAuthenticationSessionStoreage{
+
+ private static JsonMapper mapper = new JsonMapper();
+
+ @Override
+ public boolean isAuthenticated(String moaSessionID) {
+
+ AuthenticatedSessionStore session;
+
+ try {
+ session = searchInDatabase(moaSessionID, true);
+ return session.isAuthenticated();
+
+ } catch (MOADatabaseException e) {
+ return false;
+ }
+ }
+
+ @Override
+ public AuthenticationSession createSession(IRequest target) throws MOADatabaseException, BuildException {
+ String id = Random.nextRandom();
+ try {
+ AuthenticatedSessionStore dbsession = new AuthenticatedSessionStore();
+ dbsession.setSessionid(id);
+ dbsession.setAuthenticated(false);
+
+ //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1
+ Date now = new Date();
+ dbsession.setCreated(now);
+ dbsession.setUpdated(now);
+
+ dbsession.setPendingRequestID(target.getRequestID());
+
+ //set additional session informations
+ AuthenticationSessionExtensions sessionExt = new AuthenticationSessionExtensions();
+ sessionExt.setUniqueSessionId(target.getUniqueSessionIdentifier());
+ dbsession.setAdditionalInformation(mapper.serialize(sessionExt));
+
+ AuthenticationSession session = new AuthenticationSession(id, now);
+ encryptSession(session, dbsession);
+
+ //store AssertionStore element to Database
+ MOASessionDBUtils.saveOrUpdate(dbsession);
+ Logger.info("Create MOASession with sessionID: " + id);
+
+ return session;
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("MOASession could not be created.");
+ throw new MOADatabaseException(e);
+
+ } catch (JsonProcessingException e) {
+ Logger.warn("Extended session information can not be stored.", e);
+ throw new MOADatabaseException(e);
+
+ }
+
+ }
+
+ @Override
+ public AuthenticationSession getSession(String sessionID) throws MOADatabaseException {
+
+ if (MiscUtil.isEmpty(sessionID))
+ return null;
+
+ try {
+ AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true);
+ return decryptSession(dbsession);
+
+ } catch (MOADatabaseException e) {
+ Logger.info("No MOA Session with id: " + sessionID);
+ return null;
+
+ } catch (Throwable e) {
+ Logger.warn("MOASession deserialization-exception by using MOASessionID=" + sessionID, e);
+ throw new MOADatabaseException("MOASession deserialization-exception");
+ }
+ }
+
+ @Override
+ public AuthenticationSessionExtensions getAuthenticationSessionExtensions(String sessionID) throws MOADatabaseException {
+ AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true);
+
+ if (MiscUtil.isNotEmpty(dbsession.getAdditionalInformation())) {
+ try {
+ return (AuthenticationSessionExtensions)mapper.deserialize(dbsession.getAdditionalInformation(),
+ AuthenticationSessionExtensions.class);
+
+ } catch (Exception e) {
+ Logger.warn("Extended session information extraction FAILED!", e);
+ }
+ }
+ return null;
+
+ }
+
+ @Override
+ public void setAuthenticationSessionExtensions(String sessionID, AuthenticationSessionExtensions sessionExtensions) throws MOADatabaseException {
+ try {
+ AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true);
+
+ dbsession.setAdditionalInformation(
+ mapper.serialize(sessionExtensions));
+
+ MOASessionDBUtils.saveOrUpdate(dbsession);
+ Logger.debug("MOASession with sessionID=" + sessionID + " is stored in Database");
+
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("MOASession could not be stored.");
+ throw new MOADatabaseException(e);
+
+ } catch (JsonProcessingException e) {
+ Logger.warn("Extended session information can not be stored.", e);
+ throw new MOADatabaseException("Extended session information can not be stored.", e);
+
+ }
+
+ }
+
+ @Override
+ public void storeSession(AuthenticationSession session) throws MOADatabaseException, BuildException {
+ try {
+ AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true);
+
+ encryptSession(session, dbsession);
+
+ //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1
+ dbsession.setAuthenticated(session.isAuthenticated());
+ dbsession.setUpdated(new Date());
+
+ MOASessionDBUtils.saveOrUpdate(dbsession);
+ Logger.debug("MOASession with sessionID=" + session.getSessionID() + " is stored in Database");
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("MOASession could not be stored.");
+ throw new MOADatabaseException(e);
+ }
+ }
+
+ @Override
+ public void destroySession(String moaSessionID) throws MOADatabaseException {
+
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getSessionWithID");
+ query.setParameter("sessionid", moaSessionID);
+ result = query.list();
+
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() != 1) {
+ Logger.trace("No entries found.");
+ throw new MOADatabaseException("No session found with this sessionID");
+ }
+
+ AuthenticatedSessionStore dbsession = (AuthenticatedSessionStore) result.get(0);
+ tx.commit();
+ cleanDelete(dbsession);
+ }
+
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+
+ }
+
+ }
+
+ @Override
+ public String changeSessionID(AuthenticationSession session, String newSessionID) throws BuildException, MOADatabaseException {
+
+ AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true);
+
+ Logger.debug("Change SessionID from " + session.getSessionID()
+ + "to " + newSessionID);
+
+ session.setSessionID(newSessionID);
+ encryptSession(session, dbsession);
+
+ dbsession.setSessionid(newSessionID);
+ dbsession.setAuthenticated(session.isAuthenticated());
+
+ //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1
+ dbsession.setUpdated(new Date());
+
+ MOASessionDBUtils.saveOrUpdate(dbsession);
+
+ Logger.trace("Change SessionID complete.");
+
+ return newSessionID;
+
+ }
+
+ @Override
+ public String changeSessionID(AuthenticationSession session)
+ throws BuildException, MOADatabaseException {
+ String id = Random.nextRandom();
+ return changeSessionID(session, id);
+
+ }
+
+ @Override
+ public void setAuthenticated(String moaSessionID, boolean isAuthenticated) {
+
+ AuthenticatedSessionStore session;
+
+ try {
+ session = searchInDatabase(moaSessionID, true);
+ session.setAuthenticated(isAuthenticated);
+ MOASessionDBUtils.saveOrUpdate(session);
+
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("isAuthenticated can not be stored in MOASession " + moaSessionID, e);
+ }
+ }
+
+ @Override
+ public String getMOASessionSSOID(String SSOSessionID) {
+ MiscUtil.assertNotNull(SSOSessionID, "SSOsessionID");
+ Logger.trace("Get authenticated session with SSOID " + SSOSessionID + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getSessionWithSSOID");
+ query.setParameter("sessionid", SSOSessionID);
+ result = query.list();
+
+ //send transaction
+ tx.commit();
+
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() != 1) {
+ Logger.trace("No entries found.");
+ return null;
+
+ } else {
+ return result.get(0).getSessionid();
+
+ }
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+ }
+ }
+
+ @Override
+ public boolean isSSOSession(String sessionID) throws MOADatabaseException {
+ try {
+ AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true);
+ return dbsession.isSSOSession();
+
+ } catch (MOADatabaseException e) {
+ Logger.info("No MOA Session with id: " + sessionID);
+ throw new MOADatabaseException("No MOA Session with id: " + sessionID);
+ }
+ }
+
+ @Override
+ public AuthenticatedSessionStore isValidSessionWithSSOID(String SSOId) {
+
+ //TODO: is this method really needed??
+ MiscUtil.assertNotNull(SSOId, "SSOSessionID");
+ Logger.trace("Get authenticated session with SSOID " + SSOId + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getSessionWithSSOID");
+ query.setParameter("sessionid", SSOId);
+ result = query.list();
+
+ //send transaction
+ tx.commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() != 1) {
+ Logger.trace("No entries found.");
+ return null;
+
+ } else {
+ return result.get(0);
+ }
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+ }
+ }
+
+ @Override
+ public void addSSOInformation(String moaSessionID, String SSOSessionID,
+ SLOInformationInterface SLOInfo, IRequest protocolRequest) throws AuthenticationException {
+
+ AuthenticatedSessionStore dbsession;
+ Transaction tx = null;
+
+ try {
+
+ Session session = MOASessionDBUtils.getCurrentSession();
+ List<AuthenticatedSessionStore> result;
+
+ Logger.trace("Add SSO information to session " + moaSessionID);
+
+ synchronized (session) {
+
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getSessionWithID");
+ query.setParameter("sessionid", moaSessionID);
+ result = query.list();
+
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() != 1) {
+ Logger.trace("No entries found.");
+ tx.rollback();
+ throw new MOADatabaseException("No session found with this sessionID");
+ }
+
+ dbsession = (AuthenticatedSessionStore) result.get(0);
+
+ OASessionStore activeOA = null;
+ //check if OA already has an active OA session
+ if (dbsession.getActiveOAsessions() != null) {
+ for (OASessionStore el : dbsession.getActiveOAsessions()) {
+ if (el.getOaurlprefix().equals(protocolRequest.getOAURL()))
+ activeOA = el;
+ }
+ }
+
+ if (activeOA == null)
+ activeOA = new OASessionStore();
+
+ //set active OA applications
+ activeOA.setOaurlprefix(protocolRequest.getOAURL());
+ activeOA.setMoasession(dbsession);
+ activeOA.setCreated(new Date());
+
+ //set additional information for SLO
+ if (SLOInfo != null) {
+ activeOA.setAssertionSessionID(SLOInfo.getSessionIndex());
+ activeOA.setUserNameID(SLOInfo.getUserNameIdentifier());
+ activeOA.setUserNameIDFormat(SLOInfo.getUserNameIDFormat());
+ activeOA.setProtocolType(SLOInfo.getProtocolType());
+ activeOA.setAttributeQueryUsed(false);
+ activeOA.setAuthURL(protocolRequest.getAuthURL());
+
+
+ }
+
+ List<OASessionStore> activeOAs = dbsession.getActiveOAsessions();
+ activeOAs.add(activeOA);
+ dbsession.setActiveOAsessions(activeOAs);
+
+
+ //Store used SSOId
+ if (dbsession.getSSOsessionid() != null) {
+ OldSSOSessionIDStore oldSSOId = new OldSSOSessionIDStore();
+ oldSSOId.setOldsessionid(dbsession.getSSOsessionid());
+ oldSSOId.setMoasession(dbsession);
+
+ List<OldSSOSessionIDStore> oldSSOIds = dbsession.getOldssosessionids();
+ oldSSOIds.add(oldSSOId);
+ }
+
+ dbsession.setSSOSession(true);
+ dbsession.setSSOsessionid(SSOSessionID);
+ dbsession.setAuthenticated(false);
+ dbsession.setPendingRequestID("empty");
+
+ //Store MOASession
+ session.saveOrUpdate(dbsession);
+
+ //send transaction
+ tx.commit();
+
+ if (SLOInfo != null)
+ Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getOAURL()
+ + " and AssertionID: " + SLOInfo.getSessionIndex());
+ else
+ Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getOAURL());
+
+ }
+
+ } catch (MOADatabaseException e) {
+ throw new AuthenticationException("No MOASession found with Id="+moaSessionID, null);
+
+ } catch(HibernateException e) {
+ Logger.warn("Error during database saveOrUpdate. Rollback.", e);
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw new AuthenticationException("SSO Session information can not be stored! --> SSO is deactivated", null);
+ }
+ }
+
+ @Override
+ public List<OASessionStore> getAllActiveOAFromMOASession(AuthenticationSession moaSession) {
+ MiscUtil.assertNotNull(moaSession, "MOASession");
+ Session session = null;
+
+ try {
+ List<OASessionStore> oas = new ArrayList<OASessionStore>();
+
+ AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false);
+ oas.addAll(dbsession.getActiveOAsessions());
+
+ session = MOASessionDBUtils.getCurrentSession();
+ session.getTransaction().commit();
+
+ return oas;
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e);
+
+ } catch (Exception e) {
+ if (session != null && session.getTransaction() != null
+ && !session.getTransaction().wasCommitted()) {
+ session.getTransaction().rollback();
+ throw e;
+
+ }
+
+ }
+
+ return null;
+ }
+
+ @Override
+ public List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(AuthenticationSession moaSession) {
+ MiscUtil.assertNotNull(moaSession, "MOASession");
+ Session session = null;
+ try {
+ List<InterfederationSessionStore> idps = new ArrayList<InterfederationSessionStore>();
+ AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false);
+ idps.addAll(dbsession.getInderfederation());
+
+ session = MOASessionDBUtils.getCurrentSession();
+ session.getTransaction().commit();
+
+ return idps;
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e);
+
+ } catch (Exception e) {
+ if (session != null && session.getTransaction() != null
+ && !session.getTransaction().wasCommitted()) {
+ session.getTransaction().rollback();
+ throw e;
+
+ }
+
+ }
+
+ return null;
+ }
+
+ @Override
+ public AuthenticationSession searchMOASessionWithNameIDandOAID(String oaID, String userNameID) {
+ MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier");
+ MiscUtil.assertNotNull(userNameID, "userNameID");
+ Logger.trace("Get moaSession for userNameID " + userNameID + " and OA "
+ + oaID + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+ Transaction tx = null;
+
+ List<AuthenticatedSessionStore> result = null;;
+ try {
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getMOASessionWithNameIDandOAID");
+ query.setParameter("oaID", oaID);
+ query.setParameter("nameID", userNameID);
+ result = query.list();
+
+ //send transaction
+ tx.commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() != 1) {
+ Logger.trace("No unique entry found.");
+ return null;
+
+ }
+
+ return decryptSession(result.get(0));
+
+ } catch (BuildException e) {
+ Logger.warn("MOASession deserialization-exception by using MOASessionID=" + result.get(0).getSessionid(), e);
+ return null;
+
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+ }
+
+ }
+
+ @Override
+ public OASessionStore searchActiveOASSOSession(AuthenticationSession moaSession, String oaID, String protocolType) {
+ MiscUtil.assertNotNull(moaSession, "MOASession");
+ MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier");
+ MiscUtil.assertNotNull(protocolType, "usedProtocol");
+ Logger.trace("Get active OnlineApplication for sessionID " + moaSession.getSessionID() + " with OAID "
+ + oaID + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol");
+ query.setParameter("sessionID", moaSession.getSessionID());
+ query.setParameter("oaID", oaID);
+ query.setParameter("protocol", protocolType);
+ result = query.list();
+
+ //send transaction
+ tx.commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() == 0) {
+ Logger.trace("No entries found.");
+ return null;
+
+ }
+
+ return result.get(0).getActiveOAsessions().get(0);
+
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+ }
+ }
+
+ @Override
+ public AuthenticationSession getSessionWithUserNameID(String nameID) {
+
+ Transaction tx = null;
+ try {
+ MiscUtil.assertNotNull(nameID, "nameID");
+ Logger.trace("Get authenticated session with pedingRequestID " + nameID + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getMOAISessionWithUserNameID");
+ query.setParameter("usernameid", StringEscapeUtils.escapeHtml(nameID));
+ result = query.list();
+
+ //send transaction
+ tx.commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() == 0) {
+ Logger.trace("No entries found.");
+ return null;
+ }
+
+ return decryptSession(result.get(0));
+
+ } catch (Throwable e) {
+ Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID);
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ return null;
+ }
+
+ }
+
+ @Override
+ public InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASession(String sessionID) {
+ MiscUtil.assertNotNull(sessionID, "MOASession");
+ Logger.trace("Get interfederated IDP for SSO with sessionID " + sessionID + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionID");
+ query.setParameter("sessionID", sessionID);
+ result = query.list();
+
+ //send transaction
+ tx.commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() == 0) {
+ Logger.trace("No entries found.");
+ return null;
+
+ }
+
+ return result.get(0).getInderfederation().get(0);
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+ }
+ }
+
+ @Override
+ public InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASessionIDPID(String sessionID, String idpID) {
+ MiscUtil.assertNotNull(sessionID, "MOASession");
+ MiscUtil.assertNotNull(idpID, "Interfederated IDP ID");
+ Logger.trace("Get interfederated IDP "+ idpID + " for SSO with sessionID " + sessionID + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionIDIDPID");
+ query.setParameter("sessionID", sessionID);
+ query.setParameter("idpID", idpID);
+ result = query.list();
+
+ //send transaction
+ tx.commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() == 0) {
+ Logger.trace("No entries found.");
+ return null;
+
+ }
+
+ return result.get(0).getInderfederation().get(0);
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+ }
+ }
+
+ public String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException {
+ AuthenticatedSessionStore dbsession = null;
+
+ //search for active SSO session
+ if (MiscUtil.isNotEmpty(ssoID)) {
+ String moaSession = getMOASessionSSOID(ssoID);
+ if (MiscUtil.isNotEmpty(moaSession)) {
+ try {
+ dbsession = searchInDatabase(moaSession, true);
+
+ }catch (MOADatabaseException e) {
+
+ }
+ }
+ }
+
+ String id = null;
+ Date now = new Date();
+ //create new MOASession if any exists
+ AuthenticationSession session = null;
+ if (dbsession == null) {
+ id = Random.nextRandom();
+ dbsession = new AuthenticatedSessionStore();
+ dbsession.setSessionid(id);
+ dbsession.setCreated(now);
+ dbsession.setPendingRequestID(req.getRequestID());
+ session = new AuthenticationSession(id, now);
+
+ } else {
+ id = dbsession.getSessionid();
+ session = decryptSession(dbsession);
+
+ }
+
+ dbsession.setInterfederatedSSOSession(true);
+ dbsession.setAuthenticated(isAuthenticated);
+ dbsession.setUpdated(now);
+ session.setAuthenticated(true);
+ encryptSession(session, dbsession);
+
+ //add interfederation information
+ List<InterfederationSessionStore> idpList = dbsession.getInderfederation();
+
+ MOAResponse interfederationResp = req.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, MOAResponse.class);
+ String interFedEntityID = interfederationResp.getEntityID();
+
+ InterfederationSessionStore idp = null;
+ if (idpList == null) {
+ idpList = new ArrayList<InterfederationSessionStore>();
+ dbsession.setInderfederation(idpList);
+
+ } else {
+ for (InterfederationSessionStore el : idpList) {
+ //resue old entry if interfederation IDP is reused for authentication
+ if (el.getIdpurlprefix().equals(interFedEntityID))
+ idp = el;
+
+ }
+ }
+
+ //create new interfederation IDP entry
+ if (idp == null) {
+ idp = new InterfederationSessionStore();
+ idp.setCreated(now);
+ idp.setIdpurlprefix(interFedEntityID);
+ idp.setAuthURL(req.getAuthURL());
+
+ try {
+ OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().
+ getOnlineApplicationParameter(idp.getIdpurlprefix());
+ idp.setStoreSSOInformation(oa.isInterfederationSSOStorageAllowed());
+
+ } catch (ConfigurationException e) {
+ Logger.warn("MOASession could not be created.");
+ throw new MOADatabaseException(e);
+
+ }
+ idp.setMoasession(dbsession);
+ idpList.add(idp);
+
+ }
+ AssertionAttributeExtractor extract = new AssertionAttributeExtractor(interfederationResp.getResponse());
+ idp.setSessionIndex(extract.getSessionIndex());
+ idp.setUserNameID(extract.getNameID());
+ idp.setAttributesRequested(false);
+ idp.setQAALevel(extract.getQAALevel());
+
+ //store AssertionStore element to Database
+ try {
+ MOASessionDBUtils.saveOrUpdate(dbsession);
+ Logger.debug("MOASession with sessionID=" + id + " is stored in Database");
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("MOASession could not be created.");
+ throw new MOADatabaseException(e);
+ }
+
+ return id;
+ }
+
+ @Override
+ public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(AuthenticationSession moaSession) {
+ MiscUtil.assertNotNull(moaSession, "MOASession");
+ Logger.trace("Get interfederated IDP for AttributeQuery with sessionID " + moaSession.getSessionID() + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID");
+ query.setParameter("sessionID", moaSession.getSessionID());
+ result = query.list();
+
+ //send transaction
+ tx.commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() == 0) {
+ Logger.trace("No entries found.");
+ return null;
+
+ }
+
+ return result.get(0).getInderfederation().get(0);
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+ }
+ }
+
+ @Override
+ public boolean removeInterfederetedSession(String entityID,
+ String pedingRequestID) {
+
+ try {
+ Logger.debug("Remove interfederated IDP from local SSO session ...");
+
+ MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID");
+ Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List<AuthenticatedSessionStore> result;
+
+ //TODO: !!!!!!!!!!! PendingRequestID does not work
+
+ synchronized (session) {
+ session.beginTransaction();
+ Query query = session.getNamedQuery("getSessionWithPendingRequestID");
+ query.setParameter("sessionid", pedingRequestID);
+ result = query.list();
+
+ //send transaction
+ session.getTransaction().commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() != 1) {
+ Logger.trace("No entries found.");
+ return false;
+ }
+
+ AuthenticatedSessionStore authsession = result.get(0);
+
+ List<InterfederationSessionStore> idpSessions = authsession.getInderfederation();
+ if (idpSessions != null) {
+ for (InterfederationSessionStore idp : idpSessions) {
+ if (idp.getIdpurlprefix().equals(entityID))
+ idpSessions.remove(idp);
+
+ }
+ }
+
+ MOASessionDBUtils.saveOrUpdate(authsession);
+ return true;
+
+ } catch (Throwable e) {
+ Logger.warn("MOASession deserialization-exception by using MOASessionID=" + pedingRequestID);
+ return false;
+ }
+ }
+
+ @Override
+ public void clean(Date now, long authDataTimeOutCreated, long authDataTimeOutUpdated) {
+ Date expioredatecreate = new Date(now.getTime() - authDataTimeOutCreated);
+ Date expioredateupdate = new Date(now.getTime() - authDataTimeOutUpdated);
+
+ List<AuthenticatedSessionStore> results;
+ Session session = MOASessionDBUtils.getCurrentSession();
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getMOAISessionsWithTimeOut");
+ query.setTimestamp("timeoutcreate", expioredatecreate);
+ query.setTimestamp("timeoutupdate", expioredateupdate);
+ results = query.list();
+ tx.commit();
+
+ if (results.size() != 0) {
+ for(AuthenticatedSessionStore result : results) {
+ try {
+ cleanDelete(result);
+ Logger.info("Authenticated session with sessionID=" + result.getSessionid()
+ + " after session timeout.");
+
+ } catch (HibernateException e){
+ Logger.warn("Authenticated session with sessionID=" + result.getSessionid()
+ + " not removed after timeout! (Error during Database communication)", e);
+ }
+ }
+ }
+ }
+
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted())
+ tx.rollback();
+ throw e;
+ }
+ }
+
+ private static void encryptSession(AuthenticationSession session, AuthenticatedSessionStore dbsession) throws BuildException {
+ byte[] serialized = SerializationUtils.serialize(session);
+
+ EncryptedData encdata = SessionEncrytionUtil.getInstance().encrypt(serialized);
+ dbsession.setSession(encdata.getEncData());
+ dbsession.setIv(encdata.getIv());
+ }
+
+ private static AuthenticationSession decryptSession(AuthenticatedSessionStore dbsession) throws BuildException {
+ EncryptedData encdata = new EncryptedData(dbsession.getSession(),
+ dbsession.getIv());
+ byte[] decrypted = SessionEncrytionUtil.getInstance().decrypt(encdata);
+
+ return (AuthenticationSession) SerializationUtils.deserialize(decrypted);
+
+ }
+
+ private static void cleanDelete(AuthenticatedSessionStore result) {
+
+ try {
+ result.setSession("blank".getBytes());
+ MOASessionDBUtils.saveOrUpdate(result);
+
+ } catch (MOADatabaseException e) {
+ Logger.warn("Blank authenticated session with sessionID=" + result.getSessionid() + " FAILED.", e);
+
+ } finally {
+ if (!MOASessionDBUtils.delete(result))
+ Logger.error("Authenticated session with sessionID=" + result.getSessionid() + " not removed! (Error during Database communication)");
+ }
+ }
+
+ @SuppressWarnings("rawtypes")
+ private static AuthenticatedSessionStore searchInDatabase(String sessionID, boolean commit) throws MOADatabaseException {
+ MiscUtil.assertNotNull(sessionID, "moasessionID");
+ Logger.trace("Get authenticated session with sessionID " + sessionID + " from database.");
+ Session session = MOASessionDBUtils.getCurrentSession();
+
+ List result;
+ Transaction tx = null;
+ try {
+ synchronized (session) {
+ tx = session.beginTransaction();
+ Query query = session.getNamedQuery("getSessionWithID");
+ query.setParameter("sessionid", sessionID);
+ result = query.list();
+
+ //send transaction
+ if (commit)
+ tx.commit();
+ }
+
+ Logger.trace("Found entries: " + result.size());
+
+ //Assertion requires an unique artifact
+ if (result.size() != 1) {
+ Logger.trace("No entries found.");
+ throw new MOADatabaseException("No session found with this sessionID");
+
+ }
+
+ return (AuthenticatedSessionStore) result.get(0);
+
+ } catch (Exception e) {
+ if (tx != null && !tx.wasCommitted() && commit)
+ tx.rollback();
+ throw e;
+ }
+ }
+}