use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class LogoutRequestImpl method toXMLString.
/**
* Returns the <code>LogoutRequest</code> in an XML document String format
* based on the <code>LogoutRequest</code> schema described above.
*
* @param includeNSPrefix Determines whether or not the namespace qualifier
* is prepended to the Element when converted
* @param declareNS Determines whether or not the namespace is declared
* within the Element.
* @return A XML String representing the <code>LogoutRequest</code>.
* @throws SAML2Exception if some error occurs during conversion to
* <code>String</code>.
*/
public String toXMLString(boolean includeNSPrefix, boolean declareNS) throws SAML2Exception {
if (isSigned && signedXMLString != null) {
return signedXMLString;
}
validateData();
StringBuffer xmlString = new StringBuffer(1000);
xmlString.append(SAML2Constants.START_TAG);
if (includeNSPrefix) {
xmlString.append(SAML2Constants.PROTOCOL_PREFIX);
}
xmlString.append(SAML2Constants.LOGOUT_REQUEST).append(SAML2Constants.SPACE);
if (declareNS) {
xmlString.append(SAML2Constants.PROTOCOL_DECLARE_STR).append(SAML2Constants.SPACE);
}
xmlString.append(SAML2Constants.ID).append(SAML2Constants.EQUAL).append(SAML2Constants.QUOTE).append(requestId).append(SAML2Constants.QUOTE).append(SAML2Constants.SPACE).append(SAML2Constants.VERSION).append(SAML2Constants.EQUAL).append(SAML2Constants.QUOTE).append(version).append(SAML2Constants.QUOTE).append(SAML2Constants.SPACE).append(SAML2Constants.ISSUE_INSTANT).append(SAML2Constants.EQUAL).append(SAML2Constants.QUOTE).append(DateUtils.toUTCDateFormat(issueInstant)).append(SAML2Constants.QUOTE);
if ((destinationURI != null) && (destinationURI.length() > 0)) {
xmlString.append(SAML2Constants.SPACE).append(SAML2Constants.DESTINATION).append(SAML2Constants.EQUAL).append(SAML2Constants.QUOTE).append(destinationURI).append(SAML2Constants.QUOTE);
}
if ((consent != null) && (consent.length() > 0)) {
xmlString.append(SAML2Constants.SPACE).append(SAML2Constants.CONSENT).append(SAML2Constants.EQUAL).append(SAML2Constants.QUOTE).append(consent).append(SAML2Constants.QUOTE);
}
if (notOnOrAfter != null) {
xmlString.append(SAML2Constants.SPACE).append(SAML2Constants.NOTONORAFTER).append(SAML2Constants.EQUAL).append(SAML2Constants.QUOTE).append(DateUtils.toUTCDateFormat(notOnOrAfter)).append(SAML2Constants.QUOTE);
}
if ((reason != null) && (reason.length() > 0)) {
xmlString.append(SAML2Constants.SPACE).append(SAML2Constants.REASON).append(SAML2Constants.EQUAL).append(SAML2Constants.QUOTE).append(reason).append(SAML2Constants.QUOTE);
}
xmlString.append(SAML2Constants.END_TAG);
if (nameID != null) {
String issuerString = nameID.toXMLString(includeNSPrefix, declareNS);
xmlString.append(issuerString);
}
if ((signatureString != null) && (signatureString.length() > 0)) {
xmlString.append(signatureString);
}
if (extensions != null) {
xmlString.append(extensions.toXMLString(includeNSPrefix, declareNS));
}
if (baseId != null) {
xmlString.append(baseId.toXMLString(includeNSPrefix, declareNS));
}
if (nameId != null) {
xmlString.append(nameId.toXMLString(includeNSPrefix, declareNS));
}
if (encryptedId != null) {
xmlString.append(encryptedId.toXMLString(includeNSPrefix, declareNS));
}
if (sessionIndexList != null && !sessionIndexList.isEmpty()) {
Iterator sessionIterator = sessionIndexList.iterator();
while (sessionIterator.hasNext()) {
ProtocolFactory protoFactory = ProtocolFactory.getInstance();
String sessionString = (String) sessionIterator.next();
SessionIndex sIndex = protoFactory.createSessionIndex(sessionString);
xmlString.append(sIndex.toXMLString(includeNSPrefix, declareNS));
}
}
xmlString.append(SAML2Constants.SAML2_END_TAG).append(SAML2Constants.LOGOUT_REQUEST).append(SAML2Constants.END_TAG);
return xmlString.toString();
}
use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class UtilProxySAMLAuthenticatorLookup method retrieveAuthenticationFromCache.
@Override
public void retrieveAuthenticationFromCache() throws SessionException, ServerFaultException, ClientFaultException {
final String classMethod = "UtilProxySAMLAuthenticatorLookup.retrieveAuthenticationFromCache: ";
// the second visit, the user has already authenticated
// retrieve the cache authn request and relay state
// We need the session to pass it to the IDP Adapter preSendResponse
SessionProvider sessionProvider = SessionManager.getProvider();
try {
data.setSession(sessionProvider.getSession(request));
data.getEventAuditor().setSSOTokenId(data.getSession());
} catch (SessionException se) {
SAML2Utils.debug.error("An error occurred while retrieving the session: " + se.getMessage());
data.setSession(null);
}
// Get the cached Authentication Request and Relay State before
// invoking the IDP Adapter
CacheObject cacheObj;
synchronized (IDPCache.authnRequestCache) {
cacheObj = (CacheObject) IDPCache.authnRequestCache.get(data.getRequestID());
}
if (cacheObj != null) {
data.setAuthnRequest((AuthnRequest) cacheObj.getObject());
}
data.setRelayState((String) IDPCache.relayStateCache.get(data.getRequestID()));
if (!isSessionValid(sessionProvider)) {
return;
}
// Invoke the IDP Adapter after the user has been authenticated
if (preSendResponse(request, response, data)) {
return;
}
synchronized (IDPCache.authnRequestCache) {
cacheObj = (CacheObject) IDPCache.authnRequestCache.remove(data.getRequestID());
}
if (cacheObj != null) {
data.setAuthnRequest((AuthnRequest) cacheObj.getObject());
}
synchronized (IDPCache.idpAuthnContextCache) {
cacheObj = (CacheObject) IDPCache.idpAuthnContextCache.remove(data.getRequestID());
}
if (cacheObj != null) {
data.setMatchingAuthnContext((AuthnContext) cacheObj.getObject());
}
data.setRelayState((String) IDPCache.relayStateCache.remove(data.getRequestID()));
if (data.getAuthnRequest() == null) {
authNotAvailable();
return;
}
SAML2Utils.debug.message("{} RequestID= {}", classMethod, data.getRequestID());
boolean isSessionUpgrade = false;
if (CollectionUtils.isNotEmpty(IDPCache.isSessionUpgradeCache)) {
isSessionUpgrade = IDPCache.isSessionUpgradeCache.contains(data.getRequestID());
}
if (isSessionUpgrade) {
IDPSession oldSess = (IDPSession) IDPCache.oldIDPSessionCache.remove(data.getRequestID());
String sessionIndex = IDPSSOUtil.getSessionIndex(data.getSession());
if (StringUtils.isNotEmpty(sessionIndex)) {
IDPCache.idpSessionsByIndices.put(sessionIndex, oldSess);
final FedMonAgent agent = MonitorManager.getAgent();
if (agent != null && agent.isRunning()) {
final FedMonSAML2Svc saml2Svc = MonitorManager.getSAML2Svc();
if (saml2Svc != null) {
saml2Svc.setIdpSessionCount(IDPCache.idpSessionsByIndices.size());
}
}
}
}
if (data.getSession() != null) {
// call multi-federation protocol to set the protocol
MultiProtocolUtils.addFederationProtocol(data.getSession(), SingleLogoutManager.SAML2);
}
// generate assertion response
data.setSpEntityID(data.getAuthnRequest().getIssuer().getValue());
NameIDPolicy policy = data.getAuthnRequest().getNameIDPolicy();
String nameIDFormat = (policy == null) ? null : policy.getFormat();
try {
IDPSSOUtil.sendResponseToACS(request, response, out, data.getSession(), data.getAuthnRequest(), data.getSpEntityID(), data.getIdpEntityID(), data.getIdpMetaAlias(), data.getRealm(), nameIDFormat, data.getRelayState(), data.getMatchingAuthnContext());
} catch (SAML2Exception se) {
SAML2Utils.debug.error(classMethod + "Unable to do sso or federation.", se);
throw new ServerFaultException(data.getIdpAdapter(), SSO_OR_FEDERATION_ERROR, se.getMessage());
}
}
use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class IDPSessionListener method sessionInvalidated.
/**
* Callback for SessionListener.
* It is used for cleaning up the IDP session cache.
*
* @param session The session object
*/
public void sessionInvalidated(Object session) {
String classMethod = "IDPSessionListener.sessionInvalidated: ";
HashMap paramsMap = new HashMap();
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Entering ...");
}
if (session == null) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Session is null.");
}
return;
}
try {
SessionProvider sessionProvider = SessionManager.getProvider();
String[] values = sessionProvider.getProperty(session, SAML2Constants.IDP_SESSION_INDEX);
if (values == null || values.length == 0) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "No sessionIndex stored in session.");
}
return;
}
String sessionIndex = values[0];
if (sessionIndex == null || sessionIndex.length() == 0) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "No sessionIndex stored in session.");
}
return;
}
IDPSession idpSession = (IDPSession) IDPCache.idpSessionsByIndices.get(sessionIndex);
if (idpSession != null) {
paramsMap.put(SAML2Constants.ROLE, SAML2Constants.IDP_ROLE);
String metaAlias = idpSession.getMetaAlias();
String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
String idpEntityID = sm.getEntityByMetaAlias(metaAlias);
try {
List list = (List) idpSession.getNameIDandSPpairs();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
NameIDandSPpair pair = (NameIDandSPpair) iter.next();
String spEntityID = pair.getSPEntityID();
NameID nameID = pair.getNameID();
BaseConfigType idpConfig = sm.getIDPSSOConfig(realm, idpEntityID);
if (idpConfig != null) {
List idpSessionSyncList = (List) SAML2MetaUtils.getAttributes(idpConfig).get(SAML2Constants.IDP_SESSION_SYNC_ENABLED);
if ((idpEntityID != null && spEntityID != null && idpSessionSyncList != null && idpSessionSyncList.size() != 0)) {
boolean idpSessionSyncEnabled = ((String) idpSessionSyncList.get(0)).equals(SAML2Constants.TRUE) ? true : false;
// Sync flag is enabled
if (idpSessionSyncEnabled) {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "IDP Session Synchronization flag " + "is enabled, initiating SLO to SP");
}
initiateIDPSingleLogout(sessionIndex, metaAlias, realm, SAML2Constants.SOAP, nameID, spEntityID, paramsMap);
}
}
} else {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "Unable to retrieve the IDP " + "config data, idpConfig is null");
}
}
}
} catch (SAML2MetaException sme) {
SAML2Utils.debug.error("IDPSessionListener.sessionInvalidated:", sme);
} catch (SAML2Exception se) {
SAML2Utils.debug.error("IDPSessionListener.sessionInvalidated:", se);
} catch (SessionException s) {
SAML2Utils.debug.error("IDPSessionListener.sessionInvalidated:", s);
}
synchronized (IDPCache.idpSessionsByIndices) {
List list = (List) idpSession.getNameIDandSPpairs();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
NameIDandSPpair pair = (NameIDandSPpair) iter.next();
NameID nameID = pair.getNameID();
if (SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameID.getFormat())) {
IDPCache.userIDByTransientNameIDValue.remove(nameID.getValue());
}
}
}
} else {
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "IDP Session with session index " + sessionIndex + " already removed.");
}
}
IDPCache.idpSessionsByIndices.remove(sessionIndex);
IDPCache.authnContextCache.remove(sessionIndex);
String sessID = sessionProvider.getSessionID(session);
if (IDPCache.idpSessionsBySessionID.get(sessID) != null) {
IDPCache.idpSessionsBySessionID.remove(sessID);
if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsBySessionID.size());
}
}
if (IDPCache.spSessionPartnerBySessionID.get(sessID) != null) {
IDPCache.spSessionPartnerBySessionID.remove(sessID);
}
// This failing should not cause the whole process to fail
try {
if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
SAML2FailoverUtils.deleteSAML2Token(sessionIndex);
}
} catch (SAML2TokenRepositoryException se) {
SAML2Utils.debug.error(classMethod + "SAML2 Token Repository error, sessionIndex:" + sessionIndex, se);
}
if (SAML2Utils.debug.messageEnabled()) {
SAML2Utils.debug.message(classMethod + "cleaned up the IDP session cache for a session expiring or being destroyed: sessionIndex=" + sessionIndex);
}
} catch (SessionException e) {
if (SAML2Utils.debug.warningEnabled()) {
SAML2Utils.debug.warning(classMethod + "invalid or expired session.", e);
}
} catch (SAML2MetaException samlme) {
if (SAML2Utils.debug.warningEnabled()) {
SAML2Utils.debug.warning(classMethod + "unable to retrieve idp entity id.", samlme);
}
}
}
use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class LogoutUtil method setSessionIndex.
static void setSessionIndex(Status status, List sessionIndex) {
try {
StatusDetail sd = ProtocolFactory.getInstance().createStatusDetail();
status.setStatusDetail(sd);
if (sessionIndex != null && !sessionIndex.isEmpty()) {
List details = new ArrayList();
for (Iterator iter = sessionIndex.iterator(); iter.hasNext(); ) {
String si = (String) iter.next();
SessionIndex sIndex = ProtocolFactory.getInstance().createSessionIndex(si);
details.add(sIndex.toXMLString(true, true));
}
sd.setAny(details);
}
} catch (SAML2Exception e) {
debug.error("LogoutUtil.setSessionIndex: ", e);
}
}
use of com.sun.identity.saml2.protocol.SessionIndex in project OpenAM by OpenRock.
the class SAML2 method handleReturnFromRedirect.
/**
* Once we're back from the ACS, we need to validate that we have not errored during the proxying process.
* Then we detect if we need to perform a local linking authentication chain, or if the user is already
* locally linked, we need to look up the already-linked username.
*/
private int handleReturnFromRedirect(final int state, final HttpServletRequest request, final String spName, final HttpServletResponse response) throws AuthLoginException {
//first make sure to delete the cookie
removeCookiesForRedirects(request, response);
if (Boolean.parseBoolean(request.getParameter(SAML2Proxy.ERROR_PARAM_KEY))) {
return handleRedirectError(request);
}
final String key;
if (request.getParameter("jsonContent") != null) {
key = JsonValueBuilder.toJsonValue(request.getParameter("jsonContent")).get("responsekey").asString();
} else {
key = request.getParameter(SAML2Proxy.RESPONSE_KEY);
}
final String username;
SAML2ResponseData data = null;
if (!StringUtils.isBlank(key)) {
data = (SAML2ResponseData) SAML2Store.getTokenFromStore(key);
}
if (data == null && SAML2FailoverUtils.isSAML2FailoverEnabled() && !StringUtils.isBlank(key)) {
try {
data = (SAML2ResponseData) SAML2FailoverUtils.retrieveSAML2Token(key);
} catch (SAML2TokenRepositoryException e) {
return processError(bundle.getString("samlFailoverError"), "SAML2.handleReturnFromRedirect : Error reading from failover map.", e);
}
}
if (data == null) {
return processError(bundle.getString("localLinkError"), "SAML2 :: handleReturnFromRedirect() : " + "Unable to perform local linking - response data key not found");
}
storageKey = key;
assertionSubject = data.getSubject();
authnAssertion = data.getAssertion();
sessionIndex = data.getSessionIndex();
respInfo = data.getResponseInfo();
try {
//you're already linked or we auto looked up user
username = SPACSUtils.getPrincipalWithoutLogin(assertionSubject, authnAssertion, realm, spName, metaManager, entityName, storageKey);
if (SAML2PluginsUtils.isDynamicProfile(realm)) {
String spEntityId = SPSSOFederate.getSPEntityId(metaAlias);
if (shouldPersistNameID(spEntityId)) {
NameIDInfo info = new NameIDInfo(spEntityId, entityName, getNameId(), SAML2Constants.SP_ROLE, false);
setUserAttributes(AccountUtils.convertToAttributes(info, null));
}
}
if (username != null) {
principal = new SAML2Principal(username);
return success(authnAssertion, getNameId(), username);
}
} catch (SAML2Exception e) {
return processError(e, null, "SAML2.handleReturnFromRedirect : Unable to perform user lookup.");
}
if (StringUtils.isBlank(localChain)) {
return processError(bundle.getString("localLinkError"), "SAML2 :: handleReturnFromRedirect() : " + "Unable to perform local linking - local auth chain not found.");
}
//generate a sub-login context, owned by this module, and start login sequence to it
authenticationContext = new AuthContext(realm);
authenticationContext.login(AuthContext.IndexType.SERVICE, localChain, null, null, null, null);
return injectCallbacks(null, state);
}
Aggregations