use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.
the class SPACSUtils method processResponseForFedlet.
/**
* Processes response from Identity Provider to Fedlet (SP).
* This will do all required protocol processing, include signature,
* issuer and audience validation etc. A map containing processing
* result will be returned. <br>
* Here is a list of keys and values for the returned map: <br>
* SAML2Constants.ATTRIBUTE_MAP -- Attribute map containing all attributes
* passed down from IDP inside the
* Assertion. The value is a
* <code>java.util.Map</code> whose keys
* are attribute names and values are
* <code>java.util.Set</code> of string
* values for the attributes. <br>
* SAML2Constants.RELAY_STATE -- Relay state, value is a string <br>
* SAML2Constants.IDPENTITYID -- IDP entity ID, value is a string<br>
* SAML2Constants.RESPONSE -- Response object, value is an instance of
* com.sun.identity.saml2.protocol.Response
* SAML2Constants.ASSERTION -- Assertion object, value is an instance of
* com.sun.identity.saml2.assertion.Assertion
* SAML2Constants.SUBJECT -- Subject object, value is an instance of
* com.sun.identity.saml2.assertion.Subject
* SAML2Constants.NAMEID -- NameID object, value is an instance of
* com.sun.identity.saml2.assertion.NameID
*
* @param request HTTP Servlet request
* @param response HTTP Servlet response.
* @param out the print writer for writing out presentation
*
* @return <code>Map</code> which holds result of the processing.
* @throws SAML2Exception if the processing failed due to server error.
* @throws IOException if the processing failed due to IO error.
* @throws SessionException if the processing failed due to session error.
* @throws ServletException if the processing failed due to request error.
*
* @supported.api
*/
public static Map processResponseForFedlet(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws SAML2Exception, IOException, SessionException, ServletException {
if ((request == null) || (response == null)) {
throw new ServletException(SAML2SDKUtils.bundle.getString("nullInput"));
}
String requestURL = request.getRequestURL().toString();
SAML2MetaManager metaManager = new SAML2MetaManager();
if (metaManager == null) {
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorMetaManager"));
}
String metaAlias = SAML2MetaUtils.getMetaAliasByUri(requestURL);
if ((metaAlias == null) || (metaAlias.length() == 0)) {
// Check in case metaAlias has been supplied as a parameter
metaAlias = request.getParameter(SAML2MetaManager.NAME_META_ALIAS_IN_URI);
if (metaAlias == null || metaAlias.length() == 0) {
// pick the first available one
List spMetaAliases = metaManager.getAllHostedServiceProviderMetaAliases("/");
if ((spMetaAliases != null) && !spMetaAliases.isEmpty()) {
// get first one
metaAlias = (String) spMetaAliases.get(0);
}
if ((metaAlias == null) || (metaAlias.length() == 0)) {
throw new ServletException(SAML2SDKUtils.bundle.getString("nullSPEntityID"));
}
}
}
String hostEntityId = null;
try {
hostEntityId = metaManager.getEntityByMetaAlias(metaAlias);
} catch (SAML2MetaException sme) {
SAML2SDKUtils.debug.error("SPACSUtils.processResponseForFedlet", sme);
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
}
if (hostEntityId == null) {
// logging?
throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
}
// organization is always root org
String orgName = "/";
String relayState = request.getParameter(SAML2Constants.RELAY_STATE);
SessionProvider sessionProvider = null;
ResponseInfo respInfo = null;
try {
sessionProvider = SessionManager.getProvider();
} catch (SessionException se) {
SAML2SDKUtils.debug.error("SPACSUtils.processResponseForFedlet", se);
throw new SAML2Exception(se);
}
respInfo = SPACSUtils.getResponse(request, response, orgName, hostEntityId, metaManager);
Object newSession = null;
// Throws a SAML2Exception if the response cannot be validated
// or contains a non-Success StatusCode, invoking the SPAdapter SPI
// for taking action on the failed validation.
// The resulting exception has its redirectionDone flag set if
// the SPAdapter issued a HTTP redirect.
newSession = SPACSUtils.processResponse(request, response, out, metaAlias, null, respInfo, orgName, hostEntityId, metaManager, null);
SAML2SDKUtils.debug.message("SSO SUCCESS");
String[] redirected = sessionProvider.getProperty(newSession, SAML2Constants.RESPONSE_REDIRECTED);
if ((redirected != null) && (redirected.length != 0) && redirected[0].equals("true")) {
SAML2SDKUtils.debug.message("Already redirected in SPAdapter.");
// response redirected already in SPAdapter
return createMapForFedlet(respInfo, null, hostEntityId);
}
// redirect to relay state
String finalUrl = SPACSUtils.getRelayState(relayState, orgName, hostEntityId, metaManager);
String realFinalUrl = finalUrl;
if (finalUrl != null && finalUrl.length() != 0) {
try {
realFinalUrl = sessionProvider.rewriteURL(newSession, finalUrl);
} catch (SessionException se) {
SAML2SDKUtils.debug.message("SPACSUtils.processRespForFedlet", se);
realFinalUrl = finalUrl;
}
}
String redirectUrl = SPACSUtils.getIntermediateURL(orgName, hostEntityId, metaManager);
String realRedirectUrl = null;
if (redirectUrl != null && redirectUrl.length() != 0) {
if (realFinalUrl != null && realFinalUrl.length() != 0) {
if (redirectUrl.indexOf("?") != -1) {
redirectUrl += "&goto=";
} else {
redirectUrl += "?goto=";
}
redirectUrl += URLEncDec.encode(realFinalUrl);
try {
realRedirectUrl = sessionProvider.rewriteURL(newSession, redirectUrl);
} catch (SessionException se) {
SAML2SDKUtils.debug.message("SPACSUtils.processRespForFedlet: rewriting failed.", se);
realRedirectUrl = redirectUrl;
}
} else {
realRedirectUrl = redirectUrl;
}
} else {
realRedirectUrl = finalUrl;
}
return createMapForFedlet(respInfo, realRedirectUrl, hostEntityId);
}
use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.
the class SPACSUtils method processResponse.
/**
* Authenticates user with <code>Response</code>.
* Auth session upgrade will be called if input session is
* not null.
* Otherwise, saml2 auth module is called. The name of the auth module
* is retrieved from <code>SPSSOConfig</code>. If not found, "SAML2" will
* be used.
*
* @param request HTTP Servlet request
* @param response HTTP Servlet response.
* @param out the print writer for writing out presentation
* @param metaAlias metaAlias for the service provider
* @param session input session object. It could be null.
* @param respInfo <code>ResponseInfo</code> to be verified.
* @param realm realm or organization name of the service provider.
* @param hostEntityId hosted service provider Entity ID.
* @param metaManager <code>SAML2MetaManager</code> instance for meta operation.
* @param auditor a <code>SAML2EventLogger</code> auditor object to hook into
* tracking information for the saml request
* @return <code>Object</code> which holds result of the session.
* @throws SAML2Exception if the processing failed.
*/
public static Object processResponse(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String metaAlias, Object session, ResponseInfo respInfo, String realm, String hostEntityId, SAML2MetaManager metaManager, SAML2EventLogger auditor) throws SAML2Exception {
String classMethod = "SPACSUtils.processResponse: ";
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Response : " + respInfo.getResponse());
}
Map smap = null;
try {
// check Response/Assertion and get back a Map of relevant data
smap = SAML2Utils.verifyResponse(request, response, respInfo.getResponse(), realm, hostEntityId, respInfo.getProfileBinding());
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
throw se;
}
com.sun.identity.saml2.assertion.Subject assertionSubject = (com.sun.identity.saml2.assertion.Subject) smap.get(SAML2Constants.SUBJECT);
NameID nameId = assertionSubject.getNameID();
EncryptedID encId = assertionSubject.getEncryptedID();
Assertion authnAssertion = (Assertion) smap.get(SAML2Constants.POST_ASSERTION);
String sessionIndex = (String) smap.get(SAML2Constants.SESSION_INDEX);
respInfo.setSessionIndex(sessionIndex);
Integer authLevel = (Integer) smap.get(SAML2Constants.AUTH_LEVEL);
Long maxSessionTime = (Long) smap.get(SAML2Constants.MAX_SESSION_TIME);
String inRespToResp = (String) smap.get(SAML2Constants.IN_RESPONSE_TO);
List assertions = (List) smap.get(SAML2Constants.ASSERTIONS);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Assertions : " + assertions);
}
SPSSOConfigElement spssoconfig = metaManager.getSPSSOConfig(realm, hostEntityId);
// get mappers
SPAccountMapper acctMapper = SAML2Utils.getSPAccountMapper(realm, hostEntityId);
SPAttributeMapper attrMapper = SAML2Utils.getSPAttributeMapper(realm, hostEntityId);
String assertionEncryptedAttr = SAML2Utils.getAttributeValueFromSPSSOConfig(spssoconfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
boolean needAttributeEncrypted = getNeedAttributeEncrypted(assertionEncryptedAttr, spssoconfig);
boolean needNameIDEncrypted = getNeedNameIDEncrypted(assertionEncryptedAttr, spssoconfig);
Set<PrivateKey> decryptionKeys = KeyUtil.getDecryptionKeys(spssoconfig);
if (needNameIDEncrypted && encId == null) {
SAML2Utils.debug.error(classMethod + "process: NameID was not encrypted.");
SAML2Exception se = new SAML2Exception(SAML2Utils.bundle.getString("nameIDNotEncrypted"));
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
throw se;
}
if (encId != null) {
try {
nameId = encId.decrypt(decryptionKeys);
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
throw se;
}
}
respInfo.setNameId(nameId);
SPSSODescriptorElement spDesc = null;
try {
spDesc = metaManager.getSPSSODescriptor(realm, hostEntityId);
} catch (SAML2MetaException ex) {
SAML2Utils.debug.error(classMethod, ex);
}
if (spDesc == null) {
SAML2Exception se = new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_META_DATA_ERROR, se);
throw se;
}
String nameIDFormat = nameId.getFormat();
if (nameIDFormat != null) {
List spNameIDFormatList = spDesc.getNameIDFormat();
if ((spNameIDFormatList != null) && (!spNameIDFormatList.isEmpty()) && (!spNameIDFormatList.contains(nameIDFormat))) {
Object[] args = { nameIDFormat };
SAML2Exception se = new SAML2Exception(SAML2Utils.BUNDLE_NAME, "unsupportedNameIDFormatSP", args);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
throw se;
}
}
boolean isTransient = SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameIDFormat);
boolean isPersistent = SAML2Constants.PERSISTENT.equals(nameIDFormat);
boolean ignoreProfile = SAML2PluginsUtils.isIgnoredProfile(realm);
String existUserName = null;
SessionProvider sessionProvider = null;
try {
sessionProvider = SessionManager.getProvider();
} catch (SessionException se) {
// invoke SPAdapter for failure
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
throw se2;
}
if (session != null) {
try {
existUserName = sessionProvider.getPrincipalName(session);
} catch (SessionException se) {
// invoke SPAdapter for failure
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
throw se2;
}
}
String remoteHostId = authnAssertion.getIssuer().getValue();
String userName = null;
boolean isNewAccountLink = false;
boolean shouldPersistNameID = isPersistent || (!isTransient && !ignoreProfile && acctMapper.shouldPersistNameIDFormat(realm, hostEntityId, remoteHostId, nameIDFormat));
try {
if (shouldPersistNameID) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "querying data store for existing federation links: realm = " + realm + " hostEntityID = " + hostEntityId + " remoteEntityID = " + remoteHostId);
}
try {
userName = SAML2Utils.getDataStoreProvider().getUserID(realm, SAML2Utils.getNameIDKeyMap(nameId, hostEntityId, remoteHostId, realm, SAML2Constants.SP_ROLE));
} catch (DataStoreProviderException dse) {
SAML2Utils.debug.error(classMethod + "DataStoreProviderException whilst retrieving NameID " + "information", dse);
throw new SAML2Exception(dse.getMessage());
}
}
if (userName == null) {
userName = acctMapper.getIdentity(authnAssertion, hostEntityId, realm);
isNewAccountLink = true;
}
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_NO_USER_MAPPING, se);
throw se;
}
if (userName == null && respInfo.isLocalLogin()) {
// In case we just got authenticated locally, we should accept the freshly authenticated session's principal
// as the username corresponding to the received assertion.
userName = existUserName;
}
if (null != auditor) {
auditor.setUserId(userName);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "process: userName =[" + userName + "]");
}
List attrs = null;
for (Iterator it = assertions.iterator(); it.hasNext(); ) {
Assertion assertion = (Assertion) it.next();
List origAttrs = getSAMLAttributes(assertion, needAttributeEncrypted, decryptionKeys);
if (origAttrs != null && !origAttrs.isEmpty()) {
if (attrs == null) {
attrs = new ArrayList();
}
attrs.addAll(origAttrs);
}
}
Map attrMap = null;
if (attrs != null) {
try {
attrMap = attrMapper.getAttributes(attrs, userName, hostEntityId, remoteHostId, realm);
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_ATTRIBUTE_MAPPING, se);
throw se;
}
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "process: remoteHostId = " + remoteHostId);
SAML2Utils.debug.message(classMethod + "process: attrMap = " + attrMap);
}
respInfo.setAttributeMap(attrMap);
// return error code for local user login
if (StringUtils.isEmpty(userName)) {
// map the user to the existing session.
if (session != null) {
try {
sessionProvider.invalidateSession(session, request, response);
} catch (SessionException se) {
SAML2Utils.debug.error("An error occurred while trying to invalidate session", se);
}
}
throw new SAML2Exception(SAML2Utils.bundle.getString("noUserMapping"));
}
boolean writeFedInfo = isNewAccountLink && shouldPersistNameID;
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "userName : " + userName);
SAML2Utils.debug.message(classMethod + "writeFedInfo : " + writeFedInfo);
}
AuthnRequest authnRequest = null;
if (smap != null) {
authnRequest = (AuthnRequest) smap.get(SAML2Constants.AUTHN_REQUEST);
}
if (inRespToResp != null && inRespToResp.length() != 0) {
SPCache.requestHash.remove(inRespToResp);
}
Map sessionInfoMap = new HashMap();
sessionInfoMap.put(SessionProvider.REALM, realm);
sessionInfoMap.put(SessionProvider.PRINCIPAL_NAME, userName);
// set client info. always use client IP address to prevent
// reverse host lookup
String clientAddr = ClientUtils.getClientIPAddress(request);
sessionInfoMap.put(SessionProvider.HOST, clientAddr);
sessionInfoMap.put(SessionProvider.HOST_NAME, clientAddr);
sessionInfoMap.put(SessionProvider.AUTH_LEVEL, String.valueOf(authLevel));
request.setAttribute(SessionProvider.ATTR_MAP, attrMap);
try {
session = sessionProvider.createSession(sessionInfoMap, request, response, null);
} catch (SessionException se) {
// invoke SPAdapter for failure
int failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_GENERATION;
int sessCode = se.getErrCode();
if (sessCode == SessionException.AUTH_USER_INACTIVE) {
failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_USER_INACTIVE;
} else if (sessCode == SessionException.AUTH_USER_LOCKED) {
failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_USER_LOCKED;
} else if (sessCode == SessionException.AUTH_ACCOUNT_EXPIRED) {
failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_ACCOUNT_EXPIRED;
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPACSUtils.processResponse : error code=" + sessCode, se);
}
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, failureCode, se2);
throw se2;
}
// set metaAlias
String[] values = { metaAlias };
try {
setAttrMapInSession(sessionProvider, attrMap, session);
setDiscoBootstrapCredsInSSOToken(sessionProvider, authnAssertion, session);
sessionProvider.setProperty(session, SAML2Constants.SP_METAALIAS, values);
} catch (SessionException se) {
// invoke SPAdapter for failure
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
throw se2;
}
NameIDInfo info = null;
String affiID = nameId.getSPNameQualifier();
boolean isDualRole = SAML2Utils.isDualRole(hostEntityId, realm);
AffiliationDescriptorType affiDesc = null;
if (affiID != null && !affiID.isEmpty()) {
affiDesc = metaManager.getAffiliationDescriptor(realm, affiID);
}
if (affiDesc != null) {
if (!affiDesc.getAffiliateMember().contains(hostEntityId)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("spNotAffiliationMember"));
}
if (isDualRole) {
info = new NameIDInfo(affiID, remoteHostId, nameId, SAML2Constants.DUAL_ROLE, true);
} else {
info = new NameIDInfo(affiID, remoteHostId, nameId, SAML2Constants.SP_ROLE, true);
}
} else {
if (isDualRole) {
info = new NameIDInfo(hostEntityId, remoteHostId, nameId, SAML2Constants.DUAL_ROLE, false);
} else {
info = new NameIDInfo(hostEntityId, remoteHostId, nameId, SAML2Constants.SP_ROLE, false);
}
}
Map props = new HashMap();
String nameIDValueString = info.getNameIDValue();
props.put(LogUtil.NAME_ID, info.getNameIDValue());
try {
userName = sessionProvider.getPrincipalName(session);
} catch (SessionException se) {
// invoke SPAdapter for failure
SAML2Exception se2 = new SAML2Exception(se);
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
throw se2;
}
String[] data1 = { userName, nameIDValueString };
LogUtil.access(Level.INFO, LogUtil.SUCCESS_FED_SSO, data1, session, props);
// write fed info into data store
if (writeFedInfo) {
try {
AccountUtils.setAccountFederation(info, userName);
} catch (SAML2Exception se) {
// invoke SPAdapter for failure
invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.FEDERATION_FAILED_WRITING_ACCOUNT_INFO, se);
throw se;
}
String[] data = { userName, "" };
if (LogUtil.isAccessLoggable(Level.FINE)) {
data[1] = info.toValueString();
}
LogUtil.access(Level.INFO, LogUtil.FED_INFO_WRITTEN, data, session, props);
}
String requestID = respInfo.getResponse().getInResponseTo();
// save info in memory for logout
saveInfoInMemory(sessionProvider, session, sessionIndex, metaAlias, info, IDPProxyUtil.isIDPProxyEnabled(requestID), isTransient);
// invoke SP Adapter
SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostEntityId, realm);
if (spAdapter != null) {
boolean redirected = spAdapter.postSingleSignOnSuccess(hostEntityId, realm, request, response, out, session, authnRequest, respInfo.getResponse(), respInfo.getProfileBinding(), writeFedInfo);
String[] value = null;
if (redirected) {
value = new String[] { "true" };
} else {
value = new String[] { "false" };
}
try {
sessionProvider.setProperty(session, SAML2Constants.RESPONSE_REDIRECTED, value);
} catch (SessionException ex) {
SAML2Utils.debug.warning("SPSingleLogout.processResp", ex);
} catch (UnsupportedOperationException ex) {
SAML2Utils.debug.warning("SPSingleLogout.processResp", ex);
}
}
String assertionID = authnAssertion.getID();
if (respInfo.getProfileBinding().equals(SAML2Constants.HTTP_POST)) {
SPCache.assertionByIDCache.put(assertionID, SAML2Constants.ONETIME);
try {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(assertionID, SAML2Constants.ONETIME, ((Long) smap.get(SAML2Constants.NOTONORAFTER)).longValue() / 1000);
}
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "There was a problem saving the assertionID to the SAML2 Token Repository for assertionID:" + assertionID, se);
}
}
respInfo.setAssertion(authnAssertion);
return session;
}
use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.
the class SPSessionListener method sessionInvalidated.
/**
* Callback for SessionListener.
* It is used for cleaning up the SP session cache.
*
* @param session The session object
*/
public void sessionInvalidated(Object session) {
String classMethod = "SPSessionListener.sessionInvalidated: ";
HashMap paramsMap = new HashMap();
NameIDInfoKey nameIdInfoKey = null;
if (session == null || infoKeyString == null || sessionID == null) {
return;
}
SessionProvider sessionProvider = null;
SPFedSession fedSession = null;
try {
sessionProvider = SessionManager.getProvider();
} catch (SessionException se) {
return;
}
if (!sessionID.equals(sessionProvider.getSessionID(session))) {
return;
}
List fedSessionList = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
if (fedSessionList == null) {
return;
}
try {
Iterator iter = fedSessionList.iterator();
while (iter.hasNext()) {
fedSession = (SPFedSession) iter.next();
if (fedSession.spTokenID.equals(sessionID)) {
paramsMap.put(SAML2Constants.ROLE, SAML2Constants.SP_ROLE);
String metaAlias = fedSession.metaAlias;
nameIdInfoKey = NameIDInfoKey.parse(infoKeyString);
String spEntityID = sm.getEntityByMetaAlias(metaAlias);
String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
BaseConfigType spConfig = sm.getSPSSOConfig(realm, spEntityID);
if (spConfig != null) {
List spSessionSyncList = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.SP_SESSION_SYNC_ENABLED);
if (spEntityID != null && spSessionSyncList != null && (spSessionSyncList.size() != 0)) {
boolean spSessionSyncEnabled = ((String) spSessionSyncList.get(0)).equals(SAML2Constants.TRUE) ? true : false;
// is enabled
if (spSessionSyncEnabled) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "SP Session Synchronization flag " + "is enabled, initiating SLO to IDP");
}
initiateSPSingleLogout(metaAlias, realm, SAML2Constants.SOAP, nameIdInfoKey, fedSession, paramsMap);
}
}
} else {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Unable to retrieve the SP config" + " data, spConfig is null");
}
}
}
}
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error("SPSessionListener.sessionInvalidated:", sme);
} catch (SAML2Exception se) {
SAML2Utils.debug.error("SPSessionListener.sessionInvalidated:", se);
} catch (SessionException s) {
SAML2Utils.debug.error("IDPSessionListener.sessionInvalidated:", s);
}
synchronized (fedSessionList) {
Iterator iter = fedSessionList.iterator();
while (iter.hasNext()) {
fedSession = (SPFedSession) iter.next();
if (fedSession.spTokenID.equals(sessionID)) {
iter.remove();
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
}
}
if (fedSessionList.isEmpty()) {
SPCache.fedSessionListsByNameIDInfoKey.remove(infoKeyString);
}
}
}
use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.
the class SPACSUtils method saveInfoInMemory.
public static void saveInfoInMemory(SessionProvider sessionProvider, Object session, String sessionIndex, String metaAlias, NameIDInfo info, boolean isIDPProxy, boolean isTransient) throws SAML2Exception {
String infoKeyString = (new NameIDInfoKey(info.getNameIDValue(), info.getHostEntityID(), info.getRemoteEntityID())).toValueString();
String infoKeyAttribute = AccountUtils.getNameIDInfoKeyAttribute();
String[] fromToken = null;
try {
fromToken = sessionProvider.getProperty(session, infoKeyAttribute);
if (fromToken == null || fromToken.length == 0 || fromToken[0] == null || fromToken[0].length() == 0) {
String[] values = { infoKeyString };
sessionProvider.setProperty(session, infoKeyAttribute, values);
} else {
if (fromToken[0].indexOf(infoKeyString) == -1) {
String[] values = { fromToken[0] + SAML2Constants.SECOND_DELIM + infoKeyString };
sessionProvider.setProperty(session, infoKeyAttribute, values);
}
}
if (isTransient) {
String nameIDInfoStr = info.toValueString();
String infoAttribute = AccountUtils.getNameIDInfoAttribute();
String[] nameIDInfoStrs = sessionProvider.getProperty(session, infoAttribute);
if (nameIDInfoStrs == null) {
nameIDInfoStrs = new String[1];
nameIDInfoStrs[0] = nameIDInfoStr;
} else {
Set nameIDInfoStrSet = new HashSet();
for (int i = 0; i < nameIDInfoStrs.length; i++) {
nameIDInfoStrSet.add(nameIDInfoStrs[i]);
}
nameIDInfoStrSet.add(nameIDInfoStr);
nameIDInfoStrs = (String[]) nameIDInfoStrSet.toArray(new String[nameIDInfoStrSet.size()]);
}
sessionProvider.setProperty(session, infoAttribute, nameIDInfoStrs);
}
} catch (SessionException sessE) {
throw new SAML2Exception(sessE);
}
String tokenID = sessionProvider.getSessionID(session);
if (!SPCache.isFedlet) {
List fedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
if (fedSessions == null) {
synchronized (SPCache.fedSessionListsByNameIDInfoKey) {
fedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
if (fedSessions == null) {
fedSessions = new ArrayList();
}
}
synchronized (fedSessions) {
fedSessions.add(new SPFedSession(sessionIndex, tokenID, info, metaAlias));
SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
}
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
if (isIDPProxy) {
//IDP Proxy
IDPSession idpSess = (IDPSession) IDPCache.idpSessionsBySessionID.get(tokenID);
if (idpSess == null) {
idpSess = new IDPSession(session);
IDPCache.idpSessionsBySessionID.put(tokenID, idpSess);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("Add Session Partner: " + info.getRemoteEntityID());
}
idpSess.addSessionPartner(new SAML2SessionPartner(info.getRemoteEntityID(), true));
// end of IDP Proxy
}
} else {
synchronized (fedSessions) {
Iterator iter = fedSessions.iterator();
boolean found = false;
while (iter.hasNext()) {
SPFedSession temp = (SPFedSession) iter.next();
String idpSessionIndex = null;
if (temp != null) {
idpSessionIndex = temp.idpSessionIndex;
}
if ((idpSessionIndex != null) && (idpSessionIndex.equals(sessionIndex))) {
temp.spTokenID = tokenID;
temp.info = info;
found = true;
break;
}
}
if (!found) {
fedSessions.add(new SPFedSession(sessionIndex, tokenID, info, metaAlias));
SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
}
}
}
SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
}
try {
sessionProvider.addListener(session, new SPSessionListener(infoKeyString, tokenID));
} catch (SessionException e) {
SAML2Utils.debug.error("SPACSUtils.saveInfoInMemory: " + "Unable to add session listener.");
}
}
use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.
the class SPSingleLogout method processLogoutRequest.
/**
* Gets and processes the Single <code>LogoutRequest</code> from IDP
* and return <code>LogoutResponse</code>.
*
* @param logoutReq <code>LogoutRequest</code> from IDP
* @param spEntityID name of host entity ID.
* @param realm name of host entity.
* @param request HTTP servlet request.
* @param response HTTP servlet response.
* @param isLBReq true if the request is for load balancing.
* @param binding value of <code>SAML2Constants.HTTP_REDIRECT</code> or
* <code>SAML2Constants.SOAP</code>.
* @param isVerified true if the request is verified already.
* @return LogoutResponse the target URL on successful
* <code>LogoutRequest</code>.
*/
public static LogoutResponse processLogoutRequest(LogoutRequest logoutReq, String spEntityID, String realm, HttpServletRequest request, HttpServletResponse response, boolean isLBReq, boolean destroySession, String binding, boolean isVerified) {
final String method = "processLogoutRequest : ";
NameID nameID = null;
Status status = null;
Issuer issuer = null;
String idpEntity = logoutReq.getIssuer().getValue();
String userId = null;
try {
do {
// TODO: check the NotOnOrAfter attribute of LogoutRequest
issuer = logoutReq.getIssuer();
String requestId = logoutReq.getID();
SAML2Utils.verifyRequestIssuer(realm, spEntityID, issuer, requestId);
issuer = SAML2Utils.createIssuer(spEntityID);
// get SessionIndex and NameID form LogoutRequest
List siList = logoutReq.getSessionIndex();
int numSI = 0;
if (siList != null) {
numSI = siList.size();
if (debug.messageEnabled()) {
debug.message(method + "Number of session indices in the logout request is " + numSI);
}
}
nameID = LogoutUtil.getNameIDFromSLORequest(logoutReq, realm, spEntityID, SAML2Constants.SP_ROLE);
if (nameID == null) {
debug.error(method + "LogoutRequest does not contain Name ID");
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("missing_name_identifier"));
break;
}
String infoKeyString = null;
infoKeyString = (new NameIDInfoKey(nameID.getValue(), spEntityID, idpEntity)).toValueString();
if (debug.messageEnabled()) {
debug.message(method + "infokey=" + infoKeyString);
}
if (SPCache.isFedlet) {
// verify request
if (!isVerified && !LogoutUtil.verifySLORequest(logoutReq, realm, idpEntity, spEntityID, SAML2Constants.SP_ROLE)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
}
// obtain fedlet adapter
FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(spEntityID, realm);
boolean result = false;
if (fedletAdapter != null) {
// call adapter to do real logout
result = fedletAdapter.doFedletSLO(request, response, logoutReq, spEntityID, idpEntity, siList, nameID.getValue(), binding);
}
if (result) {
status = SUCCESS_STATUS;
} else {
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("appLogoutFailed"));
}
break;
}
List list = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
if (debug.messageEnabled()) {
debug.message(method + "SPFedsessions=" + list);
}
if ((list == null) || list.isEmpty()) {
String spQ = nameID.getSPNameQualifier();
if ((spQ == null) || (spQ.length() == 0)) {
infoKeyString = (new NameIDInfoKey(nameID.getValue(), spEntityID, nameID.getNameQualifier())).toValueString();
list = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
}
}
boolean foundPeer = false;
List remoteServiceURLs = null;
if (isLBReq) {
remoteServiceURLs = FSUtils.getRemoteServiceURLs(request);
foundPeer = remoteServiceURLs != null && !remoteServiceURLs.isEmpty();
}
if (debug.messageEnabled()) {
debug.message(method + "isLBReq = " + isLBReq + ", foundPeer = " + foundPeer);
}
if (list == null || list.isEmpty()) {
if (foundPeer) {
boolean peerError = false;
for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(logoutReq, remoteLogoutURL);
if ((logoutRes != null) && !isNameNotFound(logoutRes)) {
if (isSuccess(logoutRes)) {
if (numSI > 0) {
siList = LogoutUtil.getSessionIndex(logoutRes);
if (siList == null || siList.isEmpty()) {
peerError = false;
break;
}
}
} else {
peerError = true;
}
}
}
if (peerError || (siList != null && siList.size() > 0)) {
status = PARTIAL_LOGOUT_STATUS;
} else {
status = SUCCESS_STATUS;
}
} else {
debug.error(method + "invalid Name ID received");
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("invalid_name_identifier"));
}
break;
} else {
// find the session, do signature validation
if (!isVerified && !LogoutUtil.verifySLORequest(logoutReq, realm, logoutReq.getIssuer().getValue(), spEntityID, SAML2Constants.SP_ROLE)) {
throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
}
// invoke SPAdapter for preSingleLogoutProcess
try {
String tokenId = ((SPFedSession) list.iterator().next()).spTokenID;
Object token = sessionProvider.getSession(tokenId);
userId = sessionProvider.getPrincipalName(token);
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSingleLogout." + "processLogoutRequest, user = " + userId);
}
} catch (SessionException ex) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message("SPSingleLogout." + "processLogoutRequest", ex);
}
}
userId = preSingleLogoutProcess(spEntityID, realm, request, response, userId, logoutReq, null, binding);
}
// get application logout URL
BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig(realm, spEntityID);
List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
if (debug.messageEnabled()) {
debug.message("IDPLogoutUtil.processLogoutRequest: " + "external app logout URL= " + appLogoutURL);
}
if (numSI == 0) {
// logout all fed sessions for this user
// between this SP and the IDP
List tokenIDsToBeDestroyed = new ArrayList();
synchronized (list) {
Iterator iter = list.listIterator();
while (iter.hasNext()) {
SPFedSession fedSession = (SPFedSession) iter.next();
tokenIDsToBeDestroyed.add(fedSession.spTokenID);
iter.remove();
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
}
}
for (Iterator iter = tokenIDsToBeDestroyed.listIterator(); iter.hasNext(); ) {
String tokenID = (String) iter.next();
Object token = null;
try {
token = sessionProvider.getSession(tokenID);
} catch (SessionException se) {
debug.error(method + "Could not create session from token ID = " + tokenID);
continue;
}
if (debug.messageEnabled()) {
debug.message(method + "destroy token " + tokenID);
}
// handle external application logout if configured
if ((appLogoutURL != null) && (appLogoutURL.size() != 0)) {
SAML2Utils.postToAppLogout(request, (String) appLogoutURL.get(0), token);
}
if (destroySession) {
sessionProvider.invalidateSession(token, request, response);
}
}
if (foundPeer) {
boolean peerError = false;
for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(logoutReq, remoteLogoutURL);
if ((logoutRes == null) || !(isSuccess(logoutRes) || isNameNotFound(logoutRes))) {
peerError = true;
}
}
if (peerError) {
status = PARTIAL_LOGOUT_STATUS;
} else {
status = SUCCESS_STATUS;
}
}
} else {
// logout only those fed sessions specified
// in logout request session list
String sessionIndex = null;
List siNotFound = new ArrayList();
for (int i = 0; i < numSI; i++) {
sessionIndex = (String) siList.get(i);
String tokenIDToBeDestroyed = null;
synchronized (list) {
Iterator iter = list.listIterator();
while (iter.hasNext()) {
SPFedSession fedSession = (SPFedSession) iter.next();
if (sessionIndex.equals(fedSession.idpSessionIndex)) {
if (debug.messageEnabled()) {
debug.message(method + " found si + " + sessionIndex);
}
tokenIDToBeDestroyed = fedSession.spTokenID;
iter.remove();
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
}
break;
}
}
}
if (tokenIDToBeDestroyed != null) {
try {
Object token = sessionProvider.getSession(tokenIDToBeDestroyed);
if (debug.messageEnabled()) {
debug.message(method + "destroy token (2) " + tokenIDToBeDestroyed);
}
// handle external application logout
if ((appLogoutURL != null) && (appLogoutURL.size() != 0)) {
SAML2Utils.postToAppLogout(request, (String) appLogoutURL.get(0), token);
}
if (destroySession) {
sessionProvider.invalidateSession(token, request, response);
}
} catch (SessionException se) {
debug.error(method + "Could not create " + "session from token ID = " + tokenIDToBeDestroyed);
}
} else {
siNotFound.add(sessionIndex);
}
}
if (isLBReq) {
if (foundPeer && !siNotFound.isEmpty()) {
boolean peerError = false;
LogoutRequest lReq = copyAndMakeMutable(logoutReq);
for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
lReq.setSessionIndex(siNotFound);
String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(lReq, remoteLogoutURL);
if ((logoutRes != null) && !isNameNotFound(logoutRes)) {
if (isSuccess(logoutRes)) {
siNotFound = LogoutUtil.getSessionIndex(logoutRes);
} else {
peerError = true;
}
}
if (debug.messageEnabled()) {
debug.message(method + "siNotFound = " + siNotFound);
}
if (siNotFound == null || siNotFound.isEmpty()) {
peerError = false;
break;
}
}
if (peerError || (siNotFound != null && !siNotFound.isEmpty())) {
status = PARTIAL_LOGOUT_STATUS;
} else {
status = SUCCESS_STATUS;
}
} else {
status = SUCCESS_STATUS;
}
} else {
if (siNotFound.isEmpty()) {
status = SUCCESS_STATUS;
} else {
status = SAML2Utils.generateStatus(SAML2Constants.SUCCESS, SAML2Utils.bundle.getString("requestSuccess"));
LogoutUtil.setSessionIndex(status, siNotFound);
}
}
}
} while (false);
} catch (SessionException se) {
debug.error("processLogoutRequest: ", se);
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, se.toString());
} catch (SAML2Exception e) {
debug.error("processLogoutRequest: " + "failed to create response", e);
status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, e.toString());
}
// create LogoutResponse
if (spEntityID == null) {
spEntityID = nameID.getSPNameQualifier();
}
LogoutResponse logResponse = LogoutUtil.generateResponse(status, logoutReq.getID(), issuer, realm, SAML2Constants.SP_ROLE, idpEntity);
if (isSuccess(logResponse)) {
// invoke SPAdapter for postSingleLogoutSuccess
postSingleLogoutSuccess(spEntityID, realm, request, response, userId, logoutReq, logResponse, binding);
}
return logResponse;
}
Aggregations